Skip to content

🤯 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.

✨ feat(memory): rules sheet — scalable agent switcher, sort by times checked, positive/negative direction (#20383)

Arvin Xu0b66b5dab890
diff --git a/apps/server/src/routers/lambda/expertise.ts b/apps/server/src/routers/lambda/expertise.ts
index 3929eeed1b8..c2ca844c4a8 100644
--- a/apps/server/src/routers/lambda/expertise.ts
+++ b/apps/server/src/routers/lambda/expertise.ts
@@ -1,4 +1,4 @@
-import { EXPERTISE_ENFORCEMENTS } from '@lobechat/types';
+import { EXPERTISE_ENFORCEMENTS, EXPERTISE_RULE_DIRECTIONS } from '@lobechat/types';
import { z } from 'zod';
import {
@@ -15,7 +15,11 @@ import {
ExpertiseDomainService,
} from '@/server/services/expertise/domain';
import { ExpertiseIngestionService } from '@/server/services/expertise/ingestion';
-import { DraftRuleInputSchema, ExpertiseRuleDraftService } from '@/server/services/expertise/rules';
+import {
+ DraftRuleInputSchema,
+ ExpertiseRuleDraftService,
+ RULE_DIRECTION_BATCH,
+} from '@/server/services/expertise/rules';
import { ExpertiseHistoryWorkflow } from '@/server/workflows/expertiseHistory';
/**
@@ -266,6 +270,17 @@ export const expertiseRouter = router({
.input(DraftRuleInputSchema)
.mutation(async ({ ctx, input }) => ctx.expertiseRuleDraftService.draftRule(input)),
+ /**
+ * Settles which way the named unjudged rules push the work, one bounded batch per call. The
+ * page names the batch from the list it read; a rule the reviewer already set is never
+ * overwritten.
+ */
+ judgeRuleDirections: expertiseWriteProcedure
+ .input(z.object({ lessonIds: z.array(z.string()).min(1).max(RULE_DIRECTION_BATCH) }))
+ .mutation(async ({ ctx, input }) =>
+ ctx.expertiseRuleDraftService.judgeDirections(input.lessonIds),
+ ),
+
/** 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) }))
@@ -278,6 +293,7 @@ export const expertiseRouter = router({
// `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(),
+ direction: z.enum(EXPERTISE_RULE_DIRECTIONS).optional(),
enforcement: z.enum(EXPERTISE_ENFORCEMENTS).optional(),
how: z.string().max(8000).optional(),
limits: z.string().max(4000).optional(),
@@ -293,6 +309,7 @@ export const expertiseRouter = router({
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(),
+ direction: z.enum(EXPERTISE_RULE_DIRECTIONS).optional(),
enforcement: z.enum(EXPERTISE_ENFORCEMENTS).optional(),
lessonId: z.string(),
reasonKind: z.enum(['mechanism', 'taste']).optional(),
diff --git a/apps/server/src/services/expertise/rules.test.ts b/apps/server/src/services/expertise/rules.test.ts
index 2d1fc3c8d72..2cb67f0be66 100644
--- a/apps/server/src/services/expertise/rules.test.ts
+++ b/apps/server/src/services/expertise/rules.test.ts
@@ -3,7 +3,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { DraftRuleInputSchema, ExpertiseRuleDraftService } from './rules';
-const { resolveExpertiseModelConfig } = vi.hoisted(() => ({
+const { fillLessonDirections, listRules, resolveExpertiseModelConfig } = vi.hoisted(() => ({
+ fillLessonDirections: vi.fn(),
+ listRules: vi.fn(),
resolveExpertiseModelConfig: vi.fn(),
}));
const generateObject = vi.fn();
@@ -14,6 +16,12 @@ vi.mock('@/server/services/aiGeneration', () => ({
},
}));
vi.mock('./modelConfig', () => ({ resolveExpertiseModelConfig }));
+vi.mock('@/database/models/expertise', () => ({
+ ExpertiseModel: class {
+ fillLessonDirections = fillLessonDirections;
+ listRules = listRules;
+ },
+}));
const groups = [
{ gate: '去掉页面名之后还成立吗?', id: 'g-taste', title: '我的交付审美' },
@@ -29,6 +37,7 @@ describe('ExpertiseRuleDraftService', () => {
it('drafts one rule and keeps a group id only when the reviewer has that group', async () => {
generateObject.mockResolvedValue({
compilability: 'compilable',
+ direction: 'positive',
enforcement: 'block',
groupId: 'g-design',
how: ' 样式里出现 #fff 或 12px ',
@@ -45,6 +54,7 @@ describe('ExpertiseRuleDraftService', () => {
expect(draft).toEqual({
compilability: 'compilable',
+ direction: 'positive',
enforcement: 'block',
groupId: 'g-design',
how: '样式里出现 #fff 或 12px',
@@ -63,6 +73,7 @@ describe('ExpertiseRuleDraftService', () => {
it('drops a group id the reviewer does not have and keeps the proposed group', async () => {
generateObject.mockResolvedValue({
compilability: 'not-compilable',
+ direction: 'negative',
enforcement: 'remind',
groupId: 'g-invented',
how: null,
@@ -84,6 +95,7 @@ describe('ExpertiseRuleDraftService', () => {
it('never hands back a draft that claims to be compiled already', async () => {
generateObject.mockResolvedValue({
compilability: 'compiled',
+ direction: 'positive',
enforcement: 'remind',
groupId: 'g-design',
how: null,
@@ -128,3 +140,87 @@ describe('ExpertiseRuleDraftService', () => {
);
});
});
+
+describe('ExpertiseRuleDraftService.judgeDirections', () => {
+ const rule = (id: string, extra: Record<string, unknown> = {}) => ({
+ direction: null,
+ id,
+ status: 'active',
+ title: `规矩 ${id}`,
+ ...extra,
+ });
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resolveExpertiseModelConfig.mockResolvedValue({ model: 'm', provider: 'p' });
+ });
+
+ it('judges only the named active rules without a direction and writes the answers', async () => {
+ listRules.mockResolvedValue([
+ {
+ rules: [
+ rule('a'),
+ rule('b', { direction: 'negative' }),
+ rule('c', { status: 'retired' }),
+ rule('d'),
+ // Unjudged but not in this batch: left for a later call.
+ rule('e'),
+ ],
+ },
+ ]);
+ generateObject.mockResolvedValue({
+ rules: [
+ { direction: 'positive', id: 'a' },
+ { direction: 'negative', id: 'd' },
+ ],
+ });
+
+ const result = await new ExpertiseRuleDraftService({} as never, 'user_1').judgeDirections([
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ ]);
+
+ const [params, options] = generateObject.mock.calls[0];
+ expect(params.schema.name).toBe('expertise_rule_direction');
+ expect(params.messages[1].content).toBe('- a · 规矩 a\n- d · 规矩 d');
+ expect(options.tracing.scenario).toBe('expertise_rule_direction');
+ expect(fillLessonDirections).toHaveBeenCalledWith([
+ { direction: 'positive', id: 'a' },
+ { direction: 'negative', id: 'd' },
+ ]);
+ expect(result).toEqual({ judged: 2 });
+ });
+
+ it('drops ids outside the batch and repeated answers', async () => {
+ listRules.mockResolvedValue([{ rules: [rule('a'), rule('b')] }]);
+ generateObject.mockResolvedValue({
+ rules: [
+ { direction: 'positive', id: 'a' },
+ { direction: 'negative', id: 'a' },
+ { direction: 'negative', id: 'someone-else' },
+ ],
+ });
+
+ const result = await new ExpertiseRuleDraftService({} as never, 'user_1').judgeDirections([
+ 'a',
+ 'b',
+ ]);
+
+ expect(fillLessonDirections).toHaveBeenCalledWith([{ direction: 'positive', id: 'a' }]);
+ expect(result).toEqual({ judged: 1 });
+ });
+
+ it('does not call the model when every rule already has a direction', async () => {
+ listRules.mockResolvedValue([{ rules: [rule('a', { direction: 'positive' })] }]);
+
+ const result = await new ExpertiseRuleDraftService({} as never, 'user_1').judgeDirections([
+ 'a',
+ 'not-on-this-page',
+ ]);
+
+ expect(generateObject).not.toHaveBeenCalled();
+ expect(result).toEqual({ judged: 0 });
+ });
+});
diff --git a/apps/server/src/services/expertise/rules.ts b/apps/server/src/services/expertise/rules.ts
index a8f7a65eea8..2f7ff56eb51 100644
--- a/apps/server/src/services/expertise/rules.ts
+++ b/apps/server/src/services/expertise/rules.ts
@@ -1,15 +1,19 @@
import { TRACING_SCENARIOS } from '@lobechat/const';
import {
+ chainExpertiseRuleDirection,
chainExpertiseRuleDraft,
chainExpertiseRuleGroupDraft,
+ EXPERTISE_RULE_DIRECTION_JSON_SCHEMA,
+ EXPERTISE_RULE_DIRECTION_PROMPT_VERSION,
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 { EXPERTISE_RULE_DIRECTIONS, RequestTrigger } from '@lobechat/types';
import { z } from 'zod';
+import { ExpertiseModel } from '@/database/models/expertise';
import type { LobeChatDatabase } from '@/database/type';
import { AiGenerationService } from '@/server/services/aiGeneration';
@@ -26,6 +30,7 @@ export const RuleDraftSchema = z.object({
compilability: z
.enum(['compiled', 'compilable', 'not-compilable'])
.transform((value) => (value === 'compiled' ? 'compilable' : value)),
+ direction: z.enum(EXPERTISE_RULE_DIRECTIONS),
enforcement: z.enum(['block', 'remind']),
groupId: z.string().nullable(),
how: nullableText,
@@ -41,6 +46,16 @@ export const RuleGroupDraftSchema = z.object({
title: z.string().min(1).max(60),
});
+const RuleDirectionsSchema = z.object({
+ rules: z.array(z.object({ direction: z.enum(EXPERTISE_RULE_DIRECTIONS), id: z.string() })),
+});
+
+/**
+ * How many unjudged rules one call settles. Titles are a sentence each, so a batch this size is
+ * one small request; the page asks again while any remain.
+ */
+export const RULE_DIRECTION_BATCH = 40;
+
export type RuleDraft = z.infer<typeof RuleDraftSchema>;
export type RuleGroupDraft = z.infer<typeof RuleGroupDraftSchema>;
@@ -99,6 +114,55 @@ export class ExpertiseRuleDraftService {
return { ...draft, groupId, newGroup: groupId ? null : draft.newGroup };
};
+ /**
+ * Judges the direction of the rules the page asked about and writes it. The caller names the
+ * batch so it decides what is asked and never sends a rule twice; of those ids, only active
+ * rules on this reviewer's page that still have no direction are judged, and ids the model
+ * returns outside the batch are dropped, so a slip can only touch rules this reviewer can see.
+ */
+ judgeDirections = async (lessonIds: string[]): Promise<{ judged: number }> => {
+ const model = new ExpertiseModel(this.db, this.userId, this.workspaceId);
+ const groups = await model.listRules();
+ const asked = new Set(lessonIds);
+ const batch = groups
+ .flatMap((group) => group.rules)
+ .filter((rule) => asked.has(rule.id) && rule.status === 'active' && !rule.direction)
+ .slice(0, RULE_DIRECTION_BATCH);
+ if (batch.length === 0) return { judged: 0 };
+
+ const modelConfig = await resolveExpertiseModelConfig(this.db, this.userId);
+ const ai = new AiGenerationService(this.db, this.userId, this.workspaceId);
+ const { rules } = RuleDirectionsSchema.parse(
+ await ai.generateObject(
+ {
+ ...chainExpertiseRuleDirection({
+ rules: batch.map((rule) => ({ id: rule.id, title: rule.title })),
+ }),
+ ...modelConfig,
+ schema: EXPERTISE_RULE_DIRECTION_JSON_SCHEMA,
+ },
+ {
+ metadata: { trigger: RequestTrigger.Expertise },
+ tracing: {
+ promptVersion: EXPERTISE_RULE_DIRECTION_PROMPT_VERSION,
+ scenario: TRACING_SCENARIOS.ExpertiseRuleDirection,
+ schemaName: EXPERTISE_RULE_DIRECTION_JSON_SCHEMA.name,
+ },
+ },
+ ),
+ );
+
+ // First answer per id wins; ids outside the batch are dropped.
+ const judgedById = new Map<string, (typeof rules)[number]>();
+ for (const rule of rules) {
+ if (batch.some(({ id }) => id === rule.id) && !judgedById.has(rule.id))
+ judgedById.set(rule.id, rule);
+ }
+ const judged = [...judgedById.values()];
+ await model.fillLessonDirections(judged);
+ return { judged: judged.length };
+ };
+
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);
diff --git a/locales/en-US/memory.json b/locales/en-US/memory.json
index f670b9a033c..b5f97b16156 100644
--- a/locales/en-US/memory.json
+++ b/locales/en-US/memory.json
@@ -104,10 +104,14 @@
"rules.archived.group": "Archived ({{count}})",
"rules.archived.mergedInto": "merged into \"{{title}}\"",
"rules.columns.code": "No.",
+ "rules.columns.direction": "Direction",
"rules.columns.enforcement": "Effect",
"rules.columns.method": "Check",
"rules.columns.rule": "Rule",
"rules.columns.runs": "Checked",
+ "rules.columns.runsSort.asc": "Fewest checked first — click to restore your order",
+ "rules.columns.runsSort.desc": "Most checked first — click for fewest first",
+ "rules.columns.runsSort.off": "Sort by times 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?",
@@ -131,6 +135,13 @@
"rules.compose.submit": "Save",
"rules.compose.titlePlaceholder": "The rule in one sentence",
"rules.compose.why": "Why it matters (optional)",
+ "rules.direction.negative": "Negative",
+ "rules.direction.negativeDesc": "Names what gets a delivery sent back",
+ "rules.direction.positive": "Positive",
+ "rules.direction.positiveDesc": "Guides the work toward something good",
+ "rules.direction.unset": "Not judged yet",
+ "rules.direction.unsetArchivedDesc": "Archived before its direction was recorded",
+ "rules.direction.unsetDesc": "Being judged — or pick one yourself",
"rules.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",
@@ -175,6 +186,7 @@
"rules.labOff.title": "Self-evolving 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.direction": "Direction",
"rules.meta.enforcement": "Effect",
"rules.meta.method": "Check",
"rules.meta.origin": "Origin",
@@ -207,6 +219,7 @@
"rules.origin.oneOff": "Looks like a request about that one delivery; it becomes a standing rule once another delivery is sent back for it",
"rules.origin.overSpecific": "Looks tied to one page; may belong in a broader rule",
"rules.origin.taught": "You taught it to this agent",
+ "rules.owner.agents": "Agents",
"rules.owner.mine": "My rules",
"rules.owner.untitledAgent": "Untitled agent",
"rules.reason.inferred": "inferred, you never said it",
diff --git a/locales/zh-CN/memory.json b/locales/zh-CN/memory.json
index 58441b36a6a..90c90f2e423 100644
--- a/locales/zh-CN/memory.json
+++ b/locales/zh-CN/memory.json
@@ -104,10 +104,14 @@
"rules.archived.group": "已归档({{count}})",
"rules.archived.mergedInto": "并入了「{{title}}」",
"rules.columns.code": "编号",
+ "rules.columns.direction": "方向",
"rules.columns.enforcement": "效力",
"rules.columns.method": "验法",
"rules.columns.rule": "规矩",
"rules.columns.runs": "检查过",
+ "rules.columns.runsSort.asc": "检查最少的在前,再点一次恢复你的排序",
+ "rules.columns.runsSort.desc": "检查最多的在前,再点一次改为最少的在前",
+ "rules.columns.runsSort.off": "按检查次数排序",
"rules.compose.back": "返回",
"rules.compose.blank": "自己写",
"rules.compose.describeHint": "写之前先想一下:去掉页面名、组件名、这次的任务名,它还成立吗?",
@@ -131,6 +135,13 @@
"rules.compose.submit": "记下",
"rules.compose.titlePlaceholder": "一句话说清这条规矩",
"rules.compose.why": "为什么这样要求(可不填)",
+ "rules.direction.negative": "负向",
+ "rules.direction.negativeDesc": "出现就会被打回",
+ "rules.direction.positive": "正向",
+ "rules.direction.positiveDesc": "往好的方向引导",
+ "rules.direction.unset": "还没判定",
+ "rules.direction.unsetArchivedDesc": "归档时还没有记录方向",
+ "rules.direction.unsetDesc": "正在判定,也可以自己选",
"rules.enforcement.block": "拦",
"rules.enforcement.blockDesc": "将拦下交付,直到你放行。尚未生效,目前仍只提醒",
"rules.enforcement.blockHint": "拦:将拦下交付(尚未生效,目前仍只提醒)。点一下改成提醒",
@@ -175,6 +186,7 @@
"rules.labOff.title": "「自进化」还在实验室里",
"rules.merge.banner": "点一条要并进去的规矩——「{{title}}」会归档,它的来源和次数记到目标上。",
"rules.merge.cancel": "取消",
+ "rules.meta.direction": "方向",
"rules.meta.enforcement": "效力",
"rules.meta.method": "验法",
"rules.meta.origin": "来历",
@@ -207,6 +219,7 @@
"rules.origin.oneOff": "看起来是针对那一次交付的具体意见,再有一次交付因它被打回,才算通用规矩",
"rules.origin.overSpecific": "看起来只对某个页面成立,可能该并进更通用的那条",
"rules.origin.taught": "你教给它的",
+ "rules.owner.agents": "Agent 学到的",
"rules.owner.mine": "我的规矩",
"rules.owner.untitledAgent": "未命名 Agent",
"rules.reason.inferred": "推断出来的,你没说过",
diff --git a/packages/const/src/llmGenerationTracing.ts b/packages/const/src/llmGenerationTracing.ts
index 6aa0360a0c1..3102768b7b8 100644
--- a/packages/const/src/llmGenerationTracing.ts
+++ b/packages/const/src/llmGenerationTracing.ts
@@ -14,6 +14,7 @@ export const TRACING_SCENARIOS = {
ExpertiseConsolidation: 'expertise_consolidation',
ExpertiseDomainDraft: 'expertise_domain_draft',
ExpertiseRejectionIngestion: 'expertise_rejection_ingestion',
+ ExpertiseRuleDirection: 'expertise_rule_direction',
ExpertiseRuleDraft: 'expertise_rule_draft',
ExpertiseRuleGroupDraft: 'expertise_rule_group_draft',
ExpertiseTopicIngestion: 'expertise_topic_ingestion',
diff --git a/packages/database/src/models/__tests__/expertise.test.ts b/packages/database/src/models/__tests__/expertise.test.ts
index 8980892341e..e7278b532c1 100644
--- a/packages/database/src/models/__tests__/expertise.test.ts
+++ b/packages/database/src/models/__tests__/expertise.test.ts
@@ -596,6 +596,30 @@ describe('ExpertiseModel', () => {
expect(await model.createRule({ domainId: 'rules-foreign-domain', title: 'x' })).toBeNull();
});
+ it('fills judged directions only on rules that have none', async () => {
+ const { first, second } = await seedRuleGroup();
+ const model = new ExpertiseModel(serverDB, userId);
+ const created = await model.createRule({
+ direction: 'negative',
+ domainId: 'rules-domain',
+ title: '非链接控件不要套蓝色链接样式',
+ });
+
+ // The reviewer flipped one while the judgment was in flight; their choice stands.
+ await model.updateLessonFields(second, { direction: 'positive' });
+ await model.fillLessonDirections([
+ { direction: 'positive', id: first },
+ { direction: 'negative', id: second },
+ { direction: 'positive', id: created!.id },
+ ]);
+
+ const [group] = await model.listRules();
+ const directionOf = (id: string) => group.rules.find((rule) => rule.id === id)?.direction;
+ expect(directionOf(first)).toBe('positive');
+ expect(directionOf(second)).toBe('positive');
+ expect(directionOf(created!.id)).toBe('negative');
+ });
+
it('versions a rewording but not a switch flip', async () => {
const { first } = await seedRuleGroup();
const model = new ExpertiseModel(serverDB, userId);
diff --git a/packages/database/src/models/expertise.ts b/packages/database/src/models/expertise.ts
index 4318bb766c2..b01c1c231b6 100644
--- a/packages/database/src/models/expertise.ts
+++ b/packages/database/src/models/expertise.ts
@@ -1,9 +1,11 @@
-import type {
- ExpertiseAnchorCandidate,
- ExpertiseCanonEntry,
- ExpertiseEnforcement,
- ExpertiseLayerDefinition,
- ExpertiseLessonSection,
+import {
+ EXPERTISE_RULE_DIRECTIONS,
+ type ExpertiseAnchorCandidate,
+ type ExpertiseCanonEntry,
+ type ExpertiseEnforcement,
+ type ExpertiseLayerDefinition,
+ type ExpertiseLessonSection,
+ type ExpertiseRuleDirection,
} from '@lobechat/types';
import { and, asc, desc, eq, inArray, isNotNull, isNull, or, type SQL, sql } from 'drizzle-orm';
@@ -230,6 +232,8 @@ export class ExpertiseModel {
compilability: expertiseLessons.compilability,
createdAt: expertiseLessons.createdAt,
createdByUserId: expertiseLessons.createdByUserId,
+ // Null until judged; the page asks for the unjudged ones to be settled.
+ direction: expertiseLessons.direction,
domainId: expertiseLessons.domainId,
originRunId: expertiseLessons.originRunId,
// Rows that predate the column hold null; they have only ever been reminders.
@@ -1111,6 +1115,7 @@ export class ExpertiseModel {
*/
createRule = async (params: {
compilability?: 'compilable' | 'not-compilable';
+ direction?: ExpertiseRuleDirection;
domainId: string;
enforcement?: ExpertiseEnforcement;
how?: string;
@@ -1139,6 +1144,7 @@ export class ExpertiseModel {
code,
compilability: params.compilability ?? 'not-compilable',
createdByUserId: this.userId,
+ direction: params.direction ?? null,
domainId: params.domainId,
enforcement: params.enforcement ?? 'remind',
polarity: 'rule',
@@ -1185,6 +1191,21 @@ export class ExpertiseModel {
.where(eq(expertiseLessons.id, lessonId));
};
+ /**
+ * Writes judged directions onto rules that still have none. A rule the reviewer flipped while
+ * the judgment was in flight keeps their choice: only null rows are filled.
+ */
+ fillLessonDirections = async (judged: { direction: ExpertiseRuleDirection; id: string }[]) => {
+ for (const direction of EXPERTISE_RULE_DIRECTIONS) {
+ const ids = judged.filter((rule) => rule.direction === direction).map((rule) => rule.id);
+ if (ids.length === 0) continue;
+ await this.db
+ .update(expertiseLessons)
+ .set({ direction, updatedAt: new Date() })
+ .where(and(inArray(expertiseLessons.id, ids), isNull(expertiseLessons.direction)));
+ }
+ };
+
/**
* 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.
diff --git a/packages/database/src/repositories/expertiseRules/index.ts b/packages/database/src/repositories/expertiseRules/index.ts
index 6888c7d6c07..baba20a59ac 100644
--- a/packages/database/src/repositories/expertiseRules/index.ts
+++ b/packages/database/src/repositories/expertiseRules/index.ts
@@ -2,6 +2,7 @@ import type {
ExpertiseEnforcement,
ExpertiseLessonSection,
ExpertiseReasonKind,
+ ExpertiseRuleDirection,
} from '@lobechat/types';
import { ExpertiseModel } from '../../models/expertise';
@@ -11,6 +12,7 @@ export type RuleSectionPatch = Partial<Record<'rule' | 'why' | 'how' | 'limits',
export interface UpdateRulePatch {
compilability?: 'compilable' | 'not-compilable';
+ direction?: ExpertiseRuleDirection;
enforcement?: ExpertiseEnforcement;
reasonKind?: ExpertiseReasonKind;
sections?: RuleSectionPatch;
@@ -38,7 +40,7 @@ export class ExpertiseRuleRepository {
* 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.
+ * direction, compilability, reason kind) are not versioned: they are settings, not judgments.
*/
updateRule = async (lessonId: string, patch: UpdateRulePatch) =>
this.inTransaction(async (model) => {
@@ -89,6 +91,7 @@ export class ExpertiseRuleRepository {
}
await model.updateLessonFields(lessonId, {
...(patch.compilability && { compilability: patch.compilability }),
+ ...(patch.direction && { direction: patch.direction }),
...(patch.enforcement && { enforcement: patch.enforcement }),
...(patch.reasonKind && { reasonKind: patch.reasonKind }),
...(titleChanged && { title }),
diff --git a/packages/locales/src/default/memory.ts b/packages/locales/src/default/memory.ts
index 9ba9804655b..2b0f8843d0d 100644
--- a/packages/locales/src/default/memory.ts
+++ b/packages/locales/src/default/memory.ts
@@ -113,10 +113,14 @@ export default {
'rules.archived.group': 'Archived ({{count}})',
'rules.archived.mergedInto': 'merged into "{{title}}"',
'rules.columns.code': 'No.',
+ 'rules.columns.direction': 'Direction',
'rules.columns.enforcement': 'Effect',
'rules.columns.method': 'Check',
'rules.columns.rule': 'Rule',
'rules.columns.runs': 'Checked',
+ 'rules.columns.runsSort.asc': 'Fewest checked first — click to restore your order',
+ 'rules.columns.runsSort.desc': 'Most checked first — click for fewest first',
+ 'rules.columns.runsSort.off': 'Sort by times checked',
'rules.compose.back': 'Back',
'rules.compose.blank': 'Write it myself',
'rules.compose.describeHint':
@@ -142,6 +146,13 @@ export default {
'rules.compose.submit': 'Save',
'rules.compose.titlePlaceholder': 'The rule in one sentence',
'rules.compose.why': 'Why it matters (optional)',
+ 'rules.direction.negative': 'Negative',
+ 'rules.direction.negativeDesc': 'Names what gets a delivery sent back',
+ 'rules.direction.positive': 'Positive',
+ 'rules.direction.positiveDesc': 'Guides the work toward something good',
+ 'rules.direction.unset': 'Not judged yet',
+ 'rules.direction.unsetArchivedDesc': 'Archived before its direction was recorded',
+ 'rules.direction.unsetDesc': 'Being judged — or pick one yourself',
'rules.enforcement.block': 'Block',
'rules.enforcement.blockDesc':
'Will hold the delivery until you let it through. Not in effect yet: for now it only reminds',
@@ -196,6 +207,7 @@ export default {
'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.direction': 'Direction',
'rules.meta.enforcement': 'Effect',
'rules.meta.method': 'Check',
'rules.meta.origin': 'Origin',
@@ -234,6 +246,7 @@ export default {
'Looks like a request about that one delivery; it becomes a standing rule once another delivery is sent back for it',
'rules.origin.overSpecific': 'Looks tied to one page; may belong in a broader rule',
'rules.origin.taught': 'You taught it to this agent',
+ 'rules.owner.agents': 'Agents',
'rules.owner.mine': 'My rules',
'rules.owner.untitledAgent': 'Untitled agent',
'rules.reason.inferred': 'inferred, you never said it',
diff --git a/packages/prompts/src/chains/expertise.ts b/packages/prompts/src/chains/expertise.ts
index 7fffa3112e5..428bb16629f 100644
--- a/packages/prompts/src/chains/expertise.ts
+++ b/packages/prompts/src/chains/expertise.ts
@@ -113,7 +113,7 @@ export const chainExpertiseDomainDraft = ({
],
});
-export const EXPERTISE_RULE_DRAFT_PROMPT_VERSION = 'v2';
+export const EXPERTISE_RULE_DRAFT_PROMPT_VERSION = 'v3';
/**
* One rule drafted from whatever the reviewer typed or pasted: a sentence, a paragraph, or a
@@ -126,6 +126,7 @@ export const EXPERTISE_RULE_DRAFT_JSON_SCHEMA = {
additionalProperties: false,
properties: {
compilability: { enum: ['compilable', 'not-compilable'], type: 'string' },
+ direction: { enum: ['positive', 'negative'], type: 'string' },
enforcement: { enum: ['block', 'remind'], type: 'string' },
groupId: { type: ['string', 'null'] },
how: { type: ['string', 'null'] },
@@ -144,6 +145,7 @@ export const EXPERTISE_RULE_DRAFT_JSON_SCHEMA = {
},
required: [
'compilability',
+ 'direction',
'enforcement',
'groupId',
'how',
@@ -163,6 +165,7 @@ Return:
- 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;
+- direction: "positive" when the rule steers toward a quality to reach (what good looks like), "negative" when it names a thing that gets a delivery sent back (what must not appear). Judge what the rule asks for, not how the sentence is worded or where it came from;
- 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;
@@ -195,6 +198,56 @@ export const chainExpertiseRuleDraft = ({
],
});
+export const EXPERTISE_RULE_DIRECTION_PROMPT_VERSION = 'v1';
+
+/**
+ * Judges which way each of a batch of existing rules pushes the work. Rules written before the
+ * direction existed, and rules distilled from runs, reach the page without one; this settles
+ * them in one call per batch instead of one per rule.
+ */
+export const EXPERTISE_RULE_DIRECTION_JSON_SCHEMA = {
+ name: 'expertise_rule_direction',
+ schema: {
+ additionalProperties: false,
+ properties: {
+ rules: {
+ items: {
+ additionalProperties: false,
+ properties: {
+ direction: { enum: ['positive', 'negative'], type: 'string' },
+ id: { type: 'string' },
+ },
+ required: ['direction', 'id'],
+ type: 'object',
+ },
+ type: 'array',
+ },
+ },
+ required: ['rules'],
+ type: 'object',
+ },
+} as const satisfies ExpertiseGenerateObjectSchema;
+
+const EXPERTISE_RULE_DIRECTION_SYSTEM_PROMPT = `Each line below is one delivery rule. For every rule decide which way it pushes the work:
+
+- "positive" — it steers toward a quality to reach: what a good delivery has or does ("give empty states a clear purpose", "keep the source view when opening a detail");
+- "negative" — it names a thing that gets a delivery sent back: what must not appear or must not happen ("no blue link styling on controls that are not links", "do not show raw fraction scores").
+
+Judge what the rule asks for, not the grammar: "X instead of Y" is positive when the point is reaching X, negative when the point is ruling out Y. A rule that says both leans the way its first clause does.
+
+Return one entry per rule, with its id copied exactly. Do not skip a rule and do not invent ids.`;
+
+export const chainExpertiseRuleDirection = ({
+ rules,
+}: {
+ rules: { id: string; title: string }[];
+}): { messages: OpenAIChatMessage[] } => ({
+ messages: [
+ { content: EXPERTISE_RULE_DIRECTION_SYSTEM_PROMPT, role: 'system' },
+ { content: rules.map((rule) => `- ${rule.id} · ${rule.title}`).join('\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. */
diff --git a/src/features/MemoryRules/ComposeModal.tsx b/src/features/MemoryRules/ComposeModal.tsx
index 33eff187343..2b7f5e600a8 100644
--- a/src/features/MemoryRules/ComposeModal.tsx
+++ b/src/features/MemoryRules/ComposeModal.tsx
@@ -1,6 +1,10 @@
'use client';
-import type { ExpertiseEnforcement } from '@lobechat/types';
+import {
+ EXPERTISE_RULE_DIRECTIONS,
+ type ExpertiseEnforcement,
+ type ExpertiseRuleDirection,
+} from '@lobechat/types';
import { Flexbox, Icon } from '@lobehub/ui';
import {
ActionIcon,
@@ -33,6 +37,7 @@ import GeneratingBorder from '@/components/GeneratingBorder';
import { expertiseService, type RuleDraft, type RuleGroup } from '@/services/expertise';
import { shinyTextStyles } from '@/styles';
+import { DIRECTION_ICON } from './DirectionToggle';
import { composeStyles, type CreatedGroup, createGroupModal } from './GroupModal';
import { useScopeLabel } from './labels';
@@ -112,6 +117,8 @@ const ComposeContent = ({
const [how, setHow] = useState('');
const [limits, setLimits] = useState('');
const [enforcement, setEnforcement] = useState<ExpertiseEnforcement>('remind');
+ // Left unset when writing by hand: the page judges it afterwards unless the reviewer picks.
+ const [direction, setDirection] = useState<ExpertiseRuleDirection>();
const [compilability, setCompilability] = useState<Compilability>('not-compilable');
const [busy, setBusy] = useState(false);
const [tick, setTick] = useState(0);
@@ -144,6 +151,7 @@ const ComposeContent = ({
setHow(drafted.how ?? '');
setLimits(drafted.limits ?? '');
setEnforcement(drafted.enforcement);
+ setDirection(drafted.direction);
setCompilability(drafted.compilability);
if (drafted.groupId) {
setGroupId(drafted.groupId);
@@ -184,6 +192,7 @@ const ComposeContent = ({
if (!domainId) return;
const created = await expertiseService.createRule({
compilability,
+ direction,
domainId,
enforcement,
how: how.trim() || undefined,
@@ -352,6 +361,19 @@ const ComposeContent = ({
<Icon icon={ChevronDownIcon} size={12} />
</span>
</DropdownMenu>
+ <DropdownMenu
+ items={EXPERTISE_RULE_DIRECTIONS.map((value) => ({
+ key: value,
+ label: t(`rules.direction.${value}`),
+ onClick: () => setDirection(value),
+ }))}
+ >
+ <span className={styles.chip}>
+ <Icon icon={DIRECTION_ICON[direction ?? 'unset']} size={13} />
+ {direction ? t(`rules.direction.${direction}`) : t('rules.meta.direction')}
+ <Icon icon={ChevronDownIcon} size={12} />
+ </span>
+ </DropdownMenu>
<DropdownMenu
items={[
{
diff --git a/src/features/MemoryRules/DetailPanel.tsx b/src/features/MemoryRules/DetailPanel.tsx
index 2a35ca1a3e3..e0f6bd2fe04 100644
--- a/src/features/MemoryRules/DetailPanel.tsx
+++ b/src/features/MemoryRules/DetailPanel.tsx
@@ -1,6 +1,10 @@
'use client';
-import type { ExpertiseEnforcement, ExpertiseReasonKind } from '@lobechat/types';
+import {
+ EXPERTISE_RULE_DIRECTIONS,
+ type ExpertiseEnforcement,
+ type ExpertiseReasonKind,
+} from '@lobechat/types';
import { Block, Flexbox, Icon } from '@lobehub/ui';
import {
ActionIcon,
@@ -36,6 +40,7 @@ import RightPanel from '@/features/RightPanel';
import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
import type { RuleGroup, RuleItem, UpdateRuleInput } from '@/services/expertise';
+import { DIRECTION_ICON } from './DirectionToggle';
import Field from './Field';
import { useRuleRevisions, useRuleSources } from './hooks';
import {
@@ -377,6 +382,24 @@ const RuleDocument = ({
)}
</span>
</Property>
+ <Property
+ icon={DIRECTION_ICON[rule.direction ?? 'unset']}
+ label={t('rules.meta.direction')}
+ menu={
+ editable
+ ? choose(
+ EXPERTISE_RULE_DIRECTIONS,
+ (value) => t(`rules.direction.${value}`),
+ (direction) => void save({ direction }),
+ )
+ : undefined
+ }
+ >
+ <Text weight={500}>{t(`rules.direction.${rule.direction ?? 'unset'}`)}</Text>
+ <span className={styles.muted}>
+ {t(`rules.direction.${rule.direction ?? 'unset'}Desc`)}
+ </span>
+ </Property>
<Property
icon={ClipboardCheckIcon}
label={t('rules.meta.method')}
diff --git a/src/features/MemoryRules/DirectionToggle.tsx b/src/features/MemoryRules/DirectionToggle.tsx
new file mode 100644
index 00000000000..ee1ffdcbb57
--- /dev/null
+++ b/src/features/MemoryRules/DirectionToggle.tsx
@@ -0,0 +1,57 @@
+'use client';
+
+import type { ExpertiseRuleDirection } from '@lobechat/types';
+import { Icon } from '@lobehub/ui';
+import { Tooltip } from '@lobehub/ui/base-ui';
+import { cx } from 'antd-style';
+import { BanIcon, CircleDashedIcon, type LucideIcon, SparklesIcon } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { styles } from './styles';
+
+/** Shared with the document's property row, so the sheet and the document read the same. */
+export const DIRECTION_ICON: Record<ExpertiseRuleDirection | 'unset', LucideIcon> = {
+ negative: BanIcon,
+ positive: SparklesIcon,
+ unset: CircleDashedIcon,
+};
+
+interface DirectionToggleProps {
+ disabled?: boolean;
+ onChange: (next: ExpertiseRuleDirection) => void;
+ value?: ExpertiseRuleDirection | null;
+}
+
+/**
+ * The direction column is itself the switch, like the effect column: one click flips
+ * positive ⇄ negative. A rule not judged yet shows a dashed mark; clicking it settles it as
+ * positive, and the reviewer can flip on from there.
+ */
+const DirectionToggle = ({ disabled, onChange, value }: DirectionToggleProps) => {
+ const { t } = useTranslation('memory');
+ const key = value ?? 'unset';
+ // Archived rules are never judged and cannot be switched, so do not promise either.
+ const hint =
+ disabled && !value ? t('rules.direction.unsetArchivedDesc') : t(`rules.direction.${key}Desc`);
+ return (
+ <Tooltip title={hint}>
+ <span
+ className={cx(
+ styles.modeBtn,
+ value === 'positive' && styles.directionPositive,
+ value === 'negative' && styles.directionNegative,
+ !value && styles.modeRemind,
+ )}
+ onClick={(e) => {
+ e.stopPropagation();
+ if (!disabled) onChange(value === 'positive' ? 'negative' : 'positive');
+ }}
+ >
+ <Icon icon={DIRECTION_ICON[key]} size={13} />
+ {value ? t(`rules.direction.${value}`) : '—'}
+ </span>
+ </Tooltip>
+ );
+};
+
+export default DirectionToggle;
diff --git a/src/features/MemoryRules/PartSwitcher.tsx b/src/features/MemoryRules/PartSwitcher.tsx
new file mode 100644
index 00000000000..1fbca49f2e1
--- /dev/null
+++ b/src/features/MemoryRules/PartSwitcher.tsx
@@ -0,0 +1,88 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { Segmented, Select } from '@lobehub/ui/base-ui';
+import { useTranslation } from 'react-i18next';
+
+import { agentSectionsByCount, liveCount, type OwnerSection } from './labels';
+import OwnerLabel from './OwnerLabel';
+import { styles } from './styles';
+import { useAgentToReopen } from './useAgentToReopen';
+
+/** Past this many agents the picker gets a search box; below it, scanning the list is faster. */
+const SEARCH_FROM = 8;
+
+interface PartSwitcherProps {
+ onChange: (key: string) => void;
+ sections: OwnerSection[];
+ value: string;
+}
+
+/**
+ * Whose sheet is on screen, in two steps that both stay one line wide however many agents have
+ * learned something: "My rules" or "Agents" first, then which agent. One segment per agent ran
+ * off the page once there were more than a handful.
+ *
+ * Switching to "Agents" reopens the agent last looked at, or the one that learned the most.
+ */
+const PartSwitcher = ({ onChange, sections, value }: PartSwitcherProps) => {
+ const { t } = useTranslation('memory');
+ const mine = sections.find((section) => section.key === 'mine');
+ const agents = agentSectionsByCount(sections);
+ const reopen = useAgentToReopen(
+ value,
+ agents.map((section) => section.key),
+ );
+
+ const onAgent = value !== 'mine';
+ const agentTotal = agents.reduce((sum, section) => sum + liveCount(section), 0);
+
+ return (
+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>
+ <Segmented
+ value={onAgent ? 'agents' : 'mine'}
+ options={[
+ {
+ label: <OwnerLabel count={mine ? liveCount(mine) : 0} owner={{ kind: 'mine' }} />,
+ value: 'mine',
+ },
+ {
+ label: (
+ <Flexbox horizontal align={'center'} gap={6}>
+ <span>{t('rules.owner.agents')}</span>
+ <span className={styles.ownerCount}>{agentTotal}</span>
+ </Flexbox>
+ ),
+ value: 'agents',
+ },
+ ]}
+ onChange={(next) => {
+ onChange(next === 'mine' ? 'mine' : reopen);
+ }}
+ />
+ {onAgent && (
+ <Select
+ popupMatchSelectWidth={false}
+ showSearch={agents.length >= SEARCH_FROM}
+ style={{ minWidth: 200, width: 'auto' }}
+ value={value}
+ variant={'filled'}
+ options={agents.map((section) => ({
+ label: <OwnerLabel count={liveCount(section)} owner={section.owner} />,
+ // What the search box matches against, since the label is not plain text.
+ title:
+ section.owner.kind === 'agent'
+ ? section.owner.agent.title || t('rules.owner.untitledAgent')
+ : undefined,
+ value: section.key,
+ }))}
+ onChange={(next) => {
+ if (typeof next === 'string') onChange(next);
+ }}
+ />
+ )}
+ </Flexbox>
+ );
+};
+
+export default PartSwitcher;
diff --git a/src/features/MemoryRules/RuleRow.tsx b/src/features/MemoryRules/RuleRow.tsx
index 778a4d370dc..4873b9d1410 100644
--- a/src/features/MemoryRules/RuleRow.tsx
+++ b/src/features/MemoryRules/RuleRow.tsx
@@ -1,6 +1,6 @@
'use client';
-import type { ExpertiseEnforcement } from '@lobechat/types';
+import type { ExpertiseEnforcement, ExpertiseRuleDirection } 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';
@@ -10,6 +10,7 @@ import { useTranslation } from 'react-i18next';
import type { RuleItem } from '@/services/expertise';
+import DirectionToggle from './DirectionToggle';
import EnforcementToggle from './EnforcementToggle';
import { styles } from './styles';
@@ -18,7 +19,10 @@ interface RuleRowProps {
/** Where an archived rule went, when it was folded into another one. */
archivedInto?: string | null;
code: string;
+ /** Off while the sheet is sorted by a column: that order is not the reviewer's to drag. */
+ draggable?: boolean;
menu: DropdownItem[];
+ onDirection: (next: ExpertiseRuleDirection) => void;
onEnforcement: (next: ExpertiseEnforcement) => void;
onSelect: () => void;
rule: RuleItem;
@@ -35,7 +39,9 @@ const RuleRow = ({
active,
archivedInto,
code,
+ draggable = true,
menu,
+ onDirection,
onEnforcement,
onSelect,
rule,
@@ -62,7 +68,7 @@ const RuleRow = ({
onClick={onSelect}
>
<span data-hover className={styles.hover} onClick={(e) => e.stopPropagation()}>
- {!archived && <SortableList.DragHandle size={'small'} />}
+ {!archived && draggable && <SortableList.DragHandle size={'small'} />}
</span>
<span className={styles.cellId}>{code}</span>
<div style={{ minWidth: 0 }}>
@@ -89,6 +95,7 @@ const RuleRow = ({
)}
</Flexbox>
</div>
+ <DirectionToggle disabled={archived} value={rule.direction} onChange={onDirection} />
<EnforcementToggle disabled={archived} value={rule.enforcement} onChange={onEnforcement} />
<span className={styles.muted}>{t(`rules.method.${rule.compilability}`)}</span>
<Tooltip
diff --git a/src/features/MemoryRules/index.tsx b/src/features/MemoryRules/index.tsx
index d3cdd867b11..f226811d2f0 100644
--- a/src/features/MemoryRules/index.tsx
+++ b/src/features/MemoryRules/index.tsx
@@ -1,9 +1,9 @@
'use client';
import { Block, Empty, Flexbox, Icon, SortableList } from '@lobehub/ui';
-import { Button, Segmented, Text, toast } from '@lobehub/ui/base-ui';
+import { Button, Text, toast } from '@lobehub/ui/base-ui';
import { cx } from 'antd-style';
-import { FlaskConicalIcon, PencilIcon, PlusIcon } from 'lucide-react';
+import { ArrowDownIcon, ArrowUpIcon, FlaskConicalIcon, PencilIcon, PlusIcon } from 'lucide-react';
import { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -21,12 +21,20 @@ import DetailPanel from './DetailPanel';
import { createGroupModal } from './GroupModal';
import GroupSection from './GroupSection';
import { useRules } from './hooks';
-import { findMove, mergedIntoId, sectionsByOwner } from './labels';
-import OwnerLabel from './OwnerLabel';
+import {
+ findMove,
+ mergedIntoId,
+ nextRunsSort,
+ type RunsSort,
+ sectionsByOwner,
+ sortByRuns,
+} from './labels';
+import PartSwitcher from './PartSwitcher';
import { buildRuleMenu } from './ruleMenu';
import RuleRow from './RuleRow';
import RulesOnboarding, { type RulesOnboardingAgents } from './RulesOnboarding';
import { styles } from './styles';
+import { useJudgeDirections } from './useJudgeDirections';
const LabOff = () => {
const { t } = useTranslation('memory');
@@ -68,6 +76,7 @@ const MemoryRules = () => {
const [mergeFrom, setMergeFrom] = useState<string>();
const [collapsed, setCollapsed] = useState<Record<string, boolean>>({});
const [partKey, setPartKey] = useState('mine');
+ const [runsSort, setRunsSort] = useState<RunsSort>(null);
const groups = useMemo(() => data?.groups ?? [], [data]);
const sections = useMemo(() => sectionsByOwner(groups), [groups]);
@@ -118,6 +127,12 @@ const MemoryRules = () => {
}
: undefined;
+ useJudgeDirections(
+ enabled,
+ live.filter((rule) => !rule.direction).map((rule) => rule.id),
+ mutate,
+ );
+
// A selection or a merge in progress belongs to the part it started in; switching drops both,
// so a merge can only ever pick a target within its own part.
const switchPart = (key: string) => {
@@ -153,6 +168,7 @@ const MemoryRules = () => {
const updateRule = async (id: string, patch: UpdateRuleInput) => {
try {
if (patch.enforcement) await patchLocal(id, { enforcement: patch.enforcement });
+ if (patch.direction) await patchLocal(id, { direction: patch.direction });
await expertiseService.updateRule(id, patch);
await refresh();
return true;
@@ -258,6 +274,7 @@ const MemoryRules = () => {
<RuleRow
active={rule.id === selectedId}
code={codes.get(rule.id) ?? ''}
+ draggable={!runsSort}
menu={buildRuleMenu(t, rule, sameSection(rule.domainId), handlers)}
rule={rule}
taughtToAgent={part.owner.kind === 'agent'}
@@ -265,6 +282,7 @@ const MemoryRules = () => {
const into = mergedIntoId(rule);
return into ? (all.find((r) => r.id === into)?.title ?? into) : null;
})()}
+ onDirection={(direction) => void updateRule(rule.id, { direction })}
onEnforcement={(enforcement) => void updateRule(rule.id, { enforcement })}
onSelect={() => select(rule.id)}
/>
@@ -307,9 +325,12 @@ const MemoryRules = () => {
) : (
<SortableList
gap={0}
- items={items}
+ items={sortByRuns(items, runsSort)}
renderItem={renderRow}
- onChange={(next) => void reorder(group.domain.id, next)}
+ // A sorted view is not the reviewer's order, so it cannot be dragged into one.
+ onChange={(next) => {
+ if (!runsSort) void reorder(group.domain.id, next);
+ }}
/>
)}
</div>
@@ -330,7 +351,9 @@ const MemoryRules = () => {
<NavHeader />
<Flexbox horizontal flex={1} height={'100%'} width={'100%'}>
<Flexbox className={styles.body}>
- <WideScreenContainer gap={18} paddingBlock={'24px 96px'}>
+ {/* Full width: with direction, effect, check and count columns the sheet needs the
+ room, and a centred reading column only squeezed the rule text. */}
+ <WideScreenContainer fullWidth gap={18} paddingBlock={'24px 96px'} paddingInline={32}>
<Flexbox
horizontal
align={'flex-start'}
@@ -391,24 +414,8 @@ const MemoryRules = () => {
{/* Whose sheet this is: the reviewer's own rules, or one agent's lessons. Only
shown once some agent has learned something, so there is a choice to make. */}
{sections.length > 1 && (
- <Flexbox horizontal paddingBlock={'0 12px'} paddingInline={8}>
- <Segmented
- value={part.key}
- options={sections.map((section) => ({
- label: (
- <OwnerLabel
- owner={section.owner}
- count={
- section.groups
- .flatMap((group) => group.rules)
- .filter((rule) => rule.status === 'active').length
- }
- />
- ),
- value: section.key,
- }))}
- onChange={(value) => switchPart(String(value))}
- />
+ <Flexbox paddingBlock={'0 12px'} paddingInline={8}>
+ <PartSwitcher sections={sections} value={part.key} onChange={switchPart} />
</Flexbox>
)}
{!mineOnboarding && (
@@ -416,9 +423,24 @@ const MemoryRules = () => {
<span />
<span>{t('rules.columns.code')}</span>
<span>{t('rules.columns.rule')}</span>
+ <span>{t('rules.columns.direction')}</span>
<span>{t('rules.columns.enforcement')}</span>
<span>{t('rules.columns.method')}</span>
- <span>{t('rules.columns.runs')}</span>
+ <button
+ aria-pressed={runsSort !== null}
+ title={t(`rules.columns.runsSort.${runsSort ?? 'off'}`)}
+ type={'button'}
+ className={cx(
+ styles.sortHeader,
+ runsSort !== null && styles.sortHeaderActive,
+ )}
+ onClick={() => setRunsSort(nextRunsSort(runsSort))}
+ >
+ {t('rules.columns.runs')}
+ {runsSort && (
+ <Icon icon={runsSort === 'desc' ? ArrowDownIcon : ArrowUpIcon} size={12} />
+ )}
+ </button>
<span />
</div>
)}
@@ -441,7 +463,7 @@ const MemoryRules = () => {
</div>
<SortableList
gap={0}
- items={partArchived}
+ items={sortByRuns(partArchived, runsSort)}
renderItem={renderRow}
onChange={() => {}}
/>
diff --git a/src/features/MemoryRules/labels.test.ts b/src/features/MemoryRules/labels.test.ts
index 380e2d058cf..2e062813e45 100644
--- a/src/features/MemoryRules/labels.test.ts
+++ b/src/features/MemoryRules/labels.test.ts
@@ -3,12 +3,15 @@ import { describe, expect, it } from 'vitest';
import type { RuleGroup } from '@/services/expertise';
import {
+ agentSectionsByCount,
appendException,
findMove,
+ nextRunsSort,
revisionAuthorKey,
ruleOrigin,
sectionBody,
sectionsByOwner,
+ sortByRuns,
} from './labels';
describe('appendException', () => {
@@ -122,3 +125,57 @@ describe('sectionsByOwner', () => {
expect(sections[0]).toMatchObject({ groups: [], key: 'mine' });
});
});
+
+describe('sortByRuns', () => {
+ const rules = [
+ { hitRunCount: 1, id: 'a' },
+ { hitRunCount: 3, id: 'b' },
+ { hitRunCount: 1, id: 'c' },
+ { hitRunCount: 0, id: 'd' },
+ ];
+
+ it("leaves the reviewer's own order alone when the sort is off", () => {
+ expect(sortByRuns(rules, null)).toBe(rules);
+ });
+
+ it('puts the most-checked first and keeps ties in their own order', () => {
+ expect(sortByRuns(rules, 'desc').map((rule) => rule.id)).toEqual(['b', 'a', 'c', 'd']);
+ });
+
+ it('puts the least-checked first when ascending', () => {
+ expect(sortByRuns(rules, 'asc').map((rule) => rule.id)).toEqual(['d', 'a', 'c', 'b']);
+ });
+
+ it('steps off → most first → fewest first → off on each header click', () => {
+ expect(nextRunsSort(null)).toBe('desc');
+ expect(nextRunsSort('desc')).toBe('asc');
+ expect(nextRunsSort('asc')).toBeNull();
+ });
+});
+
+describe('agentSectionsByCount', () => {
+ const agentGroup = (agentId: string, statuses: string[]) =>
+ ({
+ domain: { id: `d-${agentId}` },
+ owner: {
+ agent: { avatar: null, backgroundColor: null, id: agentId, title: agentId },
+ kind: 'agent',
+ },
+ rules: statuses.map((status, index) => ({ id: `${agentId}-${index}`, status })),
+ scopes: [],
+ }) as unknown as RuleGroup;
+
+ it('lists agents by lessons in force, most first, without the reviewer part', () => {
+ const sections = sectionsByOwner([
+ agentGroup('few', ['active']),
+ agentGroup('many', ['active', 'active', 'active']),
+ // Archived lessons do not count toward the number on the option.
+ agentGroup('archived', ['active', 'retired', 'retired', 'retired']),
+ ]);
+ expect(agentSectionsByCount(sections).map((section) => section.key)).toEqual([
+ 'agent:many',
+ 'agent:few',
+ 'agent:archived',
+ ]);
+ });
+});
diff --git a/src/features/MemoryRules/labels.ts b/src/features/MemoryRules/labels.ts
index 2bebd59a377..fb0f14c66fe 100644
--- a/src/features/MemoryRules/labels.ts
+++ b/src/features/MemoryRules/labels.ts
@@ -142,3 +142,35 @@ export const findMove = (
}
return null;
};
+
+/** How many rules of one part are in force — the number each switcher option carries. */
+export const liveCount = (section: OwnerSection) =>
+ section.groups.flatMap((group) => group.rules).filter((rule) => rule.status === 'active').length;
+
+/**
+ * The agent parts in the order the picker lists them: most lessons first, so the agents that
+ * learned the most are on top however many there are. Ties keep the server's order.
+ */
+export const agentSectionsByCount = (sections: OwnerSection[]) =>
+ sections
+ .filter((section) => section.owner.kind === 'agent')
+ .map((section) => ({ count: liveCount(section), section }))
+ .sort((a, b) => b.count - a.count)
+ .map(({ section }) => section);
+
+/** Sorting by the "checked" column: off (the reviewer's own order), most first, fewest first. */
+export type RunsSort = 'asc' | 'desc' | null;
+
+/** One click on the column header steps off → most first → fewest first → off. */
+export const nextRunsSort = (sort: RunsSort): RunsSort =>
+ sort === null ? 'desc' : sort === 'desc' ? 'asc' : null;
+
+/**
+ * Rules in one group ordered by how many runs checked them. Off returns the reviewer's order
+ * untouched; ties keep it too, so equal counts never shuffle between renders.
+ */
+export const sortByRuns = <T extends Pick<RuleItem, 'hitRunCount'>>(rules: T[], sort: RunsSort) => {
+ if (!sort) return rules;
+ const sign = sort === 'desc' ? -1 : 1;
+ return [...rules].sort((a, b) => sign * ((a.hitRunCount ?? 0) - (b.hitRunCount ?? 0)));
+};
diff --git a/src/features/MemoryRules/styles.ts b/src/features/MemoryRules/styles.ts
index 56a359764d2..71115ff3f7c 100644
--- a/src/features/MemoryRules/styles.ts
+++ b/src/features/MemoryRules/styles.ts
@@ -25,6 +25,20 @@ export const styles = createStaticStyles(({ css }) => ({
chevronOpen: css`
transform: rotate(90deg);
`,
+ directionNegative: css`
+ color: ${cssVar.colorTextSecondary};
+
+ & svg {
+ color: ${cssVar.colorError};
+ }
+ `,
+ directionPositive: css`
+ color: ${cssVar.colorTextSecondary};
+
+ & svg {
+ color: ${cssVar.colorSuccess};
+ }
+ `,
divider: css`
padding-block: 22px 6px;
padding-inline: 8px;
@@ -35,7 +49,7 @@ export const styles = createStaticStyles(({ css }) => ({
`,
grid: css`
display: grid;
- grid-template-columns: 22px 40px minmax(220px, 2fr) 56px 64px 64px 28px;
+ grid-template-columns: 22px 40px minmax(220px, 2fr) 56px 56px 64px 64px 28px;
column-gap: 8px;
align-items: start;
`,
@@ -161,6 +175,36 @@ export const styles = createStaticStyles(({ css }) => ({
font-size: 13px;
font-weight: 600;
`,
+ sortHeader: css`
+ cursor: pointer;
+ user-select: none;
+
+ display: inline-flex;
+ gap: 2px;
+ align-items: center;
+
+ width: fit-content;
+ padding: 0;
+ border: 0;
+
+ font: inherit;
+ color: inherit;
+
+ background: none;
+
+ &:focus-visible {
+ border-radius: ${cssVar.borderRadiusSM};
+ outline: 2px solid ${cssVar.colorPrimaryBorder};
+ outline-offset: 2px;
+ }
+
+ &:hover {
+ color: ${cssVar.colorText};
+ }
+ `,
+ sortHeaderActive: css`
+ color: ${cssVar.colorText};
+ `,
thead: css`
position: sticky;
z-index: 1;
diff --git a/src/features/MemoryRules/useAgentToReopen.test.ts b/src/features/MemoryRules/useAgentToReopen.test.ts
new file mode 100644
index 00000000000..ef883b46d18
--- /dev/null
+++ b/src/features/MemoryRules/useAgentToReopen.test.ts
@@ -0,0 +1,33 @@
+import { renderHook } from '@testing-library/react';
+import { describe, expect, it } from 'vitest';
+
+import { useAgentToReopen } from './useAgentToReopen';
+
+// The switcher lists agents most-lessons first; `many` leads, `few` is what onboarding opens.
+const agentKeys = ['agent:many', 'agent:few'];
+
+describe('useAgentToReopen', () => {
+ it('reopens an agent opened from outside the switcher, not the count leader', () => {
+ const { rerender, result } = renderHook(({ value }) => useAgentToReopen(value, agentKeys), {
+ initialProps: { value: 'agent:few' },
+ });
+ rerender({ value: 'mine' });
+
+ expect(result.current).toBe('agent:few');
+ });
+
+ it('opens the agent that learned the most when none was viewed yet', () => {
+ const { result } = renderHook(() => useAgentToReopen('mine', agentKeys));
+
+ expect(result.current).toBe('agent:many');
+ });
+
+ it('falls back to the leader when the remembered agent is gone', () => {
+ const { rerender, result } = renderHook(({ keys, value }) => useAgentToReopen(value, keys), {
+ initialProps: { keys: agentKeys, value: 'agent:few' },
+ });
+ rerender({ keys: ['agent:many'], value: 'mine' });
+
+ expect(result.current).toBe('agent:many');
+ });
+});
diff --git a/src/features/MemoryRules/useAgentToReopen.ts b/src/features/MemoryRules/useAgentToReopen.ts
new file mode 100644
index 00000000000..8aa0fac990e
--- /dev/null
+++ b/src/features/MemoryRules/useAgentToReopen.ts
@@ -0,0 +1,13 @@
+import { useState } from 'react';
+
+/**
+ * The agent the switcher reopens when the reader comes back to "Agents": the one last on screen,
+ * however it got there — picked in the switcher or opened from the onboarding link — else the
+ * first of `agentKeys` (the one that learned the most).
+ */
+export const useAgentToReopen = (value: string, agentKeys: string[]) => {
+ const [lastAgent, setLastAgent] = useState<string>();
+ // Adjusting state during render: whichever agent is on screen becomes the remembered one.
+ if (value !== 'mine' && value !== lastAgent) setLastAgent(value);
+ return lastAgent && agentKeys.includes(lastAgent) ? lastAgent : agentKeys[0];
+};
diff --git a/src/features/MemoryRules/useJudgeDirections.test.ts b/src/features/MemoryRules/useJudgeDirections.test.ts
new file mode 100644
index 00000000000..40304ee09b2
--- /dev/null
+++ b/src/features/MemoryRules/useJudgeDirections.test.ts
@@ -0,0 +1,63 @@
+import { renderHook, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useJudgeDirections } from './useJudgeDirections';
+
+const { judgeRuleDirections } = vi.hoisted(() => ({ judgeRuleDirections: vi.fn() }));
+vi.mock('@/services/expertise', () => ({ expertiseService: { judgeRuleDirections } }));
+
+const refresh = vi.fn(async () => {});
+const sleep = () => new Promise((resolve) => setTimeout(resolve, 20));
+const ids = (prefix: string, count: number) =>
+ Array.from({ length: count }, (_, index) => `${prefix}${index}`);
+
+describe('useJudgeDirections', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ judgeRuleDirections.mockResolvedValue({ judged: 1 });
+ });
+
+ it('starts another call for a rule written after the first one began', async () => {
+ const { rerender } = renderHook(({ list }) => useJudgeDirections(true, list, refresh), {
+ initialProps: { list: ['old'] },
+ });
+ await waitFor(() => expect(refresh).toHaveBeenCalledTimes(1));
+
+ // A hand-written rule with no direction lands after the refresh.
+ rerender({ list: ['new'] });
+
+ await waitFor(() => expect(judgeRuleDirections).toHaveBeenLastCalledWith(['new']));
+ });
+
+ it('works through every batch, however many rules there are', async () => {
+ // Nothing is judged, so the list never shrinks: progress comes only from batching.
+ judgeRuleDirections.mockResolvedValue({ judged: 0 });
+ const all = ids('r', 450);
+ renderHook(() => useJudgeDirections(true, all, refresh));
+
+ await waitFor(() => expect(judgeRuleDirections).toHaveBeenCalledTimes(12));
+ const sent = judgeRuleDirections.mock.calls.flatMap(([batch]) => batch);
+ expect(sent).toEqual(all);
+ expect(Math.max(...judgeRuleDirections.mock.calls.map(([batch]) => batch.length))).toBe(40);
+ });
+
+ it('never sends a rule the model skipped a second time', async () => {
+ judgeRuleDirections.mockResolvedValue({ judged: 0 });
+ const { rerender } = renderHook(({ list }) => useJudgeDirections(true, list, refresh), {
+ initialProps: { list: ['skipped'] },
+ });
+ await waitFor(() => expect(judgeRuleDirections).toHaveBeenCalledTimes(1));
+
+ rerender({ list: ['skipped'] });
+ await sleep();
+
+ expect(judgeRuleDirections).toHaveBeenCalledTimes(1);
+ });
+
+ it('does nothing while the lab is off', async () => {
+ renderHook(() => useJudgeDirections(false, ['a'], refresh));
+ await sleep();
+
+ expect(judgeRuleDirections).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/MemoryRules/useJudgeDirections.ts b/src/features/MemoryRules/useJudgeDirections.ts
new file mode 100644
index 00000000000..9be0574d04b
--- /dev/null
+++ b/src/features/MemoryRules/useJudgeDirections.ts
@@ -0,0 +1,50 @@
+import { useEffect, useRef, useState } from 'react';
+
+import { useSingleton } from '@/hooks/useSingleton';
+import { expertiseService } from '@/services/expertise';
+
+/** Rules per call; matches the server's cap on one judging request. */
+const BATCH = 40;
+
+/**
+ * Judges, in the background, the directions of rules that reached the page without one (written
+ * before it existed, distilled from a run, or written by hand without picking one). Until then
+ * the column shows a dash and stays a switch, so nothing waits on it.
+ *
+ * One call at a time, each naming the next batch of rules no call has asked about yet. When a
+ * call ends the hook looks again, so every unjudged rule — including one written mid-visit — is
+ * asked about exactly once per visit; a rule the model skips is not sent again, so it cannot loop
+ * the page or hold up the rules behind it.
+ */
+export const useJudgeDirections = (
+ enabled: boolean,
+ unjudgedIds: string[],
+ refresh: () => Promise<unknown>,
+) => {
+ const asked = useSingleton(() => new Set<string>());
+ const runningRef = useRef(false);
+ // Bumped when a call ends, so the next batch (or a rule that arrived meanwhile) gets its turn.
+ const [calls, setCalls] = useState(0);
+ const key = unjudgedIds.join(',');
+
+ useEffect(() => {
+ if (!enabled || runningRef.current) return;
+ const batch = unjudgedIds.filter((id) => !asked.has(id)).slice(0, BATCH);
+ if (batch.length === 0) return;
+ for (const id of batch) asked.add(id);
+ runningRef.current = true;
+ void (async () => {
+ try {
+ const { judged } = await expertiseService.judgeRuleDirections(batch);
+ if (judged > 0) await refresh();
+ } catch (error) {
+ // Quiet on purpose: the reviewer did not ask for this, and every row stays settable.
+ console.error('[MemoryRules] judging directions failed:', error);
+ } finally {
+ runningRef.current = false;
+ setCalls((n) => n + 1);
+ }
+ })();
+ // `key` stands for `unjudgedIds`, whose array identity changes every render.
+ }, [enabled, key, calls, refresh]);
+};
diff --git a/src/services/expertise.ts b/src/services/expertise.ts
index 70918de3ba1..7c8c04ad310 100644
--- a/src/services/expertise.ts
+++ b/src/services/expertise.ts
@@ -57,6 +57,9 @@ class ExpertiseService {
updateRule = async (lessonId: string, patch: UpdateRuleInput) =>
lambdaClient.expertise.updateRule.mutate({ lessonId, ...patch });
+ judgeRuleDirections = async (lessonIds: string[]) =>
+ lambdaClient.expertise.judgeRuleDirections.mutate({ lessonIds });
+
reorderRule = async (domainId: string, lessonId: string, beforeId: string | null) =>
lambdaClient.expertise.reorderRule.mutate({ beforeId, domainId, lessonId });