🤯 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
♻️ refactor(expertise): rebuild self-learning as a growth portrait (#18394)
Arvin Xu3043944d1d14
diff --git a/apps/server/src/routers/lambda/expertise.ts b/apps/server/src/routers/lambda/expertise.tsindex 93e0cf09d45..15783c07fd2 100644--- a/apps/server/src/routers/lambda/expertise.ts+++ b/apps/server/src/routers/lambda/expertise.ts@@ -3,12 +3,10 @@ import { z } from 'zod';import { ExpertiseModel } from '@/database/models/expertise';import { authedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';-import { ExpertiseDomainService } from '@/server/services/expertise/domain';+import { DomainDraftSchema, ExpertiseDomainService } from '@/server/services/expertise/domain';import { ExpertiseIngestionService } from '@/server/services/expertise/ingestion';import { ExpertiseHistoryWorkflow } from '@/server/workflows/expertiseHistory';-import { recentLessonDelta } from './expertiseHelpers';-const expertiseProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {const { ctx } = opts;return opts.next({@@ -66,23 +64,23 @@ const toMaturity = (s?: {};export const expertiseRouter = router({- /** L0: all expertise available to an agent and its latest state. */+ /**+ * L0: the growth portrait — every bound domain with its habits (active lessons + recent+ * outcomes), the cumulative-learned series, and the per-run reliability series.+ * Reliability tiers are folded on the client so one pure helper owns the thresholds.+ */listByAgent: expertiseProcedure.input(z.object({ agentId: z.string() })).query(async ({ ctx, input }) => {const bound = await ctx.expertiseModel.listDomainsForAgent(input.agentId);const domainIds = bound.map((b) => b.domain.id);- const [snapshots, actors, insights, series] = await Promise.all([+ const [snapshots, series, reliability, lessons] = await Promise.all([ctx.expertiseModel.latestSnapshots(domainIds),- ctx.expertiseModel.actorsByDomain(domainIds),- ctx.expertiseModel.listInsights(domainIds),ctx.expertiseModel.seriesForDomains(domainIds),+ ctx.expertiseModel.reliabilitySeries(domainIds),+ ctx.expertiseModel.listLessonsWithRecent(domainIds),]);const snapByDomain = new Map(snapshots.map((s) => [s.domainId, s]));- const actorsByDomain = new Map<string, string[]>();- for (const a of actors) {- actorsByDomain.set(a.domainId, [...(actorsByDomain.get(a.domainId) ?? []), a.actorId]);- }const seriesByDomain = new Map<string, { n: number; run: number }[]>();for (const s of series) {seriesByDomain.set(s.domainId, [@@ -90,43 +88,52 @@ export const expertiseRouter = router({{ n: s.activeCount, run: s.runIndex },]);}+ const reliabilityByDomain = new Map<+ string,+ { pass: number; run: number; violation: number }[]+ >();+ for (const r of reliability) {+ reliabilityByDomain.set(r.domainId, [+ ...(reliabilityByDomain.get(r.domainId) ?? []),+ { pass: r.pass, run: r.runIndex, violation: r.violation },+ ]);+ }+ const lessonsByDomain = new Map<string, typeof lessons>();+ for (const l of lessons) {+ lessonsByDomain.set(l.domainId, [...(lessonsByDomain.get(l.domainId) ?? []), l]);+ }- const domains = bound.map(({ binding, domain }) => {+ const domains = bound.map(({ domain }) => {const snap = snapByDomain.get(domain.id);- const points = seriesByDomain.get(domain.id) ?? [];- // Net change over the latest five runs distinguishes growth, retirement, and no learning.- const delta = recentLessonDelta(points);return {- activeRate: snap?.activeRate ?? null,- actors: actorsByDomain.get(domain.id) ?? [],- canonCoverage: snap?.canonCoverage ?? null,- contributionMode: binding.contributionMode,- delta,+ canonEntries: domain.canonEntries,+ domainFilter: domain.domainFilter,id: domain.id,- /** Timestamp of the latest practice run. */lastPracticedAt: snap?.capturedAt ?? null,- layerCounts: snap?.layerCounts ?? {},- layerCoverage: snap?.layerCoverage ?? null,+ layerCanonRef: domain.anchorCandidates?.[0]?.layerCanonRef ?? null,layers: domain.layers,layerSource: domain.layerSource,- lessonCount: snap?.activeCount ?? 0,- maturity: toMaturity(snap),+ lessons: (lessonsByDomain.get(domain.id) ?? []).map((l) => ({+ code: l.code,+ createdAt: l.createdAt,+ hitCount: l.hitCount,+ id: l.id,+ lastHitAt: l.lastHitAt,+ layer: l.layer,+ recent: l.recent,+ /** Taught by the user directly (as opposed to distilled from practice). */+ taughtByUser: l.createdByUserId != null,+ title: l.title,+ })),+ outOfScope: domain.outOfScope,+ reliability: reliabilityByDomain.get(domain.id) ?? [],runCount: snap?.runIndex ?? 0,- /** Series used by the overlaid maturity chart. */- series: points,- slug: domain.slug,+ series: seriesByDomain.get(domain.id) ?? [],title: domain.title,};});- return {- domains,- insights,- totals: {- domains: domains.length,- lessons: domains.reduce((a, d) => a + d.lessonCount, 0),- },- };+ return { domains };}),/** L1: the complete SCLPT domain state and time series. */@@ -199,15 +206,41 @@ export const expertiseRouter = router({return { hits, lesson };}),- /** Creates an expertise domain from a natural-language brief. */+ /** Step 1 of creation: interpret the brief into an editable draft. Nothing is persisted. */+ draftDomain: expertiseProcedure+ .input(z.object({ agentId: z.string(), brief: z.string().min(1) }))+ .mutation(async ({ ctx, input }) => ctx.expertiseDomainService.draftFromBrief(input)),++ /** Step 2 of creation: persist the reviewed anchor and bind it to the agent. */createDomain: expertiseProcedure- .input(- z.object({- agentId: z.string(),- brief: z.string().min(1),- }),- )- .mutation(async ({ ctx, input }) => ctx.expertiseDomainService.createFromBrief(input)),+ .input(DomainDraftSchema.extend({ agentId: z.string(), brief: z.string().min(1) }))+ .mutation(async ({ ctx, input }) => ctx.expertiseDomainService.create(input)),++ /** How many past conversations a history warm-up would read. */+ countHistory: expertiseProcedure+ .input(z.object({ agentId: z.string() }))+ .query(async ({ ctx, input }) => ({+ candidateCount: await ctx.expertiseIngestionService.countHistoricalTopics(input.agentId),+ })),++ /** The user teaches one lesson directly, in their own words. */+ teachLesson: expertiseProcedure+ .input(z.object({ domainId: z.string(), text: z.string().min(1).max(2000) }))+ .mutation(async ({ ctx, input }) =>+ ctx.expertiseModel.teachLesson({ domainId: input.domainId, text: input.text }),+ ),++ /** The user corrects a lesson; the correction is versioned and joins the lesson body. */+ reviseLesson: expertiseProcedure+ .input(z.object({ lessonId: z.string(), text: z.string().min(1).max(2000) }))+ .mutation(async ({ ctx, input }) =>+ ctx.expertiseModel.reviseLesson(input.lessonId, input.text),+ ),++ /** The user asks it to forget a lesson. */+ retireLesson: expertiseProcedure+ .input(z.object({ lessonId: z.string() }))+ .mutation(async ({ ctx, input }) => ctx.expertiseModel.retireLesson(input.lessonId)),/** Explicitly bootstraps expertise from conversations that existed before the domain did. */ingestHistory: expertiseProcedurediff --git a/apps/server/src/routers/lambda/expertiseHelpers.test.ts b/apps/server/src/routers/lambda/expertiseHelpers.test.tsdeleted file mode 100644index 631e4c2953a..00000000000--- a/apps/server/src/routers/lambda/expertiseHelpers.test.ts+++ /dev/null@@ -1,19 +0,0 @@-import { describe, expect, it } from 'vitest';--import { recentLessonDelta } from './expertiseHelpers';--describe('recentLessonDelta', () => {- it('uses zero as the baseline for the first practice', () => {- expect(recentLessonDelta([{ n: 1, run: 1 }])).toBe(1);- });-- it('reports recent net change after multiple practices', () => {- expect(- recentLessonDelta([- { n: 2, run: 1 },- { n: 4, run: 2 },- { n: 3, run: 3 },- ]),- ).toBe(1);- });-});diff --git a/apps/server/src/routers/lambda/expertiseHelpers.ts b/apps/server/src/routers/lambda/expertiseHelpers.tsdeleted file mode 100644index 58a630093d0..00000000000--- a/apps/server/src/routers/lambda/expertiseHelpers.ts+++ /dev/null@@ -1,12 +0,0 @@-interface ExpertiseSeriesPoint {- n: number;- run: number;-}--/** Recent net growth, using zero as the baseline for a domain's first practice. */-export const recentLessonDelta = (points: ExpertiseSeriesPoint[]) => {- const recent = points.slice(-6);- if (recent.length === 0) return 0;- if (recent.length === 1) return recent[0].n;- return recent.at(-1)!.n - recent[0].n;-};diff --git a/apps/server/src/services/expertise/domain.test.ts b/apps/server/src/services/expertise/domain.test.tsindex ee979ce72f8..8dc15ab310e 100644--- a/apps/server/src/services/expertise/domain.test.ts+++ b/apps/server/src/services/expertise/domain.test.ts@@ -23,36 +23,83 @@ vi.mock('@/server/services/aiGeneration', () => ({},}));+const draft = {+ canonEntries: [+ {+ key: 'blameless',+ source: 'Google SRE Book',+ statement: 'Postmortems that assign blame hide the systemic cause.',+ title: 'Blameless postmortem',+ },+ ],+ domainFilter: 'Include production incident diagnosis and remediation.',+ layerCanonRef: 'Google SRE incident lifecycle',+ layerSource: 'canonical',+ layers: [+ { description: 'Detect and triage.', key: 'detect', title: 'Detection' },+ { description: null, key: 'root-cause', title: 'Root cause' },+ ],+ outOfScope: 'Exclude general architecture discussions without an incident.',+ rationale: 'The brief is about incidents end to end.',+ title: 'Production incident response',+};+describe('ExpertiseDomainService', () => {beforeEach(() => vi.clearAllMocks());- it('uses structured generation instead of parsing the brief with string rules', async () => {+ it('drafts a full anchor (layers + canon) without persisting anything', async () => {getAgentModelConfig.mockResolvedValue({ model: 'test-model', provider: 'test-provider' });- generateObject.mockResolvedValue({- domainFilter: 'Include production incident diagnosis and remediation.',- outOfScope: 'Exclude general architecture discussions without an incident.',- title: 'Production incident response',- });- createDomain.mockResolvedValue('domain_1');+ generateObject.mockResolvedValue(draft);- const result = await new ExpertiseDomainService({} as never, 'user_1').createFromBrief({+ const result = await new ExpertiseDomainService({} as never, 'user_1').draftFromBrief({agentId: 'agent_1',- brief: 'Help it improve at production incidents, excluding general design discussions.',+ brief: 'Help it improve at production incidents.',});expect(generateObject).toHaveBeenCalledWith(expect.objectContaining({- schema: expect.objectContaining({ name: 'expertise_domain_brief' }),+ schema: expect.objectContaining({ name: 'expertise_domain_draft' }),}),expect.any(Object),);- expect(createDomain).toHaveBeenCalledWith({+ expect(result.layers).toHaveLength(2);+ expect(result.canonEntries[0].key).toBe('blameless');+ expect(createDomain).not.toHaveBeenCalled();+ });++ it('persists the reviewed draft as the chosen anchor, carrying layers and canon', async () => {+ createDomain.mockResolvedValue('domain_1');++ const result = await new ExpertiseDomainService({} as never, 'user_1').create({+ ...draft,agentId: 'agent_1',- brief: 'Help it improve at production incidents, excluding general design discussions.',- domainFilter: 'Include production incident diagnosis and remediation.',- outOfScope: 'Exclude general architecture discussions without an incident.',- title: 'Production incident response',- });+ brief: 'Help it improve at production incidents.',+ } as never);++ expect(createDomain).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agent_1',+ canonEntries: draft.canonEntries,+ layerCanonRef: 'Google SRE incident lifecycle',+ layerSource: 'canonical',+ layers: [+ {+ canonRef: 'Google SRE incident lifecycle',+ description: 'Detect and triage.',+ key: 'detect',+ title: 'Detection',+ },+ {+ canonRef: 'Google SRE incident lifecycle',+ description: undefined,+ key: 'root-cause',+ title: 'Root cause',+ },+ ],+ rationale: 'The brief is about incidents end to end.',+ title: 'Production incident response',+ }),+ );expect(result).toBe('domain_1');});});diff --git a/apps/server/src/services/expertise/domain.ts b/apps/server/src/services/expertise/domain.tsindex 1862bf10463..f2dd29a43ee 100644--- a/apps/server/src/services/expertise/domain.ts+++ b/apps/server/src/services/expertise/domain.ts@@ -7,26 +7,99 @@ import { ExpertiseModel } from '@/database/models/expertise';import type { LobeChatDatabase } from '@/database/type';import { AiGenerationService } from '@/server/services/aiGeneration';-const DomainBriefSchema = z.object({+const LayerSchema = z.object({+ description: z.string().nullable(),+ key: z.string().min(1).max(40),+ title: z.string().min(1).max(60),+});+const CanonEntrySchema = z.object({+ key: z.string().min(1).max(40),+ source: z.string().min(1).max(120),+ statement: z.string().min(1),+ title: z.string().min(1).max(80),+});++/**+ * A draft is a full anchor candidate, not just a name and a filter: the layer model and the+ * canon decide where lessons attach and what "coverage" even means, so the person creating a+ * direction must be able to see and edit them before anything is persisted.+ */+export const DomainDraftSchema = z.object({+ canonEntries: z.array(CanonEntrySchema).max(8),domainFilter: z.string().min(1),+ layerCanonRef: z.string().nullable(),+ layerSource: z.enum(['canonical', 'invented']),+ layers: z.array(LayerSchema).max(6),outOfScope: z.string().nullable(),+ rationale: z.string().nullable(),title: z.string().min(1).max(80),});+export type DomainDraft = z.infer<typeof DomainDraftSchema>;-const DOMAIN_BRIEF_JSON_SCHEMA: GenerateObjectSchema = {- name: 'expertise_domain_brief',+const DOMAIN_DRAFT_JSON_SCHEMA: GenerateObjectSchema = {+ name: 'expertise_domain_draft',schema: {additionalProperties: false,properties: {+ canonEntries: {+ items: {+ additionalProperties: false,+ properties: {+ key: { type: 'string' },+ source: { type: 'string' },+ statement: { type: 'string' },+ title: { type: 'string' },+ },+ required: ['key', 'source', 'statement', 'title'],+ type: 'object',+ },+ maxItems: 8,+ type: 'array',+ },domainFilter: { type: 'string' },+ layerCanonRef: { type: ['string', 'null'] },+ layerSource: { enum: ['canonical', 'invented'], type: 'string' },+ layers: {+ items: {+ additionalProperties: false,+ properties: {+ description: { type: ['string', 'null'] },+ key: { type: 'string' },+ title: { type: 'string' },+ },+ required: ['description', 'key', 'title'],+ type: 'object',+ },+ maxItems: 6,+ type: 'array',+ },outOfScope: { type: ['string', 'null'] },+ rationale: { type: ['string', 'null'] },title: { maxLength: 80, type: 'string' },},- required: ['domainFilter', 'outOfScope', 'title'],+ required: [+ 'canonEntries',+ 'domainFilter',+ 'layerCanonRef',+ 'layerSource',+ 'layers',+ 'outOfScope',+ 'rationale',+ 'title',+ ],type: 'object',},};+const DRAFT_SYSTEM_PROMPT = [+ 'Convert the user brief into one executable expertise domain — an anchor the agent will learn against.',+ 'Return: a concise title; domainFilter stating which conversations and work count as practice; outOfScope stating explicit exclusions;',+ 'layers — the 2 to 5 levels this expertise is judged on (a stable key, a short title, one-line description). Prefer a canonical layer model from a well-known framework in this field and name it in layerCanonRef with layerSource="canonical"; only invent layers (layerSource="invented", layerCanonRef=null) when no canonical model fits;',+ 'canonEntries — 3 to 8 referenceable principles from recognised books, frameworks or methodologies in this field (stable key, title, source, and the general statement of why the failure recurs);',+ 'rationale — one or two sentences on why this anchor fits the brief.',+ 'Preserve the user intent, do not invent a broader domain, keep keys short ASCII slugs, and write all human-facing fields in the language used by the user.',+].join(' ');+export class ExpertiseDomainService {constructor(private readonly db: LobeChatDatabase,@@ -34,43 +107,59 @@ export class ExpertiseDomainService {private readonly workspaceId?: string,) {}- createFromBrief = async (input: { agentId: string; brief: string }) => {+ /** Turns one natural-language brief into an editable domain draft; nothing is persisted. */+ draftFromBrief = async (input: { agentId: string; brief: string }) => {const agentModel = new AgentModel(this.db, this.userId, this.workspaceId);const modelConfig = await agentModel.getAgentModelConfig(input.agentId);if (!modelConfig) throw new Error('Agent model configuration is unavailable');const ai = new AiGenerationService(this.db, this.userId, this.workspaceId);- const generated = DomainBriefSchema.parse(+ return DomainDraftSchema.parse(await ai.generateObject({messages: [- {- content:- 'Convert the user brief into one executable expertise domain. Return a concise title, a domainFilter that states what conversations and work count as practice, and outOfScope that states explicit exclusions. Preserve the user intent, do not invent a broader domain, and write all fields in the language used by the user.',- role: 'system',- },+ { content: DRAFT_SYSTEM_PROMPT, role: 'system' },{ content: input.brief.trim(), role: 'user' },],...modelConfig,- schema: DOMAIN_BRIEF_JSON_SCHEMA,+ schema: DOMAIN_DRAFT_JSON_SCHEMA,},{- metadata: { trigger: 'expertise_domain_brief' },+ metadata: { trigger: 'expertise_domain_draft' },tracing: {agentId: input.agentId,- promptVersion: 'expertise-domain-brief-v1',+ promptVersion: 'expertise-domain-draft-v2',scenario: TRACING_SCENARIOS.TopicAutoSummary,- schemaName: DOMAIN_BRIEF_JSON_SCHEMA.name,+ schemaName: DOMAIN_DRAFT_JSON_SCHEMA.name,},},),);+ };- return new ExpertiseModel(this.db, this.userId, this.workspaceId).createDomain({- ...generated,+ /** Persists a reviewed draft as the chosen anchor. The user has seen and possibly edited every field by now. */+ create = async (input: DomainDraft & { agentId: string; brief: string }) =>+ new ExpertiseModel(this.db, this.userId, this.workspaceId).createDomain({agentId: input.agentId,brief: input.brief,- outOfScope: generated.outOfScope ?? undefined,+ canonEntries: input.canonEntries,+ domainFilter: input.domainFilter,+ layerCanonRef: input.layerCanonRef ?? undefined,+ layers: input.layers.map((l) => ({+ canonRef: input.layerCanonRef ?? undefined,+ description: l.description ?? undefined,+ key: l.key,+ title: l.title,+ })),+ layerSource: input.layerSource,+ outOfScope: input.outOfScope ?? undefined,+ rationale: input.rationale ?? undefined,+ title: input.title,});++ /** One-shot path kept for callers that do not review the draft (tests, scripts). */+ createFromBrief = async (input: { agentId: string; brief: string }) => {+ const generated = await this.draftFromBrief(input);+ return this.create({ ...input, ...generated });};}diff --git a/locales/en-US/selfLearning.json b/locales/en-US/selfLearning.jsonindex d36dbd5debd..a09fbc691a9 100644--- a/locales/en-US/selfLearning.json+++ b/locales/en-US/selfLearning.json@@ -1,147 +1,121 @@{- "anchor.choose": "Take this direction",- "anchor.chooseFailed": "Could not set the direction. Try again.",- "anchor.howBody": "Once a direction is set, nothing else is required of you: every conversation that matches its filter counts as one practice, and the rules are extracted from the places it got things wrong. Work with it the way you normally would — the curve fills itself in.",- "anchor.howTitle": "Where the data comes from",- "anchor.noCandidates": "No directions proposed yet",- "anchor.noCandidatesDesc": "Directions are read out of what this agent has actually been doing. Have a few real conversations in the area you care about, then come back — the more it has done, the sharper the proposals.",- "anchor.pending": "Waiting for you to pick a direction",- "anchor.pendingDesc": "A domain is a choice, not a discovery — the same agent can be anchored two different ways and both are correct. Pick one and it starts building rules from the very next matching conversation.",- "anchor.tag": "Direction not picked",- "anchor.traceCandidates": "{{count}} possible directions",- "anchor.traceCluster": "Recurring work grouped",- "anchor.traceConversations": "Past conversations",- "anchor.traceHelp": "These are two valid ways to define the same body of work, not a system recommendation. Pick the boundary you want this expertise to learn within.",- "coverage.blankHint": "never tested at this layer",- "coverage.canon": "Layer model: {{source}}",- "coverage.gaps": "No rules yet",- "coverage.invented": "Layer model has no canonical source",- "coverage.share": "{{title}} · {{count}} rules",- "coverage.sub": "{{covered}}/{{total}} layers have rules · {{unused}} rules never used",- "coverage.title": "Where the learning has landed",- "coverage.total": "{{count}} lessons total",+ "anchor.filter": "Counts as practice",+ "anchor.noCanon": "no canon — coverage cannot be judged",+ "anchor.noLayers": "no layers — lessons are not grouped by level",+ "anchor.outOfScope": "Does not count",+ "anchor.subtitle": "the standard it learns against, set when the direction was created",+ "anchor.title": "Its anchor",+ "charts.count": "{{count}} lessons",+ "charts.early": "started at {{rate}}%",+ "charts.learned": "Learned so far",+ "charts.learnedSub": "{{runs}} practices",+ "charts.passRate": "Done right",+ "charts.recentAvg": "average of the last {{count}}",+ "charts.refLine": "90% line",+ "charts.run1": "run 1",+ "charts.runN": "run {{n}}",+ "charts.streak": "{{count}} practices in a row with no mistakes",+ "charts.tooFew": "Curves appear after the second practice.",+ "create.anchor.addCanon": "Add",+ "create.anchor.addLayer": "Add",+ "create.anchor.canon": "Canon",+ "create.anchor.canonHint": "the recognised principles it will be judged against",+ "create.anchor.canonSource": "source (book / framework)",+ "create.anchor.canonStatement": "the general principle — why this failure recurs",+ "create.anchor.canonTitle": "principle",+ "create.anchor.layerDesc": "one line on what this layer covers",+ "create.anchor.layerTitle": "layer",+ "create.anchor.layers": "Layers",+ "create.anchor.layersFrom": "from {{ref}}",+ "create.anchor.layersInvented": "no canonical model fits — layers proposed from the brief",+ "create.anchor.noCanon": "No canon yet — it will still learn, but coverage cannot be judged.",+ "create.anchor.noLayers": "No layers yet — lessons will not be grouped by level.","create.back": "Back",- "create.briefHelp": "Say what you want it to get good at, and what does not count. That sentence becomes the test for which conversations feed this expertise — we work the name out from it.",- "create.briefPlaceholder": "e.g. I want it to get better at handling live incidents — from symptom to root cause to prevention. Design discussions and general ops questions do not count.",+ "create.briefHelp": "Say what you want it to get better at, and what does not count. This sentence becomes the test for which conversations count as practice in this direction; we work out the name from it.",+ "create.briefPlaceholder": "e.g. I want it to get better at handling production incidents — from symptom to root cause to prevention. Design discussions and general ops Q&A do not count.","create.cancel": "Cancel",- "create.entry": "Create an expertise",- "create.failed": "Could not create it. Try again.",- "create.filterHelp": "One executable test: which conversations count as practice for this expertise, and which do not. This is what keeps it from learning from everything.",- "create.filterLabel": "What counts as practice",- "create.filterPlaceholder": "e.g. the conversation is diagnosing a live incident with observable symptoms. Design discussions and general ops questions do not count.",- "create.generating": "Generating the expertise…",- "create.modalTitle": "Create an expertise",- "create.parse": "Continue",- "create.parsedFilter": "Conversations that count as practice",- "create.parsedTitle": "Expertise name",- "create.submit": "Create",- "create.titleLabel": "Name",- "create.titlePlaceholder": "e.g. Incident response",- "detail.anchorTitle": "What the anchoring step saw",- "detail.chart.count": "{{count}}",- "detail.chart.firstRun": "run 1",- "detail.chart.legendActual": "actual",- "detail.chart.legendBars": "bars = learned that round (blue = you were in the conversation)",- "detail.chart.legendFit": "projected at the current pace",- "detail.chart.noProjection": "The fit is not reliable ({{reason}}), so no projection is drawn and no estimated number is shown.",- "detail.chart.nthRun": "run {{n}}",- "detail.chart.reach90": "projected to hit 90% at run {{run}}",- "detail.chart.remaining": "{{count}} more practices",- "detail.chart.speculative": "Treat this projection as a rough estimate: the observation has not yet covered a full learning cycle, so the curve has not turned and the ceiling is inferred rather than measured. Run {{n90}} will move as more practice comes in.",- "detail.chart.title": "Rules learned, as a share of the estimated ceiling",- "detail.chart.today": "today · {{count}} practices",- "detail.chart.trustworthy": "At the current pace, {{remaining}} more practices reach 90% (run {{n90}}).",- "detail.domainFilter": "Domain filter: ",- "detail.firstPracticeDesc": "{{lessons}} rules were captured. A trend appears after the next matching practice, so there is no curve or maturity estimate yet.",- "detail.firstPracticeTitle": "The first practice is recorded",- "detail.headline": "Practised {{runs}} times, learned {{lessons}} rules.",- "detail.learningSummary": "{{lessons}} reusable rules distilled from practice.",- "detail.metric.cannot": "needs more practice",- "detail.metric.maturity": "Maturity",- "detail.metric.maturitySub": "{{learned}} of an estimated {{ceiling}}",- "detail.metric.r2": "Curve fit",- "detail.metric.r2Sub": "across {{count}} practices",- "detail.metric.rate": "Learning speed",- "detail.metric.rateSub": "one learning cycle per {{tau}} practices",- "detail.metric.shape": "Curve shape",- "detail.metric.shapeSub": "gained {{count}} in the tail",- "detail.notPractised": "Not practised yet",- "detail.notPractisedDesc": "The direction is set. It starts building rules the next time a conversation matches the filter below — nothing to chart until then.",- "detail.outOfScope": "Out of scope: ",- "detail.practiceSummary": "From {{runs}} practices · {{hits}} recorded validation hits",- "detail.shapeClause.growing": "and the curve is still climbing",- "detail.shapeClause.noisy": "though the curve is too noisy to read",- "detail.shapeClause.saturated": "and the curve has flattened",- "detail.shapeClause.stalled": "but the curve never really got going",- "detail.subheadOk": "The estimated ceiling for this domain is {{ceiling}} rules, {{shape}}.",- "detail.subheadUnusable": "The fit is not usable — maturity cannot be computed for this domain.",- "detail.totals": "{{runs}} practices · {{lessons}} rules · {{hits}} hits",- "empty.desc": "Point it at something it does often, and rules will grow out of repeated real practice.",+ "create.confirm": "Create",+ "create.failed": "Could not create the direction. Try again.",+ "create.field.domainFilter": "What counts as practice",+ "create.field.outOfScope": "What does not count",+ "create.field.outOfScopePlaceholder": "e.g. design discussions, general Q&A…",+ "create.field.title": "Name",+ "create.generate": "Generate",+ "create.generating": "Reading your brief…",+ "create.modalTitle": "Start a new direction",+ "create.next": "Next",+ "create.regenerate": "Regenerate",+ "create.reviewHelp": "Here is the anchor it read out of your brief. Fix anything that is off — the filter decides which conversations it learns from; the layers and canon decide where lessons attach and what “coverage” means.",+ "create.reviewStep": "Review the anchor",+ "domains.meta": "{{habits}} habits · {{runs}} practices",+ "domains.title": "Directions",+ "domains.word.fresh": "just starting",+ "domains.word.recurring": "{{count}} recurring",+ "domains.word.shaky": "{{count}} shaky",+ "domains.word.stable": "all solid",+ "empty.desc": "Point it at something it does often, and lessons will grow out of repeated real practice.","empty.title": "Turn real work into expertise",- "headline.alsoDeclining": " {{name}} has turned back down.",- "headline.alsoRising": " {{name}} is still climbing steeply.",- "headline.flat": "{{name}} is approaching its current estimated ceiling.",- "headline.none": "None of them has flattened yet.",- "headline.rising": "{{name}} is still climbing steeply.",- "history.empty": "There are no existing conversations to import.",- "history.entry": "Learn from history",- "history.failed": "Historical learning could not be started. Try again.",- "history.started": "Started learning from {{count}} existing conversations. New experience will appear here as it is distilled.",- "insights.title": "What it noticed across all these practices",- "journey.count": "{{count}} expertises",- "journey.step1": "Pick a direction",- "journey.step1Desc": "what counts as practice",- "journey.step2": "Let it do the work",- "journey.step2Desc": "rules come from real conversations",- "journey.step3": "Read where it stands",- "journey.step3Desc": "the curve becomes readable",- "layers.blank": "nothing yet",- "layers.count": "{{count}}",- "layers.fromCanon": "Layers from {{source}}",- "layers.invented": "Layers made up — no canonical model",- "layers.noteBody": "Each expertise gets its layers from its own canon during anchoring — a different domain means a different set. A layer at zero is a gap the canonical model exposed, not a rendering hole.",- "layers.noteTitle": "Layers come from the domain’s own canon, not a global enum",- "layers.title": "Which layers it learns at",- "layers.unanchored": "{{count}} rules are not anchored to any canonical entry.",- "maturity.reason.low-confidence": "too few practices, or the curve is too erratic to fit",- "maturity.reason.no-data": "never practised",- "maturity.reason.pending": "still computing",- "maturity.reason.tau-pinned": "the learning cycle is longer than what has been observed",- "overview.allDomains": "All {{count}} expertises",- "overview.firstPractice": "first practice",- "overview.noNumber": "needs more practice",- "overview.rowMeta": "{{lessons}} rules · practised {{runs}} times",- "overview.soloNext": "Open it to see what counts as practice — the rules start coming the next time a conversation matches.",- "overview.soloOpen": "Open it for the curve, the layers it learns at, and every rule it has picked up.",- "overview.totals": "{{domains}} expertises · {{lessons}} rules in total",- "overview.trendPending": "trend after the next practice",- "plateau.growing": "growing",- "plateau.noisy": "noisy",- "plateau.saturated": "saturated",- "plateau.stalled": "stalled",- "rules.allTitle": "All rules",- "rules.detail.domainUnavailable": "Domain context could not be loaded",+ "habit.action.correct": "Correct this",+ "habit.action.forget": "Let it forget",+ "habit.action.source": "See how it used this",+ "habit.action.teachAgain": "Teach it again",+ "habit.hint.freshNone": "no chance to test yet",+ "habit.hint.freshOne": "used once",+ "habit.hint.recurring": "wrong {{bad}} of the last {{total}} times · last in “{{topic}}”",+ "habit.hint.recurringNoTopic": "wrong {{bad}} of the last {{total}} times",+ "habit.hint.shaky": "wrong once in the last {{total}} · in “{{topic}}”",+ "habit.hint.shakyNoTopic": "wrong once in the last {{total}}",+ "habit.hint.stable": "{{count}} times, all right",+ "habit.hint.taughtPending": "you taught this; waiting for the next practice",+ "habit.recentTip.none": "not tested yet",+ "habit.recentTip.pass": "right",+ "habit.recentTip.title": "last {{count}}: {{list}}",+ "habit.recentTip.violation": "wrong",+ "habit.taughtTag": "you taught",+ "habit.teach.done": "Taught — it carries this from the next conversation.",+ "habit.teach.failed": "Could not save that. Try again.",+ "habit.teach.forgot": "Forgotten. It will not practice this anymore.",+ "habit.teach.placeholderCorrect": "What is off? Say it in your words — it folds this into the lesson…",+ "habit.teach.placeholderRecurring": "Tell it when this applies and when it absolutely does not…",+ "habit.teach.send": "Teach it",+ "habits.search": "Search habits",+ "habits.summary": "{{stable}} formed · {{shaky}} shaky · {{recurring}} recurring · {{fresh}} new",+ "habits.title": "Its habits",+ "headline.detail.recurring": "“{{title}}” keeps going wrong",+ "headline.detail.shaky": "{{count}} habits still go either way",+ "headline.multi.ok": "Across {{domains}} directions, everything it learned has become a habit.",+ "headline.single.fresh": "{{name}}: {{runs}} practice in, {{count}} lessons captured, none tested yet.",+ "headline.single.notPracticed": "{{name}} is set as a direction — nothing practiced yet.",+ "headline.single.recurring": "{{name}}: {{runs}} practices in, habits are mostly solid.",+ "headline.single.shaky": "{{name}}: {{runs}} practices in, most habits are solid.",+ "headline.single.stable": "{{name}}: {{runs}} practices in, everything it learned has become a habit.",+ "headline.subline": "{{habits}} habits · {{runs}} practices · lessons take effect as soon as they are learned; correct anything you see wrong",+ "headline.sublineMulti": "{{domains}} directions · {{habits}} habits · lessons take effect as soon as they are learned; correct anything you see wrong",+ "nav.newDomain": "Start a new direction",+ "nav.teach": "Teach it one",+ "nav.warmup": "Review past conversations",+ "profile.counts": "{{count}} habits",+ "profile.fresh": "{{count}} new",+ "profile.recurring": "{{count}} recurring",+ "profile.shaky": "{{count}} shaky",+ "profile.title": "Its profile in this direction",+ "profile.word.fresh": "just starting",+ "profile.word.mostlyStable": "mostly solid",+ "profile.word.stable": "solid",+ "profile.word.unstable": "slips sometimes",+ "profile.word.weak": "weak spot",+ "rules.allTitle": "All lessons",+ "rules.detail.domainUnavailable": "Direction context could not be loaded","rules.detail.examples": "Where it was tested",- "rules.detail.eyebrow": "Rule {{code}}",+ "rules.detail.eyebrow": "Lesson {{code}}","rules.detail.meta": "{{hits}} uses across {{runs}} practices","rules.detail.noExamples": "No recorded examples yet",- "rules.detail.noExamplesDesc": "This rule has not matched a later practice yet, so there is not enough evidence to judge whether it works.",- "rules.detail.notFound": "This rule no longer exists",+ "rules.detail.noExamplesDesc": "The example count and this list come from different reads. Nothing has been recorded here yet.",+ "rules.detail.notFound": "This lesson no longer exists","rules.detail.openSource": "Open source · {{title}}","rules.detail.outcome.pass": "Worked","rules.detail.outcome.violation": "Missed","rules.detail.retry": "Retry",- "rules.filter.all": "All rules",- "rules.filter.core": "Backbone",- "rules.filter.niche": "Situational",- "rules.filter.unused": "Never used",- "rules.hint.core": "used in almost every practice",- "rules.hint.niche": "only fires in specific situations",- "rules.hint.unused": "a rare case, or not a rule at all?",- "rules.hitCount": "Used {{count}} times",- "rules.hitsShort": "{{count}} uses",- "rules.neverUsedShort": "never used",- "rules.searchPlaceholder": "Search by rule title","rules.section.breaks": "What breaks","rules.section.correct": "Better approach","rules.section.dont": "Do not turn it into",@@ -152,22 +126,29 @@"rules.section.why": "Why","rules.section.works": "Why it works","rules.section.wrong": "Wrong approach",- "rules.stats": "{{total}} rules · {{hits}} hits · {{unused}} never used",- "rules.tier.core": "Backbone",- "rules.tier.niche": "Situational",- "rules.tier.unused": "Never used",- "rules.title": "Rules",- "rules.unanchored": "no anchor",- "rules.viewAll": "View all {{count}} rules",- "shape.declining": "turning down = losing ability",- "shape.flat": "flat = near the estimated ceiling",- "shape.fresh": "not practised yet",- "shape.rising": "still steep = still growing",- "shape.stuck": "hugging the floor = practising without learning",- "shape.tag.declining": "losing ability",- "shape.tag.flat": "near estimated ceiling",- "shape.tag.fresh": "not practised yet",- "shape.tag.rising": "growing",- "shape.tag.stuck": "not learning",- "title": "Self-evolving"+ "taught.arc.pending": "no chance to use yet",+ "taught.arc.recurring": "slipped again",+ "taught.arc.shaky": "goes either way",+ "taught.arc.used": "used ✓",+ "taught.title": "You taught it {{count}} things",+ "teachNew.domain": "Direction",+ "teachNew.help": "Say it in your words. It becomes a lesson tagged “you taught”, in effect from the next conversation.",+ "teachNew.placeholder": "e.g. When verifying a journalist, check their byline history before their social accounts…",+ "tier.fresh": "Just learned",+ "tier.freshSub": "not tested yet",+ "tier.recurring": "Recurring",+ "tier.recurringSub": "has the rule, keeps breaking it — worth teaching again",+ "tier.shaky": "Shaky",+ "tier.shakySub": "right sometimes, wrong sometimes",+ "tier.stable": "Formed",+ "tier.stableSub": "clean recently — nothing to check",+ "title": "Self-evolving",+ "warmup.dismiss": "OK",+ "warmup.done": "Review finished — {{learned}} lessons picked up and already in use. Every practice from now on tests them; anything unstable will surface here.",+ "warmup.failed": "Could not start the review. Try again.",+ "warmup.idle": "It has had {{count}} related conversations. Let it review them first to pick up what it already knows — lessons take effect right away.",+ "warmup.idleNone": "No past conversations to review yet. It starts learning from the next matching one.",+ "warmup.running": "Reviewing {{count}} past conversations… {{learned}} lessons so far",+ "warmup.start": "Review {{count}} past conversations",+ "warmup.title": "“{{name}}” is ready"}diff --git a/locales/zh-CN/selfLearning.json b/locales/zh-CN/selfLearning.jsonindex c0212b39216..266bcf05c2a 100644--- a/locales/zh-CN/selfLearning.json+++ b/locales/zh-CN/selfLearning.json@@ -1,173 +1,154 @@{- "anchor.choose": "就选这个方向",- "anchor.chooseFailed": "没能定下方向,再试一次。",- "anchor.howBody": "方向定下来之后不需要你再做别的:每一次符合判据的对话就算一次实践,规则从它做错的地方提取出来。像平常那样用它干活就行 —— 曲线是自己长出来的。",- "anchor.howTitle": "数据从哪儿来",- "anchor.noCandidates": "还没有可选的方向",- "anchor.noCandidatesDesc": "方向是从这个 agent 实际做过的事情里读出来的。先在你关心的那件事上真跑几次对话再回来 —— 它做得越多,给出的方向越准。",- "anchor.pending": "等你先定一个方向",- "anchor.pendingDesc": "领域是选择,不是发现 —— 同一个 agent 锚两次可能得到两个都成立的身份。定下来之后,下一次符合判据的对话它就开始长规则。",- "anchor.tag": "方向待定",- "anchor.traceCandidates": "{{count}} 个可选方向",- "anchor.traceCluster": "归纳重复出现的工作",- "anchor.traceConversations": "历史对话",- "anchor.traceHelp": "这不是系统推荐的第一名和第二名,而是同一批工作可以成立的两种边界。选择你希望这个专长以后在哪个范围里学习。",- "coverage.blankHint": "这一层从来没被考过",- "coverage.canon": "分层依据:{{source}}",- "coverage.gaps": "还没有规则",- "coverage.invented": "分层没有对应的经典模型",- "coverage.share": "{{title}} · {{count}} 条",- "coverage.sub": "{{covered}}/{{total}} 层有规则 · {{unused}} 条从没用上",- "coverage.title": "学到的东西落在哪儿",- "coverage.total": "共 {{count}} 条经验",- "create.back": "返回修改",- "create.briefHelp": "说清楚你想让它在什么事情上变强,以及什么不算。这句话会成为「哪些对话算这个专长的实践」的判据,名称我们从里面解析出来。",+ "anchor.filter": "什么算实践",+ "anchor.noCanon": "没有经典依据 —— 没法判断覆盖",+ "anchor.noLayers": "没有分层 —— 经验不按层归类",+ "anchor.outOfScope": "什么不算",+ "anchor.subtitle": "建域时定下的标准,它拿这些在学",+ "anchor.title": "它的锚",+ "charts.count": "{{count}} 条",+ "charts.early": "起步时 {{rate}}%",+ "charts.learned": "累计学到",+ "charts.learnedSub": "{{runs}} 次实践",+ "charts.passRate": "做对率",+ "charts.recentAvg": "最近 {{count}} 次平均",+ "charts.refLine": "90% 线",+ "charts.run1": "第 1 次",+ "charts.runN": "第 {{n}} 次",+ "charts.streak": "已连续 {{count}} 次实践零错",+ "charts.tooFew": "再练一次就有曲线了。",+ "create.anchor.addCanon": "添加",+ "create.anchor.addLayer": "添加",+ "create.anchor.canon": "经典依据",+ "create.anchor.canonHint": "它会被拿来对照的公认原则",+ "create.anchor.canonSource": "出处(书 / 框架)",+ "create.anchor.canonStatement": "一般性原则 —— 为什么这个错会反复出现",+ "create.anchor.canonTitle": "原则",+ "create.anchor.layerDesc": "这一层管什么,一句话",+ "create.anchor.layerTitle": "层名",+ "create.anchor.layers": "分层",+ "create.anchor.layersFrom": "来自 {{ref}}",+ "create.anchor.layersInvented": "没有合适的经典分层 —— 按你的描述提议的分层",+ "create.anchor.noCanon": "还没有经典依据 —— 它照样会学,但没法判断「覆盖」了没。",+ "create.anchor.noLayers": "还没有分层 —— 经验不会按层归类。",+ "create.back": "返回改一句话",+ "create.briefHelp": "说清楚你想让它在什么事情上变强,以及什么不算。这句话会成为「哪些对话算这个方向的实践」的判据,名称我们从里面解析出来。","create.briefPlaceholder": "例如:我想让它在处理线上故障上变强,从现象到根因再到防复发。方案讨论、通用运维问答都不算。","create.cancel": "取消",- "create.entry": "创建进化领域",- "create.failed": "没能创建,再试一次。",- "create.filterHelp": "一条可执行的判据:哪些对话算这个专长的实践,哪些不算。它是这个专长不至于什么都往里学的唯一守门人。",- "create.filterLabel": "什么算这个专长的实践",- "create.filterPlaceholder": "例如:对话在处理一个正在发生的线上故障,且有可观测到的现象。方案讨论、通用运维问答都不算。",- "create.generating": "正在自动生成进化领域…",- "create.modalTitle": "创建进化领域",- "create.parse": "继续",- "create.parsedFilter": "哪些对话算实践",- "create.parsedTitle": "专长名称",- "create.submit": "创建",- "create.titleLabel": "名称",- "create.titlePlaceholder": "例如:线上故障处置",- "detail.anchorTitle": "锚定这一步看出来的",- "detail.chart.count": "{{count}} 条",- "detail.chart.firstRun": "第 1 次",- "detail.chart.legendActual": "真实累计",- "detail.chart.legendBars": "柱 = 当次新增(蓝 = 你在对话里)",- "detail.chart.legendFit": "按现在的速度往后推",- "detail.chart.noProjection": "拟合不可靠({{reason}}),因此不做外推,也不给估算数字。",- "detail.chart.nthRun": "{{n}} 次",- "detail.chart.reach90": "预计第 {{run}} 次到 90%",- "detail.chart.remaining": "还要练 {{count}} 次",- "detail.chart.speculative": "这条外推只能当粗估:观测还没覆盖一个完整的学习周期,曲线尚未拐弯,上限是推出来的而不是测出来的。随着实践增加,第 {{n90}} 次这个数字会变。",- "detail.chart.title": "累计学到的经验 · 占估计上限的比例",- "detail.chart.today": "今天 · {{count}} 次",- "detail.chart.trustworthy": "按现在的速度,再练 {{remaining}} 次到 90%(第 {{n90}} 次)。",- "detail.domainFilter": "领域过滤器:",- "detail.firstPracticeDesc": "本次沉淀了 {{lessons}} 条经验。下一次匹配的实践完成后才会形成趋势,因此暂不展示曲线和成熟度估算。",- "detail.firstPracticeTitle": "第一次实践已记录",- "detail.headline": "练了 {{runs}} 次,学会 {{lessons}} 条。",- "detail.learningSummary": "从实践中沉淀了 {{lessons}} 条可复用经验。",- "detail.metric.cannot": "还需时间积累",- "detail.metric.maturity": "成熟度",- "detail.metric.maturitySub": "{{learned}} / 估计 {{ceiling}} 条",- "detail.metric.r2": "曲线贴合度",- "detail.metric.r2Sub": "基于 {{count}} 次实践",- "detail.metric.rate": "学习速度",- "detail.metric.rateSub": "每 {{tau}} 次实践走完一个学习周期",- "detail.metric.shape": "曲线形态",- "detail.metric.shapeSub": "后段还涨了 {{count}} 条",- "detail.notPractised": "还没练过",- "detail.notPractisedDesc": "方向已经定了。下一次有对话落进下面这条判据,它就开始长规则 —— 在那之前没有曲线可画。",- "detail.outOfScope": "范围外:",- "detail.practiceSummary": "来自 {{runs}} 次实践 · 记录了 {{hits}} 次验证命中",- "detail.shapeClause.growing": "曲线还在往上走",- "detail.shapeClause.noisy": "但曲线太噪,读不出趋势",- "detail.shapeClause.saturated": "曲线已经压平了",- "detail.shapeClause.stalled": "但曲线从没真正起来过",- "detail.subheadOk": "估计这个领域一共能学到 {{ceiling}} 条,{{shape}}。",- "detail.subheadUnusable": "拟合不可靠 —— 这个领域的成熟度还算不出来。",- "detail.totals": "{{runs}} 次实践 · {{lessons}} 条经验 · {{hits}} 次命中",- "empty.desc": "挑一件它经常做的事情定个方向,规则会从一次次真实实践里逐渐长出来。",+ "create.confirm": "创建",+ "create.failed": "方向没能创建,请重试。",+ "create.field.domainFilter": "什么算实践",+ "create.field.outOfScope": "什么不算",+ "create.field.outOfScopePlaceholder": "例:方案讨论、通用问答…",+ "create.field.title": "名称",+ "create.generate": "生成",+ "create.generating": "正在读你的描述…",+ "create.modalTitle": "开一个新方向",+ "create.next": "下一步",+ "create.regenerate": "重新生成",+ "create.reviewHelp": "这是它从你的描述里读出来的锚。看看有没有偏 —— 过滤器决定它从哪些对话里学;分层和经典依据决定经验挂在哪、「覆盖」意味着什么。",+ "create.reviewStep": "检查锚",+ "domains.meta": "{{habits}} 个习惯 · {{runs}} 次实践",+ "domains.title": "方向",+ "domains.word.fresh": "刚起步",+ "domains.word.recurring": "{{count}} 个老毛病",+ "domains.word.shaky": "{{count}} 个还不稳",+ "domains.word.stable": "都稳了",+ "empty.desc": "挑一件它经常做的事情定个方向,经验会从一次次真实实践里逐渐长出来。","empty.title": "用真实实践形成专长",- "headline.alsoDeclining": "{{name}}掉了头。",- "headline.alsoRising": "{{name}}还在陡着长,",- "headline.flat": "{{name}}正在接近当前估计上限。",- "headline.none": "还没有哪一项压平。",- "headline.rising": "{{name}}还在陡着长。",- "history.empty": "还没有可摄取的历史对话。",- "history.entry": "从历史对话学习",- "history.failed": "历史摄取没能启动,请重试。",- "history.started": "已开始摄取 {{count}} 个历史对话,提炼出的经验会陆续出现在这里。",- "insights.title": "这几十次下来,它自己看出来的",- "journey.count": "{{count}} 项",- "journey.step1": "定一个方向",- "journey.step1Desc": "说清楚什么算实践",- "journey.step2": "让它去干活",- "journey.step2Desc": "规则从真实对话里长出来",- "journey.step3": "看它走到哪儿",- "journey.step3Desc": "曲线开始能读了",- "layers.blank": "一条都没有",- "layers.count": "{{count}} 条",- "layers.fromCanon": "分层来自 {{source}}",- "layers.invented": "分层是自己发明的,没有对应的经典模型",- "layers.noteBody": "每个专长的分层由锚定阶段从它自己的经典推出来 —— 换个领域就是另一套。某一层为零,是 canonical 分层照出来的缺口,不是没渲染出来。",- "layers.noteTitle": "分层来自领域自己的 canon,不是全局枚举",- "layers.title": "它从哪几层学到东西",- "layers.unanchored": "有 {{count}} 条规则没锚到任何经典条目。",- "maturity.reason.low-confidence": "实践次数太少,或曲线波动太大,拟合不成立",- "maturity.reason.no-data": "还没练过",- "maturity.reason.pending": "还在算",- "maturity.reason.tau-pinned": "学习周期比已观测到的还长",- "overview.allDomains": "全部专长 {{count}}",- "overview.firstPractice": "首次实践",- "overview.noNumber": "还需时间积累",- "overview.rowMeta": "{{lessons}} 条 · 练过 {{runs}} 次",- "overview.soloNext": "点进去看它认哪些对话算实践 —— 下一次有对话对上,规则就开始长了。",- "overview.soloOpen": "点进去看曲线、它在哪几层学,以及已经攒下的每一条规则。",- "overview.totals": "{{domains}} 项专长 · 累计 {{lessons}} 条经验",- "overview.trendPending": "再实践一次后形成趋势",- "plateau.growing": "还在长",- "plateau.noisy": "噪声",- "plateau.saturated": "已饱和",- "plateau.stalled": "从没起来过",+ "habit.action.correct": "纠正这条",+ "habit.action.forget": "让它忘掉",+ "habit.action.source": "看它最近怎么用的",+ "habit.action.teachAgain": "再教一次",+ "habit.hint.freshNone": "还没机会检验",+ "habit.hint.freshOne": "用过 1 次",+ "habit.hint.recurring": "最近 {{total}} 次里错了 {{bad}} 次 · 上次在「{{topic}}」",+ "habit.hint.recurringNoTopic": "最近 {{total}} 次里错了 {{bad}} 次",+ "habit.hint.shaky": "最近 {{total}} 次里错了 1 次 · 在「{{topic}}」",+ "habit.hint.shakyNoTopic": "最近 {{total}} 次里错了 1 次",+ "habit.hint.stable": "{{count}} 次全对",+ "habit.hint.taughtPending": "你教的,等下次实践检验",+ "habit.recentTip.none": "还没检验过",+ "habit.recentTip.pass": "对",+ "habit.recentTip.title": "最近 {{count}} 次:{{list}}",+ "habit.recentTip.violation": "错",+ "habit.taughtTag": "你教的",+ "habit.teach.done": "教给它了 —— 下次对话开始带上。",+ "habit.teach.failed": "没存上,请重试。",+ "habit.teach.forgot": "已让它忘掉,之后不再练这条。",+ "habit.teach.placeholderCorrect": "哪里不对?用你的话说,它会并进这条经验里…",+ "habit.teach.placeholderRecurring": "告诉它什么情况下适用、什么情况下绝对不行…",+ "habit.teach.send": "教给它",+ "habits.search": "搜习惯",+ "habits.summary": "{{stable}} 个已养成 · {{shaky}} 个还不稳 · {{recurring}} 个老毛病 · {{fresh}} 个刚学",+ "habits.title": "它的习惯",+ "headline.detail.recurring": "「{{title}}」老是犯",+ "headline.detail.shaky": "有 {{count}} 个还时对时错",+ "headline.multi.ok": "{{domains}} 个方向学到的都已经养成习惯了。",+ "headline.single.fresh": "{{name}}练了 {{runs}} 次,学到 {{count}} 条,还没检验过。",+ "headline.single.notPracticed": "「{{name}}」方向已定,还没开始练。",+ "headline.single.recurring": "{{name}}练了 {{runs}} 次,习惯基本稳了。",+ "headline.single.shaky": "{{name}}练了 {{runs}} 次,大部分习惯稳了。",+ "headline.single.stable": "{{name}}练了 {{runs}} 次,学到的都已经养成习惯了。",+ "headline.subline": "{{habits}} 个习惯 · {{runs}} 次实践 · 经验即学即用,看到不对的随手教",+ "headline.sublineMulti": "{{domains}} 个方向 · {{habits}} 个习惯 · 经验即学即用,看到不对的随手教",+ "nav.newDomain": "开新方向",+ "nav.teach": "直接教它一条",+ "nav.warmup": "温习历史对话",+ "profile.counts": "{{count}} 个习惯",+ "profile.fresh": "{{count}} 个刚学",+ "profile.recurring": "{{count}} 个老犯",+ "profile.shaky": "{{count}} 个还不稳",+ "profile.title": "它在这个方向的画像",+ "profile.word.fresh": "刚起步",+ "profile.word.mostlyStable": "基本稳",+ "profile.word.stable": "很稳",+ "profile.word.unstable": "出过错",+ "profile.word.weak": "短板","rules.allTitle": "全部经验",- "rules.detail.domainUnavailable": "领域上下文加载失败",+ "rules.detail.domainUnavailable": "方向信息没能加载","rules.detail.examples": "在哪些实践里验证过","rules.detail.eyebrow": "经验 {{code}}","rules.detail.meta": "命中 {{hits}} 次 · 覆盖 {{runs}} 次实践",- "rules.detail.noExamples": "还没有记录到实例",- "rules.detail.noExamplesDesc": "这条经验还没有在后续实践中再次命中,暂时没有足够证据判断它是否有效。",- "rules.detail.notFound": "这条经验已经不存在",+ "rules.detail.noExamples": "还没有记录到例子",+ "rules.detail.noExamplesDesc": "例子计数和这份列表来自不同的读取,这里暂时还没有记录。",+ "rules.detail.notFound": "这条经验已经不存在了","rules.detail.openSource": "打开来源 · {{title}}","rules.detail.outcome.pass": "有效",- "rules.detail.outcome.violation": "失效",+ "rules.detail.outcome.violation": "未奏效","rules.detail.retry": "重试",- "rules.filter.all": "全部规则",- "rules.filter.core": "骨干",- "rules.filter.niche": "专用",- "rules.filter.unused": "没用上过",- "rules.hint.core": "几乎每次实践都用得上",- "rules.hint.niche": "只在特定情形下触发",- "rules.hint.unused": "是罕见情形,还是它本来就不算一条规则?",- "rules.hitCount": "命中 {{count}} 次",- "rules.hitsShort": "用上 {{count}} 次",- "rules.neverUsedShort": "没用上过",- "rules.searchPlaceholder": "按经验标题搜索",- "rules.section.breaks": "会造成什么问题",- "rules.section.correct": "正确做法",- "rules.section.dont": "不要退化成",- "rules.section.good": "有效做法",+ "rules.section.breaks": "会出什么问题",+ "rules.section.correct": "更好的做法",+ "rules.section.dont": "别把它变成",+ "rules.section.good": "怎样做有效","rules.section.how": "如何使用",- "rules.section.limits": "不适用的情况",+ "rules.section.limits": "什么时候不适用","rules.section.rule": "判据","rules.section.why": "为什么","rules.section.works": "为什么有效","rules.section.wrong": "错误做法",- "rules.stats": "{{total}} 条 · 命中 {{hits}} 次 · {{unused}} 条从没用上",- "rules.tier.core": "骨干",- "rules.tier.niche": "专用",- "rules.tier.unused": "没用上过",- "rules.title": "经验",- "rules.unanchored": "没锚点",- "rules.viewAll": "查看全部 {{count}} 条经验",- "shape.declining": "掉头 = 能力在退",- "shape.flat": "压平了 = 接近估计上限",- "shape.fresh": "还没练过",- "shape.rising": "还在陡 = 在长",- "shape.stuck": "贴着底 = 练了没学到",- "shape.tag.declining": "能力在退",- "shape.tag.flat": "接近估计上限",- "shape.tag.fresh": "还没练过",- "shape.tag.rising": "在长",- "shape.tag.stuck": "练了没学到",- "title": "自进化"+ "taught.arc.pending": "还没机会用",+ "taught.arc.recurring": "又犯了",+ "taught.arc.shaky": "时对时错",+ "taught.arc.used": "用上了 ✓",+ "taught.title": "你教过它 {{count}} 件事",+ "teachNew.domain": "方向",+ "teachNew.help": "用你的话说就行。它会整理成一条经验,标「你教的」,下次对话生效。",+ "teachNew.placeholder": "例:接到媒体身份核实时,先查记者的历史署名报道再看社交账号…",+ "tier.fresh": "刚学的",+ "tier.freshSub": "还没机会检验",+ "tier.recurring": "老毛病",+ "tier.recurringSub": "有规则却反复犯 —— 最值得你再教一次",+ "tier.shaky": "还不稳",+ "tier.shakySub": "时对时错",+ "tier.stable": "已养成",+ "tier.stableSub": "最近全对 —— 平时不用看",+ "title": "自进化",+ "warmup.dismiss": "知道了",+ "warmup.done": "温习完成 —— 学到 {{learned}} 条经验,已经开始用了。之后每次实践都会检验它们,哪条不稳会浮上来。",+ "warmup.failed": "温习没能启动,请重试。",+ "warmup.idle": "它做过 {{count}} 个相关对话。让它先温习一遍把经验捡起来 —— 学到的立刻开始用。",+ "warmup.idleNone": "还没有可温习的历史对话,下一次匹配的对话就会开始学。",+ "warmup.running": "正在温习 {{count}} 个历史对话… 已学到 {{learned}} 条",+ "warmup.start": "让它温习 {{count}} 个历史对话",+ "warmup.title": "「{{name}}」已就绪"}diff --git a/packages/database/src/models/expertise.ts b/packages/database/src/models/expertise.tsindex 969046366cd..c701a28d30d 100644--- a/packages/database/src/models/expertise.ts+++ b/packages/database/src/models/expertise.ts@@ -1,3 +1,9 @@+import type {+ ExpertiseAnchorCandidate,+ ExpertiseCanonEntry,+ ExpertiseLayerDefinition,+ ExpertiseLessonSection,+} from '@lobechat/types';import { and, asc, desc, eq, inArray, isNotNull, isNull, or, sql } from 'drizzle-orm';import {@@ -7,6 +13,7 @@ import {expertiseDomainSnapshots,expertiseHits,expertiseInsights,+ expertiseLessonRevisions,expertiseLessons,expertiseRuns,topics,@@ -116,6 +123,107 @@ export class ExpertiseModel {.orderBy(asc(expertiseDomainSnapshots.domainId), asc(expertiseDomainSnapshots.runIndex));};+ /**+ * Per-run pass/violation counts — the reliability series behind the "做对率" chart.+ * A run without hits produces no row; callers treat missing runs as "nothing to judge".+ */+ reliabilitySeries = async (domainIds: string[]) => {+ if (domainIds.length === 0) return [];+ return this.db+ .select({+ domainId: expertiseHits.domainId,+ pass: sql<number>`count(*) filter (where ${expertiseHits.outcome} = 'pass')::int`,+ runIndex: expertiseRuns.runIndex,+ violation: sql<number>`count(*) filter (where ${expertiseHits.outcome} = 'violation')::int`,+ })+ .from(expertiseHits)+ .innerJoin(expertiseRuns, eq(expertiseRuns.id, expertiseHits.runId))+ .where(inArray(expertiseHits.domainId, domainIds))+ .groupBy(expertiseHits.domainId, expertiseRuns.runIndex)+ .orderBy(asc(expertiseHits.domainId), asc(expertiseRuns.runIndex));+ };++ /**+ * Active lessons for the portrait, each with its most recent hit outcomes (newest last).+ * Recent outcomes are what the client folds into a reliability tier; the topic title of each+ * hit lets the row say *where* it last went wrong without another query.+ */+ listLessonsWithRecent = async (domainIds: string[], recentLimit = 6) => {+ if (domainIds.length === 0) return [];+ const lessons = await this.db+ .select({+ code: expertiseLessons.code,+ createdAt: expertiseLessons.createdAt,+ createdByUserId: expertiseLessons.createdByUserId,+ domainId: expertiseLessons.domainId,+ hitCount: expertiseLessons.hitCount,+ id: expertiseLessons.id,+ lastHitAt: expertiseLessons.lastHitAt,+ layer: expertiseLessons.layer,+ title: expertiseLessons.title,+ })+ .from(expertiseLessons)+ .where(+ and(inArray(expertiseLessons.domainId, domainIds), eq(expertiseLessons.status, 'active')),+ )+ .orderBy(desc(expertiseLessons.hitCount), asc(expertiseLessons.code));++ const ranked = this.db.$with('ranked').as(+ this.db+ .select({+ lessonId: expertiseHits.lessonId,+ outcome: expertiseHits.outcome,+ rn: sql<number>`row_number() over (partition by ${expertiseHits.lessonId} order by ${expertiseRuns.runIndex} desc, ${expertiseHits.createdAt} desc)`.as(+ 'rn',+ ),+ runIndex: expertiseRuns.runIndex,+ subjectId: expertiseRuns.subjectId,+ subjectType: expertiseRuns.subjectType,+ })+ .from(expertiseHits)+ .innerJoin(expertiseRuns, eq(expertiseRuns.id, expertiseHits.runId))+ .where(inArray(expertiseHits.domainId, domainIds)),+ );+ const recentRows = await this.db+ .with(ranked)+ .select({+ lessonId: ranked.lessonId,+ outcome: ranked.outcome,+ rn: ranked.rn,+ runIndex: ranked.runIndex,+ subjectId: ranked.subjectId,+ subjectTitle: topics.title,+ subjectType: ranked.subjectType,+ })+ .from(ranked)+ .leftJoin(topics, and(eq(ranked.subjectType, 'topic'), eq(topics.id, ranked.subjectId)))+ .where(sql`${ranked.rn} <= ${recentLimit}`)+ .orderBy(asc(ranked.lessonId), desc(ranked.rn));++ const recentByLesson = new Map<+ string,+ {+ pass: boolean;+ runIndex: number;+ subjectId: string;+ subjectTitle: string | null;+ subjectType: string;+ }[]+ >();+ for (const r of recentRows) {+ const list = recentByLesson.get(r.lessonId) ?? [];+ list.push({+ pass: r.outcome === 'pass',+ runIndex: r.runIndex,+ subjectId: r.subjectId,+ subjectTitle: r.subjectTitle,+ subjectType: r.subjectType,+ });+ recentByLesson.set(r.lessonId, list);+ }+ return lessons.map((l) => ({ ...l, recent: recentByLesson.get(l.id) ?? [] }));+ };+/** Lists the agents that have practiced each domain. */actorsByDomain = async (domainIds: string[]) => {if (domainIds.length === 0) return [];@@ -285,12 +393,20 @@ export class ExpertiseModel {// Writes- /** Persists a model-generated domain definition and binds it to the selected agent. */+ /**+ * Persists a reviewed anchor and binds it to the selected agent.+ * The chosen candidate is also kept in anchorCandidates so the alternative can be revisited.+ */createDomain = async (params: {agentId: string;brief: string;+ canonEntries?: ExpertiseCanonEntry[];domainFilter: string;+ layerCanonRef?: string;+ layerSource?: 'canonical' | 'invented';+ layers?: ExpertiseLayerDefinition[];outOfScope?: string;+ rationale?: string;title: string;}) => {const brief = params.brief.trim();@@ -298,15 +414,33 @@ export class ExpertiseModel {const title = params.title.trim();const domainFilter = params.domainFilter.trim();const slug = `${title.slice(0, 40).replaceAll(/\s+/g, '-').toLowerCase()}-${id.slice(-6)}`;+ const layers = params.layers ?? [];+ const canonEntries = params.canonEntries ?? [];+ const layerSource = params.layerSource ?? 'invented';+ const candidate: ExpertiseAnchorCandidate = {+ canonEntries,+ domainFilter,+ key: 'chosen',+ layerCanonRef: params.layerCanonRef,+ layers,+ layerSource,+ outOfScope: params.outOfScope?.trim() || undefined,+ rationale: params.rationale?.trim() || undefined,+ title,+ };await this.db.transaction(async (tx) => {await tx.insert(expertiseDomains).values({+ anchorCandidates: [candidate],anchorChosenAt: new Date(),anchorChosenByUserId: this.userId,+ canonEntries,description: brief,domainFilter,- outOfScope: params.outOfScope?.trim() || null,id,+ layerSource,+ layers,+ outOfScope: params.outOfScope?.trim() || null,seedState: 'seeded',slug,title,@@ -323,6 +457,78 @@ export class ExpertiseModel {return id;};+ /** Stores a lesson the user taught directly; it takes effect on the next matching practice. */+ teachLesson = async (params: { domainId: string; text: string }) => {+ const domain = await this.findDomain(params.domainId);+ if (!domain) return null;+ const text = params.text.trim();+ const title = text.length > 80 ? `${text.slice(0, 79)}…` : text;+ return this.db.transaction(async (tx) => {+ const codes = await tx+ .select({ code: expertiseLessons.code })+ .from(expertiseLessons)+ .where(eq(expertiseLessons.domainId, params.domainId));+ const next =+ Math.max(0, ...codes.map(({ code }) => Number(/^P-(\d+)$/.exec(code)?.[1] ?? 0))) + 1;+ const code = `P-${String(next).padStart(2, '0')}`;+ const [row] = await tx+ .insert(expertiseLessons)+ .values({+ code,+ createdByUserId: this.userId,+ domainId: params.domainId,+ polarity: 'rule',+ sections: [{ body: text, key: 'rule' }],+ title,+ })+ .returning({ code: expertiseLessons.code, id: expertiseLessons.id });+ return row;+ });+ };++ /**+ * Records the user's correction as a new revision and folds it into the lesson body.+ * The correction is kept as its own section so the original judgment stays legible.+ */+ reviseLesson = async (lessonId: string, feedback: string) => {+ const lesson = await this.findLesson(lessonId);+ if (!lesson) return null;+ const text = feedback.trim();+ const sections: ExpertiseLessonSection[] = [+ ...lesson.sections.filter((s) => s.key !== 'limits'),+ { body: text, key: 'limits' },+ ];+ const revision = lesson.currentRevision + 1;+ await this.db.transaction(async (tx) => {+ await tx.insert(expertiseLessonRevisions).values({+ changedBy: 'user',+ changedByUserId: this.userId,+ feedback: text,+ kind: 'user-feedback',+ lessonId,+ prevTitle: lesson.title,+ revision,+ sections,+ });+ await tx+ .update(expertiseLessons)+ .set({ currentRevision: revision, sections, updatedAt: new Date() })+ .where(eq(expertiseLessons.id, lessonId));+ });+ return { id: lessonId, revision };+ };++ /** 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);+ if (!lesson) return null;+ await this.db+ .update(expertiseLessons)+ .set({ retiredAt: new Date(), status: 'retired', updatedAt: new Date() })+ .where(eq(expertiseLessons.id, lessonId));+ return { id: lessonId };+ };+// InsightslistInsights = async (domainIds: string[]) => {diff --git a/packages/locales/src/default/selfLearning.ts b/packages/locales/src/default/selfLearning.tsindex daebf71a07a..813777fdc73 100644--- a/packages/locales/src/default/selfLearning.ts+++ b/packages/locales/src/default/selfLearning.ts@@ -1,121 +1,139 @@export default {- 'anchor.pending': 'Waiting for you to pick a direction',- 'anchor.pendingDesc':- 'A domain is a choice, not a discovery — the same agent can be anchored two different ways and both are correct. Pick one and it starts building rules from the very next matching conversation.',- 'anchor.tag': 'Direction not picked',+ 'anchor.filter': 'Counts as practice',+ 'anchor.noCanon': 'no canon — coverage cannot be judged',+ 'anchor.noLayers': 'no layers — lessons are not grouped by level',+ 'anchor.outOfScope': 'Does not count',+ 'anchor.subtitle': 'the standard it learns against, set when the direction was created',+ 'anchor.title': 'Its anchor',+ 'charts.count': '{{count}} lessons',+ 'charts.early': 'started at {{rate}}%',+ 'charts.learned': 'Learned so far',+ 'charts.learnedSub': '{{runs}} practices',+ 'charts.passRate': 'Done right',+ 'charts.recentAvg': 'average of the last {{count}}',+ 'charts.refLine': '90% line',+ 'charts.run1': 'run 1',+ 'charts.runN': 'run {{n}}',+ 'charts.streak': '{{count}} practices in a row with no mistakes',+ 'charts.tooFew': 'Curves appear after the second practice.',- 'detail.anchorTitle': 'What the anchoring step saw',- 'detail.chart.count': '{{count}}',- 'detail.chart.firstRun': 'run 1',- 'detail.chart.legendActual': 'actual',- 'detail.chart.legendBars': 'bars = learned that round (blue = you were in the conversation)',- 'detail.chart.legendFit': 'projected at the current pace',- 'detail.chart.noProjection':- 'The fit is not reliable ({{reason}}), so no projection is drawn and no estimated number is shown.',- 'detail.chart.nthRun': 'run {{n}}',- 'detail.chart.reach90': 'projected to hit 90% at run {{run}}',- 'detail.chart.remaining': '{{count}} more practices',- 'detail.chart.speculative':- 'Treat this projection as a rough estimate: the observation has not yet covered a full learning cycle, so the curve has not turned and the ceiling is inferred rather than measured. Run {{n90}} will move as more practice comes in.',- 'detail.chart.title': 'Rules learned, as a share of the estimated ceiling',- 'detail.chart.today': 'today · {{count}} practices',- 'detail.chart.trustworthy':- 'At the current pace, {{remaining}} more practices reach 90% (run {{n90}}).',- 'detail.domainFilter': 'Domain filter: ',- 'detail.headline': 'Practised {{runs}} times, learned {{lessons}} rules.',- 'detail.firstPracticeDesc':- '{{lessons}} rules were captured. A trend appears after the next matching practice, so there is no curve or maturity estimate yet.',- 'detail.firstPracticeTitle': 'The first practice is recorded',- 'detail.learningSummary': '{{lessons}} reusable rules distilled from practice.',- 'detail.metric.cannot': 'needs more practice',- 'detail.metric.maturity': 'Maturity',- 'detail.metric.maturitySub': '{{learned}} of an estimated {{ceiling}}',- 'detail.metric.r2': 'Curve fit',- 'detail.metric.r2Sub': 'across {{count}} practices',- 'detail.metric.rate': 'Learning speed',- 'detail.metric.rateSub': 'one learning cycle per {{tau}} practices',- 'detail.metric.shape': 'Curve shape',- 'detail.metric.shapeSub': 'gained {{count}} in the tail',- 'detail.notPractised': 'Not practised yet',- 'detail.notPractisedDesc':- 'The direction is set. It starts building rules the next time a conversation matches the filter below — nothing to chart until then.',- 'detail.outOfScope': 'Out of scope: ',- 'detail.practiceSummary': 'From {{runs}} practices · {{hits}} recorded validation hits',- 'detail.shapeClause.growing': 'and the curve is still climbing',- 'detail.shapeClause.noisy': 'though the curve is too noisy to read',- 'detail.shapeClause.saturated': 'and the curve has flattened',- 'detail.shapeClause.stalled': 'but the curve never really got going',- 'detail.subheadOk': 'The estimated ceiling for this domain is {{ceiling}} rules, {{shape}}.',- 'detail.subheadUnusable': 'The fit is not usable — maturity cannot be computed for this domain.',- 'detail.totals': '{{runs}} practices · {{lessons}} rules · {{hits}} hits',+ 'create.anchor.addCanon': 'Add',+ 'create.anchor.addLayer': 'Add',+ 'create.anchor.canon': 'Canon',+ 'create.anchor.canonHint': 'the recognised principles it will be judged against',+ 'create.anchor.canonSource': 'source (book / framework)',+ 'create.anchor.canonStatement': 'the general principle — why this failure recurs',+ 'create.anchor.canonTitle': 'principle',+ 'create.anchor.layerDesc': 'one line on what this layer covers',+ 'create.anchor.layers': 'Layers',+ 'create.anchor.layersFrom': 'from {{ref}}',+ 'create.anchor.layersInvented': 'no canonical model fits — layers proposed from the brief',+ 'create.anchor.layerTitle': 'layer',+ 'create.anchor.noCanon': 'No canon yet — it will still learn, but coverage cannot be judged.',+ 'create.anchor.noLayers': 'No layers yet — lessons will not be grouped by level.',+ 'create.back': 'Back',+ 'create.briefHelp':+ 'Say what you want it to get better at, and what does not count. This sentence becomes the test for which conversations count as practice in this direction; we work out the name from it.',+ 'create.briefPlaceholder':+ 'e.g. I want it to get better at handling production incidents — from symptom to root cause to prevention. Design discussions and general ops Q&A do not count.',+ 'create.cancel': 'Cancel',+ 'create.confirm': 'Create',+ 'create.failed': 'Could not create the direction. Try again.',+ 'create.field.domainFilter': 'What counts as practice',+ 'create.field.outOfScope': 'What does not count',+ 'create.field.outOfScopePlaceholder': 'e.g. design discussions, general Q&A…',+ 'create.field.title': 'Name',+ 'create.generate': 'Generate',+ 'create.generating': 'Reading your brief…',+ 'create.modalTitle': 'Start a new direction',+ 'create.next': 'Next',+ 'create.regenerate': 'Regenerate',+ 'create.reviewHelp':+ 'Here is the anchor it read out of your brief. Fix anything that is off — the filter decides which conversations it learns from; the layers and canon decide where lessons attach and what “coverage” means.',+ 'create.reviewStep': 'Review the anchor',++ 'domains.meta': '{{habits}} habits · {{runs}} practices',+ 'domains.title': 'Directions',+ 'domains.word.fresh': 'just starting',+ 'domains.word.recurring': '{{count}} recurring',+ 'domains.word.shaky': '{{count}} shaky',+ 'domains.word.stable': 'all solid','empty.desc':- 'Point it at something it does often, and rules will grow out of repeated real practice.',+ 'Point it at something it does often, and lessons will grow out of repeated real practice.','empty.title': 'Turn real work into expertise',- 'headline.alsoDeclining': ' {{name}} has turned back down.',- 'headline.alsoRising': ' {{name}} is still climbing steeply.',- 'headline.flat': '{{name}} is approaching its current estimated ceiling.',- 'headline.none': 'None of them has flattened yet.',- 'headline.rising': '{{name}} is still climbing steeply.',-- 'history.empty': 'There are no existing conversations to import.',- 'history.entry': 'Learn from history',- 'history.failed': 'Historical learning could not be started. Try again.',- 'history.started':- 'Started learning from {{count}} existing conversations. New experience will appear here as it is distilled.',- 'insights.title': 'What it noticed across all these practices',+ 'habit.action.correct': 'Correct this',+ 'habit.action.forget': 'Let it forget',+ 'habit.action.source': 'See how it used this',+ 'habit.action.teachAgain': 'Teach it again',+ 'habit.hint.freshNone': 'no chance to test yet',+ 'habit.hint.freshOne': 'used once',+ 'habit.hint.recurring': 'wrong {{bad}} of the last {{total}} times · last in “{{topic}}”',+ 'habit.hint.recurringNoTopic': 'wrong {{bad}} of the last {{total}} times',+ 'habit.hint.shaky': 'wrong once in the last {{total}} · in “{{topic}}”',+ 'habit.hint.shakyNoTopic': 'wrong once in the last {{total}}',+ 'habit.hint.stable': '{{count}} times, all right',+ 'habit.hint.taughtPending': 'you taught this; waiting for the next practice',+ 'habit.recentTip.none': 'not tested yet',+ 'habit.recentTip.pass': 'right',+ 'habit.recentTip.title': 'last {{count}}: {{list}}',+ 'habit.recentTip.violation': 'wrong',+ 'habit.taughtTag': 'you taught',+ 'habit.teach.done': 'Taught — it carries this from the next conversation.',+ 'habit.teach.failed': 'Could not save that. Try again.',+ 'habit.teach.forgot': 'Forgotten. It will not practice this anymore.',+ 'habit.teach.placeholderCorrect':+ 'What is off? Say it in your words — it folds this into the lesson…',+ 'habit.teach.placeholderRecurring': 'Tell it when this applies and when it absolutely does not…',+ 'habit.teach.send': 'Teach it',+ 'habits.search': 'Search habits',+ 'habits.summary': '{{stable}} formed · {{shaky}} shaky · {{recurring}} recurring · {{fresh}} new',+ 'habits.title': 'Its habits',- 'layers.blank': 'nothing yet',- 'layers.count': '{{count}}',- 'layers.fromCanon': 'Layers from {{source}}',- 'layers.invented': 'Layers made up — no canonical model',- 'layers.noteBody':- 'Each expertise gets its layers from its own canon during anchoring — a different domain means a different set. A layer at zero is a gap the canonical model exposed, not a rendering hole.',- 'layers.noteTitle': 'Layers come from the domain’s own canon, not a global enum',- 'layers.title': 'Which layers it learns at',- 'layers.unanchored': '{{count}} rules are not anchored to any canonical entry.',+ 'headline.multi.ok': 'Across {{domains}} directions, everything it learned has become a habit.',+ 'headline.single.fresh':+ '{{name}}: {{runs}} practice in, {{count}} lessons captured, none tested yet.',+ 'headline.single.notPracticed': '{{name}} is set as a direction — nothing practiced yet.',+ 'headline.detail.recurring': '“{{title}}” keeps going wrong',+ 'headline.detail.shaky': '{{count}} habits still go either way',+ 'headline.single.recurring': '{{name}}: {{runs}} practices in, habits are mostly solid.',+ 'headline.single.shaky': '{{name}}: {{runs}} practices in, most habits are solid.',+ 'headline.single.stable':+ '{{name}}: {{runs}} practices in, everything it learned has become a habit.',+ 'headline.subline':+ '{{habits}} habits · {{runs}} practices · lessons take effect as soon as they are learned; correct anything you see wrong',+ 'headline.sublineMulti':+ '{{domains}} directions · {{habits}} habits · lessons take effect as soon as they are learned; correct anything you see wrong',- 'maturity.reason.low-confidence': 'too few practices, or the curve is too erratic to fit',- 'maturity.reason.no-data': 'never practised',- 'maturity.reason.pending': 'still computing',- 'maturity.reason.tau-pinned': 'the learning cycle is longer than what has been observed',+ 'nav.newDomain': 'Start a new direction',+ 'nav.teach': 'Teach it one',+ 'nav.warmup': 'Review past conversations',- 'overview.allDomains': 'All {{count}} expertises',- 'overview.firstPractice': 'first practice',- 'overview.noNumber': 'needs more practice',- 'overview.rowMeta': '{{lessons}} rules · practised {{runs}} times',- 'overview.totals': '{{domains}} expertises · {{lessons}} rules in total',- 'overview.trendPending': 'trend after the next practice',+ 'profile.counts': '{{count}} habits',+ 'profile.fresh': '{{count}} new',+ 'profile.recurring': '{{count}} recurring',+ 'profile.shaky': '{{count}} shaky',+ 'profile.title': 'Its profile in this direction',+ 'profile.word.fresh': 'just starting',+ 'profile.word.mostlyStable': 'mostly solid',+ 'profile.word.stable': 'solid',+ 'profile.word.unstable': 'slips sometimes',+ 'profile.word.weak': 'weak spot',- 'plateau.growing': 'growing',- 'plateau.noisy': 'noisy',- 'plateau.saturated': 'saturated',- 'plateau.stalled': 'stalled',-- 'rules.hint.core': 'used in almost every practice',- 'rules.hint.niche': 'only fires in specific situations',- 'rules.hint.unused': 'a rare case, or not a rule at all?',- 'rules.stats': '{{total}} rules · {{hits}} hits · {{unused}} never used',- 'rules.tier.core': 'Backbone',- 'rules.tier.niche': 'Situational',- 'rules.tier.unused': 'Never used',- 'rules.title': 'Rules',- 'rules.unanchored': 'no anchor',- 'rules.viewAll': 'View all {{count}} rules',- 'rules.allTitle': 'All rules',+ 'rules.allTitle': 'All lessons',+ 'rules.detail.domainUnavailable': 'Direction context could not be loaded','rules.detail.examples': 'Where it was tested',- 'rules.detail.eyebrow': 'Rule {{code}}',+ 'rules.detail.eyebrow': 'Lesson {{code}}','rules.detail.meta': '{{hits}} uses across {{runs}} practices',- 'rules.detail.domainUnavailable': 'Domain context could not be loaded','rules.detail.noExamples': 'No recorded examples yet','rules.detail.noExamplesDesc':- 'This rule has not matched a later practice yet, so there is not enough evidence to judge whether it works.',+ 'The example count and this list come from different reads. Nothing has been recorded here yet.',+ 'rules.detail.notFound': 'This lesson no longer exists','rules.detail.openSource': 'Open source · {{title}}',- 'rules.detail.retry': 'Retry',- 'rules.detail.notFound': 'This rule no longer exists','rules.detail.outcome.pass': 'Worked','rules.detail.outcome.violation': 'Missed',+ 'rules.detail.retry': 'Retry','rules.section.breaks': 'What breaks','rules.section.correct': 'Better approach','rules.section.dont': 'Do not turn it into',@@ -127,77 +145,38 @@ export default {'rules.section.works': 'Why it works','rules.section.wrong': 'Wrong approach',- 'shape.declining': 'turning down = losing ability',- 'shape.flat': 'flat = near the estimated ceiling',- 'shape.rising': 'still steep = still growing',- 'shape.stuck': 'hugging the floor = practising without learning',- 'shape.fresh': 'not practised yet',- 'shape.tag.declining': 'losing ability',- 'shape.tag.flat': 'near estimated ceiling',- 'shape.tag.fresh': 'not practised yet',- 'shape.tag.rising': 'growing',- 'shape.tag.stuck': 'not learning',+ 'taught.arc.pending': 'no chance to use yet',+ 'taught.arc.recurring': 'slipped again',+ 'taught.arc.shaky': 'goes either way',+ 'taught.arc.used': 'used ✓',+ 'taught.title': 'You taught it {{count}} things',++ 'teachNew.domain': 'Direction',+ 'teachNew.help':+ 'Say it in your words. It becomes a lesson tagged “you taught”, in effect from the next conversation.',+ 'teachNew.placeholder':+ 'e.g. When verifying a journalist, check their byline history before their social accounts…',++ 'tier.fresh': 'Just learned',+ 'tier.freshSub': 'not tested yet',+ 'tier.recurring': 'Recurring',+ 'tier.recurringSub': 'has the rule, keeps breaking it — worth teaching again',+ 'tier.shaky': 'Shaky',+ 'tier.shakySub': 'right sometimes, wrong sometimes',+ 'tier.stable': 'Formed',+ 'tier.stableSub': 'clean recently — nothing to check',- 'anchor.choose': 'Take this direction',- 'anchor.chooseFailed': 'Could not set the direction. Try again.',- 'anchor.noCandidates': 'No directions proposed yet',- 'anchor.noCandidatesDesc':- 'Directions are read out of what this agent has actually been doing. Have a few real conversations in the area you care about, then come back — the more it has done, the sharper the proposals.',- 'anchor.traceCandidates': '{{count}} possible directions',- 'anchor.traceCluster': 'Recurring work grouped',- 'anchor.traceConversations': 'Past conversations',- 'anchor.traceHelp':- 'These are two valid ways to define the same body of work, not a system recommendation. Pick the boundary you want this expertise to learn within.',- 'create.cancel': 'Cancel',- 'create.back': 'Back',- 'create.entry': 'Create an expertise',- 'create.failed': 'Could not create it. Try again.',- 'create.generating': 'Generating the expertise…',- 'create.filterHelp':- 'One executable test: which conversations count as practice for this expertise, and which do not. This is what keeps it from learning from everything.',- 'create.filterLabel': 'What counts as practice',- 'create.filterPlaceholder':- 'e.g. the conversation is diagnosing a live incident with observable symptoms. Design discussions and general ops questions do not count.',- 'create.modalTitle': 'Create an expertise',- 'create.parse': 'Continue',- 'create.parsedFilter': 'Conversations that count as practice',- 'create.parsedTitle': 'Expertise name',- 'create.submit': 'Create',- 'create.titleLabel': 'Name',- 'create.titlePlaceholder': 'e.g. Incident response',- 'coverage.blankHint': 'never tested at this layer',- 'coverage.canon': 'Layer model: {{source}}',- 'coverage.gaps': 'No rules yet',- 'coverage.invented': 'Layer model has no canonical source',- 'coverage.share': '{{title}} · {{count}} rules',- 'coverage.total': '{{count}} lessons total',- 'coverage.sub': '{{covered}}/{{total}} layers have rules · {{unused}} rules never used',- 'coverage.title': 'Where the learning has landed',- 'create.briefHelp':- 'Say what you want it to get good at, and what does not count. That sentence becomes the test for which conversations feed this expertise — we work the name out from it.',- 'create.briefPlaceholder':- 'e.g. I want it to get better at handling live incidents — from symptom to root cause to prevention. Design discussions and general ops questions do not count.',- 'journey.count': '{{count}} expertises',- 'journey.step1': 'Pick a direction',- 'journey.step1Desc': 'what counts as practice',- 'journey.step2': 'Let it do the work',- 'journey.step2Desc': 'rules come from real conversations',- 'journey.step3': 'Read where it stands',- 'journey.step3Desc': 'the curve becomes readable',- 'rules.hitsShort': '{{count}} uses',- 'rules.hitCount': 'Used {{count}} times',- 'rules.filter.all': 'All rules',- 'rules.filter.core': 'Backbone',- 'rules.filter.niche': 'Situational',- 'rules.filter.unused': 'Never used',- 'rules.searchPlaceholder': 'Search by rule title',- 'rules.neverUsedShort': 'never used',- 'overview.soloNext':- 'Open it to see what counts as practice — the rules start coming the next time a conversation matches.',- 'overview.soloOpen':- 'Open it for the curve, the layers it learns at, and every rule it has picked up.',- 'anchor.howTitle': 'Where the data comes from',- 'anchor.howBody':- 'Once a direction is set, nothing else is required of you: every conversation that matches its filter counts as one practice, and the rules are extracted from the places it got things wrong. Work with it the way you normally would — the curve fills itself in.','title': 'Self-evolving',++ 'warmup.dismiss': 'OK',+ 'warmup.done':+ 'Review finished — {{learned}} lessons picked up and already in use. Every practice from now on tests them; anything unstable will surface here.',+ 'warmup.failed': 'Could not start the review. Try again.',+ 'warmup.idle':+ 'It has had {{count}} related conversations. Let it review them first to pick up what it already knows — lessons take effect right away.',+ 'warmup.idleNone':+ 'No past conversations to review yet. It starts learning from the next matching one.',+ 'warmup.running': 'Reviewing {{count}} past conversations… {{learned}} lessons so far',+ 'warmup.start': 'Review {{count}} past conversations',+ 'warmup.title': '“{{name}}” is ready',};diff --git a/src/features/SelfLearning/CoverageCloud.tsx b/src/features/SelfLearning/CoverageCloud.tsxdeleted file mode 100644index 6385476d26e..00000000000--- a/src/features/SelfLearning/CoverageCloud.tsx+++ /dev/null@@ -1,133 +0,0 @@-'use client';--import { Block, Flexbox, Text, Tooltip } from '@lobehub/ui';-import { createStaticStyles, cssVar, useTheme } from 'antd-style';-import { memo, useMemo } from 'react';-import { useTranslation } from 'react-i18next';--import type { ExpertiseDomainDetail } from '@/services/expertise';--const styles = createStaticStyles(({ css }) => ({- empty: css`- padding-block: 3px;- padding-inline: 8px;- border: 1px dashed ${cssVar.colorBorder};- border-radius: 999px;- `,- legendDot: css`- width: 7px;- height: 7px;- border-radius: 999px;- `,- pie: css`- flex: none;- width: 104px;- height: 104px;- border-radius: 50%;- `,-}));--interface CoverageSnapshotProps {- detail: ExpertiseDomainDetail;-}--/** A composition chart answers “where is the learning concentrated?”; empty layers stay explicit gaps. */-const CoverageSnapshot = memo<CoverageSnapshotProps>(({ detail }) => {- const { t } = useTranslation('selfLearning');- const theme = useTheme();- const { domain, layerCounts, lessonStats } = detail;-- const { covered, empty, total } = useMemo(() => {- const layers = (domain.layers ?? []).map((layer) => ({- count: layerCounts[layer.key] ?? 0,- key: layer.key,- title: layer.title,- }));- return {- covered: layers.filter((layer) => layer.count > 0),- empty: layers.filter((layer) => layer.count === 0),- total: layers.reduce((sum, layer) => sum + layer.count, 0),- };- }, [domain.layers, layerCounts]);-- if (covered.length === 0 && empty.length === 0) return null;-- const colors = [theme.blue6, theme.cyan6, theme.green6, theme.gold6, theme.magenta6];- let cursor = 0;- const pie = covered- .map((layer, index) => {- const start = cursor;- cursor += (layer.count / total) * 100;- return `${colors[index % colors.length]} ${start}% ${cursor}%`;- })- .join(', ');-- return (- <Block gap={12} padding={16} variant={'outlined'}>- <Flexbox horizontal align={'baseline'} justify={'space-between'} wrap={'wrap'}>- <Text fontSize={13} weight={600}>- {t('coverage.title')}- </Text>- <Text fontSize={11} type={'secondary'}>- {t('coverage.sub', {- covered: covered.length,- total: covered.length + empty.length,- unused: lessonStats.unused,- })}- </Text>- </Flexbox>-- {total > 0 && (- <Flexbox horizontal align={'center'} gap={24}>- <Tooltip title={t('coverage.total', { count: total })}>- <div className={styles.pie} style={{ background: `conic-gradient(${pie})` }} />- </Tooltip>- <Flexbox gap={8}>- {covered.map((layer) => (- <Flexbox horizontal align={'center'} gap={6} key={layer.key}>- <div- className={styles.legendDot}- style={{ background: colors[covered.indexOf(layer) % colors.length] }}- />- <Text fontSize={11.5}>{layer.title}</Text>- <Text fontSize={11} type={'secondary'}>- {layer.count} · {Math.round((layer.count / total) * 100)}%- </Text>- </Flexbox>- ))}- </Flexbox>- </Flexbox>- )}-- {empty.length > 0 && (- <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>- <Text fontSize={11} type={'secondary'}>- {t('coverage.gaps')}- </Text>- {empty.map((layer) => (- <div className={styles.empty} key={layer.key}>- <Text fontSize={11.5} type={'secondary'}>- {layer.title}- </Text>- </div>- ))}- </Flexbox>- )}-- <Text fontSize={10.5} type={'secondary'}>- {domain.layerSource === 'canonical'- ? t('coverage.canon', {- source:- [- ...new Set((domain.layers ?? []).map((layer) => layer.canonRef).filter(Boolean)),- ].join(' · ') || '—',- })- : t('coverage.invented')}- </Text>- </Block>- );-});--CoverageSnapshot.displayName = 'CoverageSnapshot';--export default CoverageSnapshot;diff --git a/src/features/SelfLearning/CreateDomainModal.tsx b/src/features/SelfLearning/CreateDomainModal.tsxindex 3ad3a22974c..9d26f0ccac7 100644--- a/src/features/SelfLearning/CreateDomainModal.tsx+++ b/src/features/SelfLearning/CreateDomainModal.tsx@@ -1,48 +1,202 @@'use client';-import { Flexbox, Text, TextArea } from '@lobehub/ui';+import { ActionIcon, Flexbox, Icon, Input, Text, TextArea } from '@lobehub/ui';import { Button, createModal, toast, useModalContext } from '@lobehub/ui/base-ui';-import { createStaticStyles, cssVar, keyframes } from 'antd-style';-import { t as translate } from 'i18next';-import { SparklesIcon } from 'lucide-react';-import { memo, useEffect, useState } from 'react';+import { createGlobalStyle, createStaticStyles, cssVar } from 'antd-style';+import {+ AnchorIcon,+ ArrowLeftIcon,+ LayersIcon,+ PlusIcon,+ RefreshCwIcon,+ Trash2Icon,+ XIcon,+} from 'lucide-react';+import { type KeyboardEvent, memo, useCallback, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import AssigneeAvatar from '@/features/AgentTasks/features/AssigneeAvatar';+import { useAgentDisplayMeta } from '@/features/AgentTasks/shared/useAgentDisplayMeta';+import type { ExpertiseDomainDraft } from '@/services/expertise';import { expertiseService } from '@/services/expertise';interface CreateDomainContentProps {agentId: string;- onCreated: () => void;+ onCreated: (domainId: string) => void;}-const shimmer = keyframes`- to { background-position: 200% 0; }-`;-const styles = createStaticStyles(({ css }) => ({- content: css`- margin-block-start: -10px;+ body: css`+ overflow-y: auto;++ min-height: 0;+ max-height: min(70vh, 680px);+ padding-block: 8px 24px;+ padding-inline: 16px;+ `,+ close: css`+ position: absolute;+ inset-block-start: 14px;+ inset-inline-end: 14px;+ `,+ footer: css`+ padding-block: 8px;+ padding-inline: 16px;+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};+ `,+ head: css`+ position: relative;+ padding-block: 16px 8px;+ padding-inline: 16px;+ `,+ inputShell: css`+ position: relative;+ overflow: hidden;+ border-radius: 8px;+ background: ${cssVar.colorBgElevated};++ textarea {+ min-height: 206px !important;+ padding: 16px;+ border: none;++ font-size: 14px;++ background: transparent;+ box-shadow: none;+ }`,- generating: css`- border-color: transparent;- background:- linear-gradient(${cssVar.colorBgElevated}, ${cssVar.colorBgElevated}) padding-box,- linear-gradient(90deg, ${cssVar.colorPrimary}, ${cssVar.colorInfo}, ${cssVar.colorPrimary})- border-box;- background-size:- 100% 100%,- 200% 100%;- animation: ${shimmer} 1.5s linear infinite;+ inputShellLoading: css`+ &::after {+ pointer-events: none;+ content: '';++ position: absolute;+ z-index: 1;+ inset: 0;++ padding: 2px;+ border-radius: inherit;++ background: conic-gradient(+ from var(--domain-border-angle),+ ${cssVar.colorBorderSecondary} 0deg 210deg,+ #ff3d8d 238deg,+ #8b5cf6 258deg,+ #00c8ff 278deg,+ #22e6a8 298deg,+ #ffd43b 318deg,+ #ff6b35 338deg,+ ${cssVar.colorBorderSecondary} 360deg+ );++ mask:+ linear-gradient(#fff 0 0) content-box,+ linear-gradient(#fff 0 0);++ animation: domain-input-flow 1.8s linear infinite;++ mask-composite: exclude;+ }++ @keyframes domain-input-flow {+ from {+ --domain-border-angle: 0deg;+ }++ to {+ --domain-border-angle: 360deg;+ }+ }++ @media (prefers-reduced-motion: reduce) {+ &::after {+ animation: none;+ }+ }+ `,+ itemRow: css`+ display: grid;+ grid-template-columns: 32px minmax(0, 1fr) 28px;+ gap: 8px;+ align-items: start;++ padding-block: 8px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};++ &:last-child {+ border-block-end: none;+ }+ `,+ reviewSection: css`+ padding-block: 14px;++ &:first-child {+ padding-block: 0 4px;+ }+ `,+ seq: css`+ padding-block-start: 8px;+ font-size: 14px;+ color: ${cssVar.colorTextTertiary};+ `,+ 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};`,}));-/** Creates an expertise domain from one natural-language brief interpreted by the backend. */+const DomainBorderFlowStyle = createGlobalStyle`+ @property --domain-border-angle {+ inherits: false;+ initial-value: 0deg;+ syntax: '<angle>';+ }+`;++const slugify = (s: string, fallback: string) =>+ s+ .trim()+ .toLowerCase()+ .replaceAll(/[^\da-z]+/g, '-')+ .replaceAll(/^-|-$/g, '') || fallback;++/**+ * 两步建域,交互对齐 createGoal:① 一段话说清方向 → ② 检查它读出来的锚。+ *+ * 锚不只是名字和过滤器:分层决定经验挂在哪一层、经典依据决定「覆盖」意味着什么。+ * 这两样在落库前必须让人看见并能改 —— 所以 step 2 把整个锚候选摊开。+ */const CreateDomainContent = memo<CreateDomainContentProps>(({ agentId, onCreated }) => {const { t } = useTranslation('selfLearning');const { close } = useModalContext();const storageKey = `self-learning:create:${agentId}`;const [brief, setBrief] = useState(() => localStorage.getItem(storageKey) ?? '');- const [loading, setLoading] = useState(false);+ const [step, setStep] = useState<'describe' | 'preparing' | 'review'>('describe');+ const [draft, setDraft] = useState<ExpertiseDomainDraft>();+ const [creating, setCreating] = useState(false);+ const meta = useAgentDisplayMeta(agentId);useEffect(() => {if (brief.trim()) localStorage.setItem(storageKey, brief);@@ -58,49 +212,346 @@ const CreateDomainContent = memo<CreateDomainContentProps>(({ agentId, onCreatedreturn () => window.removeEventListener('beforeunload', preventLoss);}, [brief]);- const submit = async () => {+ const generate = useCallback(async () => {if (!brief.trim()) return;- setLoading(true);+ setStep('preparing');+ try {+ setDraft(await expertiseService.draftDomain({ agentId, brief: brief.trim() }));+ setStep('review');+ } catch {+ toast.error(t('create.failed'));+ setStep(draft ? 'review' : 'describe');+ }+ }, [agentId, brief, draft, t]);++ const canCreate = !!draft && !!draft.title.trim() && !!draft.domainFilter.trim() && !creating;++ const create = useCallback(async () => {+ if (!draft || !canCreate) return;+ setCreating(true);try {- await expertiseService.createDomain({ agentId, brief: brief.trim() });+ const id = await expertiseService.createDomain({+ ...draft,+ agentId,+ brief: brief.trim(),+ canonEntries: draft.canonEntries.filter((c) => c.title.trim()),+ domainFilter: draft.domainFilter.trim(),+ layers: draft.layers.filter((l) => l.title.trim()),+ outOfScope: draft.outOfScope?.trim() || null,+ title: draft.title.trim(),+ });localStorage.removeItem(storageKey);- onCreated();+ onCreated(id);close();} catch {toast.error(t('create.failed'));} finally {- setLoading(false);+ setCreating(false);+ }+ }, [agentId, brief, canCreate, close, draft, onCreated, storageKey, t]);++ const primaryRef = useRef<() => void>(undefined);+ primaryRef.current = step === 'describe' ? generate : step === 'review' ? create : undefined;+ const onKeyDown = useCallback((e: KeyboardEvent<HTMLDivElement>) => {+ if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {+ e.preventDefault();+ e.stopPropagation();+ void primaryRef.current?.();}- };+ }, []);++ const patch = (p: Partial<ExpertiseDomainDraft>) => setDraft((d) => (d ? { ...d, ...p } : d));return (- <Flexbox className={styles.content} gap={8} padding={'0 20px 16px'}>- <Text fontSize={12.5} lineHeight={1.7} type={'secondary'}>- {loading ? t('create.generating') : t('create.briefHelp')}- </Text>- <TextArea- autoFocus- className={loading ? styles.generating : undefined}- disabled={loading}- placeholder={t('create.briefPlaceholder')}- rows={5}- value={brief}- onChange={(e) => setBrief(e.target.value)}- />- <Flexbox horizontal align={'center'} gap={8} justify={'flex-end'}>- <Button disabled={loading} onClick={close}>- {t('create.cancel')}- </Button>- <Button- disabled={!brief.trim() || loading}- icon={SparklesIcon}- loading={loading}- shape={'round'}- type={'primary'}- onClick={submit}- >- {loading ? t('create.generating') : t('create.submit')}- </Button>+ <Flexbox onKeyDown={onKeyDown}>+ <DomainBorderFlowStyle />+ <Flexbox horizontal className={styles.head}>+ <Flexbox flex={1} gap={6}>+ {step === 'review' && (+ <Flexbox horizontal align={'center'} gap={8}>+ <ActionIcon+ icon={ArrowLeftIcon}+ size={'small'}+ title={t('create.back')}+ onClick={() => setStep('describe')}+ />+ <Text fontSize={12} type={'secondary'}>+ {t('create.reviewStep')}+ </Text>+ </Flexbox>+ )}+ {step === 'review' && draft ? (+ <input+ className={styles.title}+ maxLength={80}+ placeholder={t('create.field.title')}+ value={draft.title}+ onChange={(e) => patch({ title: e.target.value })}+ />+ ) : (+ <div className={styles.titleStatic}>{t('create.modalTitle')}</div>+ )}+ {step !== 'review' && (+ <>+ <div+ className={`${styles.inputShell} ${step === 'preparing' ? styles.inputShellLoading : ''}`}+ >+ <TextArea+ autoFocus+ disabled={step === 'preparing'}+ placeholder={t('create.briefPlaceholder')}+ value={brief}+ variant={'borderless'}+ onChange={(e) => setBrief(e.target.value)}+ />+ </div>+ <Text type={'secondary'}>+ {step === 'preparing' ? t('create.generating') : t('create.briefHelp')}+ </Text>+ </>+ )}+ </Flexbox>+ <ActionIcon className={styles.close} icon={XIcon} onClick={close} />+ </Flexbox>++ {step === 'review' && draft && (+ <Flexbox className={styles.body}>+ <Flexbox className={styles.reviewSection} gap={6}>+ <Text fontSize={12} type={'secondary'}>+ {t('create.reviewHelp')}+ </Text>+ {draft.rationale && (+ <Text fontSize={13} type={'secondary'}>+ {draft.rationale}+ </Text>+ )}+ </Flexbox>++ <Flexbox className={styles.reviewSection} gap={10}>+ <Text fontSize={13} weight={600}>+ {t('create.field.domainFilter')}+ </Text>+ <TextArea+ autoSize={{ maxRows: 6, minRows: 2 }}+ value={draft.domainFilter}+ variant={'filled'}+ onChange={(e) => patch({ domainFilter: e.target.value })}+ />+ <Text fontSize={13} weight={600}>+ {t('create.field.outOfScope')}+ </Text>+ <TextArea+ autoSize={{ maxRows: 5, minRows: 2 }}+ placeholder={t('create.field.outOfScopePlaceholder')}+ value={draft.outOfScope ?? ''}+ variant={'filled'}+ onChange={(e) => patch({ outOfScope: e.target.value })}+ />+ </Flexbox>++ <Flexbox className={styles.reviewSection} gap={10}>+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>+ <Flexbox horizontal align={'center'} gap={8}>+ <Icon color={cssVar.colorTextTertiary} icon={AnchorIcon} size={16} />+ <Text fontSize={13} weight={600}>+ {t('create.anchor.canon')}+ </Text>+ <Text fontSize={12} type={'secondary'}>+ {t('create.anchor.canonHint')}+ </Text>+ </Flexbox>+ <Button+ icon={PlusIcon}+ size={'small'}+ type={'text'}+ onClick={() =>+ patch({+ canonEntries: [+ ...draft.canonEntries,+ {+ key: `canon-${draft.canonEntries.length + 1}`,+ source: '',+ statement: '',+ title: '',+ },+ ],+ })+ }+ >+ {t('create.anchor.addCanon')}+ </Button>+ </Flexbox>+ {draft.canonEntries.length === 0 && (+ <Text fontSize={12} type={'secondary'}>+ {t('create.anchor.noCanon')}+ </Text>+ )}+ {draft.canonEntries.map((entry, i) => (+ <div className={styles.itemRow} key={i}>+ <span className={styles.seq}>C{i + 1}</span>+ <Flexbox gap={4}>+ <Flexbox horizontal gap={8}>+ <Input+ placeholder={t('create.anchor.canonTitle')}+ style={{ flex: 1 }}+ value={entry.title}+ variant={'filled'}+ onChange={(e) =>+ patch({+ canonEntries: draft.canonEntries.map((c, j) =>+ j === i+ ? { ...c, key: slugify(e.target.value, c.key), title: e.target.value }+ : c,+ ),+ })+ }+ />+ <Input+ placeholder={t('create.anchor.canonSource')}+ style={{ flex: 1 }}+ value={entry.source}+ variant={'filled'}+ onChange={(e) =>+ patch({+ canonEntries: draft.canonEntries.map((c, j) =>+ j === i ? { ...c, source: e.target.value } : c,+ ),+ })+ }+ />+ </Flexbox>+ <TextArea+ autoSize={{ maxRows: 4, minRows: 1 }}+ placeholder={t('create.anchor.canonStatement')}+ value={entry.statement}+ variant={'borderless'}+ onChange={(e) =>+ patch({+ canonEntries: draft.canonEntries.map((c, j) =>+ j === i ? { ...c, statement: e.target.value } : c,+ ),+ })+ }+ />+ </Flexbox>+ <ActionIcon+ icon={Trash2Icon}+ size={'small'}+ onClick={() =>+ patch({ canonEntries: draft.canonEntries.filter((_, j) => j !== i) })+ }+ />+ </div>+ ))}+ </Flexbox>+ <Flexbox className={styles.reviewSection} gap={10}>+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>+ <Flexbox horizontal align={'center'} gap={8}>+ <Icon color={cssVar.colorTextTertiary} icon={LayersIcon} size={16} />+ <Text fontSize={13} weight={600}>+ {t('create.anchor.layers')}+ </Text>+ <Text fontSize={12} type={'secondary'}>+ {draft.layerSource === 'canonical' && draft.layerCanonRef+ ? t('create.anchor.layersFrom', { ref: draft.layerCanonRef })+ : t('create.anchor.layersInvented')}+ </Text>+ </Flexbox>+ <Button+ icon={PlusIcon}+ size={'small'}+ type={'text'}+ onClick={() =>+ patch({+ layers: [+ ...draft.layers,+ { description: null, key: `layer-${draft.layers.length + 1}`, title: '' },+ ],+ })+ }+ >+ {t('create.anchor.addLayer')}+ </Button>+ </Flexbox>+ {draft.layers.length === 0 && (+ <Text fontSize={12} type={'secondary'}>+ {t('create.anchor.noLayers')}+ </Text>+ )}+ {draft.layers.map((layer, i) => (+ <div className={styles.itemRow} key={i}>+ <span className={styles.seq}>L{i + 1}</span>+ <Flexbox gap={4}>+ <Input+ placeholder={t('create.anchor.layerTitle')}+ value={layer.title}+ variant={'filled'}+ onChange={(e) =>+ patch({+ layers: draft.layers.map((l, j) =>+ j === i+ ? { ...l, key: slugify(e.target.value, l.key), title: e.target.value }+ : l,+ ),+ })+ }+ />+ <Input+ placeholder={t('create.anchor.layerDesc')}+ value={layer.description ?? ''}+ variant={'borderless'}+ onChange={(e) =>+ patch({+ layers: draft.layers.map((l, j) =>+ j === i ? { ...l, description: e.target.value } : l,+ ),+ })+ }+ />+ </Flexbox>+ <ActionIcon+ icon={Trash2Icon}+ size={'small'}+ onClick={() => patch({ layers: draft.layers.filter((_, j) => j !== i) })}+ />+ </div>+ ))}+ </Flexbox>+ </Flexbox>+ )}++ <Flexbox horizontal align={'center'} className={styles.footer} justify={'space-between'}>+ <Flexbox horizontal align={'center'} gap={6}>+ <AssigneeAvatar agentId={agentId} size={18} />+ <Text fontSize={12}>{meta?.title}</Text>+ </Flexbox>+ <Flexbox horizontal align={'center'} gap={4}>+ {step === 'review' && (+ <Button+ icon={RefreshCwIcon}+ size={'small'}+ style={{ color: cssVar.colorTextTertiary }}+ type={'text'}+ onClick={() => void generate()}+ >+ {t('create.regenerate')}+ </Button>+ )}+ <Button+ disabled={step === 'preparing' || (step === 'describe' ? !brief.trim() : !canCreate)}+ loading={step === 'preparing' || creating}+ shape={'round'}+ size={'small'}+ type={'primary'}+ onClick={() => void primaryRef.current?.()}+ >+ {step === 'preparing'+ ? t('create.generating')+ : step === 'describe'+ ? t('create.next')+ : t('create.confirm')}+ </Button>+ </Flexbox></Flexbox></Flexbox>);@@ -113,6 +564,7 @@ export const openCreateDomainModal = (props: CreateDomainContentProps) =>content: <CreateDomainContent {...props} />,footer: null,maskClosable: false,- title: translate('create.modalTitle', { ns: 'selfLearning' }),- width: 'min(88vw, 560px)',+ styles: { content: { overflow: 'hidden', padding: 0 } },+ title: null,+ width: 'min(88vw, 720px)',});diff --git a/src/features/SelfLearning/Curves.tsx b/src/features/SelfLearning/Curves.tsxdeleted file mode 100644index 9e5d29ab7db..00000000000--- a/src/features/SelfLearning/Curves.tsx+++ /dev/null@@ -1,159 +0,0 @@-'use client';--import { useTheme } from 'antd-style';-import { memo, useMemo } from 'react';-import { useTranslation } from 'react-i18next';--import type { ExpertiseDomainItem } from '@/services/expertise';--const W = 860;-const H = 210;-const PL = 34;-const PB = 22;-/** 右侧留给线尾标签的空间 —— 标签压在图上就没人看得清哪条是哪条。 */-const PR = 60;--interface CurvesProps {- colors: Record<string, string>;- domains: ExpertiseDomainItem[];- /** 上色并带标签的那几条;其余淡成背景。 */- focusIds: string[];- hoverId?: string;- onHover: (id?: string) => void;- onOpen: (id: string) => void;-}--/**- * 所有专长的累计曲线叠在一张图上。- *- * **纵轴是成熟度比例,不是条数** —— 学到 3 条的领域和学到 34 条的领域在条数坐标里- * 差一个量级,叠在一起只能看见一条线。归一化之后,形状本身就是结论:压平了 = 学完了,- * 还在陡 = 在长,掉头 = 能力在退,贴着底 = 练了没学到。- *- * 拟合不可信的专长没有 pInf,用它自己的最大值归一 —— 形状仍然成立,只是纵轴读数- * 不该被当成成熟度,所以那几条不进 focus、不带标签。- */-const Curves = memo<CurvesProps>(({ domains, focusIds, colors, hoverId, onHover, onOpen }) => {- const { t } = useTranslation('selfLearning');- const theme = useTheme();-- const { maxRun, paths } = useMemo(() => {- const runs = Math.max(1, ...domains.map((d) => d.runCount));- const items = domains- .filter((d) => d.series.length > 1)- .map((d) => {- const ceiling = d.maturity.usable- ? (d.maturity.pInf ?? 0)- : Math.max(...d.series.map((p) => p.n));- const scale = ceiling > 0 ? ceiling : 1;- const pts = d.series.map((p) => ({- x: PL + (p.run / runs) * (W - PL - PR),- y: H - PB - (p.n / scale) * (H - PB - 14),- }));- return {- d: pts- .map((p, i) => `${i === 0 ? 'M' : 'L'}${p.x.toFixed(1)},${p.y.toFixed(1)}`)- .join(' '),- end: pts.at(-1)!,- id: d.id,- title: d.title,- };- });- return { maxRun: runs, paths: items };- }, [domains]);-- const focus = paths.filter((p) => focusIds.includes(p.id));- const rest = paths.filter((p) => !focusIds.includes(p.id));-- return (- <svg height={H} style={{ display: 'block', width: '100%' }} viewBox={`0 0 ${W} ${H}`}>- {[0, 25, 50, 75, 100].map((v) => {- const y = H - PB - (v / 100) * (H - PB - 14);- return (- <g key={v}>- <line- pointerEvents={'none'}- stroke={theme.colorBorderSecondary}- strokeDasharray={v === 0 || v === 100 ? '' : '3 4'}- x1={PL}- x2={W - PR + 4}- y1={y}- y2={y}- />- <text- fill={theme.colorTextQuaternary}- fontSize={10}- pointerEvents={'none'}- x={0}- y={y + 3}- >- {v}%- </text>- </g>- );- })}- {[0, 0.25, 0.5, 0.75, 1].map((r) => {- const run = Math.round(maxRun * r);- return (- <text- fill={theme.colorTextQuaternary}- fontSize={10}- key={r}- pointerEvents={'none'}- textAnchor={'middle'}- x={PL + r * (W - PL - PR)}- y={H - 6}- >- {run <= 1 ? t('detail.chart.firstRun') : t('detail.chart.nthRun', { n: run })}- </text>- );- })}-- {rest.map((p) => (- <path- d={p.d}- fill={'none'}- key={p.id}- opacity={hoverId && hoverId !== p.id ? 0.12 : 0.28}- stroke={theme.colorTextQuaternary}- strokeWidth={hoverId === p.id ? 2.5 : 1.5}- style={{ cursor: 'pointer' }}- onClick={() => onOpen(p.id)}- onMouseEnter={() => onHover(p.id)}- onMouseLeave={() => onHover(undefined)}- />- ))}- {focus.map((p) => (- <g key={p.id}>- <path- d={p.d}- fill={'none'}- opacity={hoverId && hoverId !== p.id ? 0.25 : 1}- stroke={colors[p.id]}- strokeLinecap={'round'}- strokeWidth={hoverId === p.id ? 3.2 : 2.2}- style={{ cursor: 'pointer' }}- onClick={() => onOpen(p.id)}- onMouseEnter={() => onHover(p.id)}- onMouseLeave={() => onHover(undefined)}- />- <circle cx={p.end.x} cy={p.end.y} fill={colors[p.id]} pointerEvents={'none'} r={3.4} />- <text- fill={hoverId && hoverId !== p.id ? theme.colorTextQuaternary : theme.colorText}- fontSize={11}- fontWeight={600}- pointerEvents={'none'}- x={p.end.x + 7}- y={p.end.y + 4}- >- {p.title}- </text>- </g>- ))}- </svg>- );-});--Curves.displayName = 'Curves';--export default Curves;diff --git a/src/features/SelfLearning/Detail/FitCurve.tsx b/src/features/SelfLearning/Detail/FitCurve.tsxdeleted file mode 100644index 286caf47a77..00000000000--- a/src/features/SelfLearning/Detail/FitCurve.tsx+++ /dev/null@@ -1,217 +0,0 @@-'use client';--import { useTheme } from 'antd-style';-import { memo, useMemo } from 'react';-import { useTranslation } from 'react-i18next';--import type { ExpertiseDomainDetail, ExpertiseMaturity } from '@/services/expertise';--import { projectSeries, runsToRatio } from '../hooks';-import { getLearnedGains } from './curveHelpers';--const W = 900;-const H = 320;-const PL = 44;-const PB = 34;-const PT = 14;-/** 右侧留给「N 条」那一列刻度。 */-const PR = 84;--interface FitCurveProps {- maturity: ExpertiseMaturity;- runCount: number;- series: ExpertiseDomainDetail['series'];-}--/**- * 累计学到的经验,纵轴同时标成熟度百分比与条数。- *- * 外推只在拟合可信时画,且**永远是虚线** —— 实线段是观测,虚线段是模型,两者在- * 视觉上必须能一眼分开。撞了 τ 上界的拟合一条虚线都不画:那条线会画出一个- * 「永远学不完」的斜坡,那是搜索边界的伪影,不是这个 agent 的事实。- */-const FitCurve = memo<FitCurveProps>(({ series, maturity, runCount }) => {- const { t } = useTranslation('selfLearning');- const theme = useTheme();-- const geom = useMemo(() => {- const usable = maturity.usable && !!maturity.pInf && !!maturity.tau;- const pInf = usable ? maturity.pInf! : Math.max(1, ...series.map((s) => s.activeCount));- const tau = usable ? maturity.tau! : 0;- const n90 = usable ? runsToRatio(tau, 0.9) : runCount;- const xMax = usable ? Math.max(runCount, Math.round(n90 * 1.12)) : Math.max(1, runCount);-- const x = (i: number) => PL + ((i - 1) / Math.max(1, xMax - 1)) * (W - PL - PR);- const y = (n: number) => H - PB - (n / pInf) * (H - PB - PT);-- const actual = series- .map(- (s, k) =>- `${k === 0 ? 'M' : 'L'}${x(s.runIndex).toFixed(1)},${y(s.activeCount).toFixed(1)}`,- )- .join(' ');-- const last = series.at(-1);- const future =- usable && last- ? projectSeries(pInf, tau, last.runIndex, last.activeCount, xMax)- .map((p, k) => `${k === 0 ? 'M' : 'L'}${x(p.run).toFixed(1)},${y(p.n).toFixed(1)}`)- .join(' ')- : '';-- const learnedGains = getLearnedGains(series);- const bars = series.map((s, k) => ({- gain: learnedGains[k],- human: s.hadHumanInLoop,- run: s.runIndex,- }));- const maxGain = Math.max(1, ...bars.map((b) => b.gain));-- return { actual, bars, future, last, maxGain, n90, pInf, usable, x, xMax, y };- }, [series, maturity, runCount]);-- const { x, y, pInf, xMax, usable, n90, last } = geom;- const ticks = [1, Math.round(xMax * 0.33), Math.round(xMax * 0.66), xMax].filter(- (v, i, a) => a.indexOf(v) === i,- );-- return (- <svg height={H} style={{ display: 'block', width: '100%' }} viewBox={`0 0 ${W} ${H}`}>- {[0, 25, 50, 75, 90, 100].map((p) => {- const yy = H - PB - (p / 100) * (H - PB - PT);- return (- <g key={p}>- <line- strokeDasharray={p === 0 || p === 100 ? '' : '3 4'}- x1={PL}- x2={W - PR + 6}- y1={yy}- y2={yy}- stroke={- p === 90- ? theme.colorSuccessBorder- : p === 0 || p === 100- ? theme.colorTextQuaternary- : theme.colorBorderSecondary- }- />- <text fill={theme.colorTextQuaternary} fontSize={10} x={4} y={yy + 3}>- {p}%- </text>- <text fill={theme.colorTextQuaternary} fontSize={10} x={W - PR + 12} y={yy + 3}>- {t('detail.chart.count', { count: Math.round((p / 100) * pInf) })}- </text>- </g>- );- })}- {ticks.map((i) => (- <text- fill={theme.colorTextQuaternary}- fontSize={10}- key={i}- textAnchor={'middle'}- x={x(i)}- y={H - 16}- >- {i <= 1 ? t('detail.chart.firstRun') : t('detail.chart.nthRun', { n: i })}- </text>- ))}-- {geom.bars.map((b) =>- b.gain <= 0 ? null : (- <rect- fill={b.human ? theme.colorInfoBorder : theme.colorFillSecondary}- height={(b.gain / geom.maxGain) * 46}- key={b.run}- rx={1.5}- width={Math.max(3, (W - PL - PR) / xMax - 1)}- x={x(b.run) - 2}- y={H - PB - (b.gain / geom.maxGain) * 46}- />- ),- )}-- {usable && geom.future && (- <path- d={geom.future}- fill={'none'}- opacity={maturity.usable && maturity.speculative ? 0.35 : 0.6}- stroke={theme.colorSuccess}- strokeDasharray={'7 5'}- strokeWidth={2.2}- />- )}-- <path- d={geom.actual}- fill={'none'}- stroke={theme.colorSuccess}- strokeLinecap={'round'}- strokeWidth={2.8}- />- {last && (- <circle cx={x(last.runIndex)} cy={y(last.activeCount)} fill={theme.colorSuccess} r={4.5} />- )}-- {last && (- <>- <line- stroke={theme.colorBorder}- strokeDasharray={'2 3'}- x1={x(last.runIndex)}- x2={x(last.runIndex)}- y1={PT}- y2={H - PB}- />- <text- fill={theme.colorText}- fontSize={10.5}- fontWeight={600}- textAnchor={'middle'}- x={x(last.runIndex)}- y={PT - 2}- >- {t('detail.chart.today', { count: runCount })}- </text>- </>- )}-- {usable && n90 > (last?.runIndex ?? 0) && (- <g>- <circle- cx={x(n90)}- cy={y(pInf * 0.9)}- fill={'none'}- r={5}- stroke={theme.colorSuccess}- strokeDasharray={'2 2'}- strokeWidth={1.6}- />- <text- fill={theme.colorText}- fontSize={10.5}- fontWeight={600}- textAnchor={'end'}- x={x(n90) - 11}- y={y(pInf * 0.9) - 16}- >- {t('detail.chart.reach90', { run: n90 })}- </text>- <text- fill={theme.colorTextTertiary}- fontSize={10}- textAnchor={'end'}- x={x(n90) - 11}- y={y(pInf * 0.9) - 4}- >- {t('detail.chart.remaining', { count: n90 - (last?.runIndex ?? 0) })}- </text>- </g>- )}- </svg>- );-});--FitCurve.displayName = 'FitCurve';--export default FitCurve;diff --git a/src/features/SelfLearning/Detail/curveHelpers.test.ts b/src/features/SelfLearning/Detail/curveHelpers.test.tsdeleted file mode 100644index bf29868d8d3..00000000000--- a/src/features/SelfLearning/Detail/curveHelpers.test.ts+++ /dev/null@@ -1,16 +0,0 @@-import { describe, expect, it } from 'vitest';--import { getLearnedGains } from './curveHelpers';--describe('getLearnedGains', () => {- it('uses cumulative learned totals when active lessons decrease after retirement', () => {- const gains = getLearnedGains([- { learnedTotal: 2 },- { learnedTotal: 4 },- { learnedTotal: 4 },- { learnedTotal: 5 },- ]);-- expect(gains).toEqual([2, 2, 0, 1]);- });-});diff --git a/src/features/SelfLearning/Detail/curveHelpers.ts b/src/features/SelfLearning/Detail/curveHelpers.tsdeleted file mode 100644index b67e3623001..00000000000--- a/src/features/SelfLearning/Detail/curveHelpers.ts+++ /dev/null@@ -1,9 +0,0 @@-interface LearnedSnapshot {- learnedTotal: number;-}--/** Returns newly learned lessons per run without treating retirements as negative learning. */-export const getLearnedGains = (series: LearnedSnapshot[]) =>- series.map((snapshot, index) =>- Math.max(0, snapshot.learnedTotal - (series[index - 1]?.learnedTotal ?? 0)),- );diff --git a/src/features/SelfLearning/Detail/index.tsx b/src/features/SelfLearning/Detail/index.tsxdeleted file mode 100644index f3573f57d08..00000000000--- a/src/features/SelfLearning/Detail/index.tsx+++ /dev/null@@ -1,404 +0,0 @@-'use client';--import { Block, Flexbox, Text } from '@lobehub/ui';-import { createStaticStyles, useTheme } from 'antd-style';-import { memo, useEffect } from 'react';-import { useTranslation } from 'react-i18next';-import { Link, useNavigate, useParams } from 'react-router';-import urlJoin from 'url-join';--import AsyncBoundary from '@/components/AsyncBoundary';-import Loading from '@/components/Loading/BrandTextLoading';-import AgentBreadcrumb from '@/features/AgentBreadcrumb';-import NavHeader from '@/features/NavHeader';-import WideScreenContainer from '@/features/WideScreenContainer';-import { useAgentStore } from '@/store/agent';--import CoverageCloud from '../CoverageCloud';-import { runsToRatio, useExpertiseDomain, useExpertiseLessons } from '../hooks';-import RuleList from '../RuleList';-import FitCurve from './FitCurve';--const styles = createStaticStyles(({ css }) => ({- body: css`- overflow-y: auto;- display: flex;- `,- sentence: css`- font-size: 26px;- font-weight: 700;- line-height: 1.5;- `,- learningGrid: css`- display: grid;- grid-template-columns: minmax(280px, 0.72fr) minmax(420px, 1.28fr);- gap: 16px;- align-items: start;-- @media (width <= 960px) {- grid-template-columns: 1fr;- }- `,-}));--/** plateauKind 是 DB 的开放字符串,映射成受控的 i18n key 再翻译。 */-const PLATEAU_KEY: Record<- string,- 'plateau.growing' | 'plateau.noisy' | 'plateau.saturated' | 'plateau.stalled'-> = {- growing: 'plateau.growing',- noisy: 'plateau.noisy',- saturated: 'plateau.saturated',- stalled: 'plateau.stalled',-};--/** 副标题末尾那半句:把曲线形态说成人话,而不是把 plateauKind 直接印出来。 */-const SHAPE_CLAUSE: Record<- string,- | 'detail.shapeClause.growing'- | 'detail.shapeClause.noisy'- | 'detail.shapeClause.saturated'- | 'detail.shapeClause.stalled'-> = {- growing: 'detail.shapeClause.growing',- noisy: 'detail.shapeClause.noisy',- saturated: 'detail.shapeClause.saturated',- stalled: 'detail.shapeClause.stalled',-};--const DomainDetail = memo(() => {- const { t } = useTranslation('selfLearning');- const theme = useTheme();- const navigate = useNavigate();- const params = useParams();- const activeAgentId = useAgentStore((s) => s.activeAgentId);- const domainId = params.domainId;-- const { data, error, isLoading, mutate } = useExpertiseDomain(domainId);- const {- data: lessons,- error: lessonsError,- isLoading: lessonsLoading,- mutate: mutateLessons,- } = useExpertiseLessons(domainId);-- const maturity = data?.maturity;- const selfLearningPath = activeAgentId- ? urlJoin('/agent', activeAgentId, 'self-learning')- : undefined;- const rulesPath =- selfLearningPath && domainId ? urlJoin(selfLearningPath, domainId, 'rules') : '';-- useEffect(() => {- if (!isLoading && !error && !data && selfLearningPath) {- navigate(selfLearningPath, { replace: true });- }- }, [data, error, isLoading, navigate, selfLearningPath]);-- return (- <Flexbox height={'100%'} width={'100%'}>- <NavHeader- styles={{ left: { paddingInlineStart: 24 } }}- left={- activeAgentId ? (- <AgentBreadcrumb- agentId={activeAgentId}- extraItems={data?.domain.title ? [data.domain.title] : undefined}- title={- <Link to={selfLearningPath ?? '#'}>- <Text as={'span'} color={'inherit'} weight={500}>- {t('title')}- </Text>- </Link>- }- />- ) : null- }- />- <Flexbox className={styles.body} flex={1} width={'100%'}>- <WideScreenContainer>- <AsyncBoundary- data={data}- error={error}- errorVariant={'page'}- isLoading={isLoading}- loading={<Loading debugId="SelfLearningDomain" />}- onRetry={() => mutate()}- >- {data && (- <Flexbox gap={24} paddingBlock={'26px 64px'}>- {data.runCount === 0 ? (- /* 刚定完方向、一次还没练过:画不出曲线,坐标轴会退化成一排「1 条」。- 这时候该说的是下一步做什么,而不是摆一张空图。 */- <Block gap={8} padding={20} variant={'outlined'}>- <Text weight={600}>{t('detail.notPractised')}</Text>- <Text fontSize={13} lineHeight={1.7} type={'secondary'}>- {t('detail.notPractisedDesc')}- </Text>- <Text fontSize={12.5} lineHeight={1.75} type={'secondary'}>- <Text as={'span'} weight={600}>- {t('detail.domainFilter')}- </Text>- {data.domain.domainFilter}- </Text>- </Block>- ) : (- <>- <Text className={styles.sentence}>- {t('detail.learningSummary', {- lessons: data.lessonStats.total,- })}- <br />- <Text className={styles.sentence} type={'secondary'}>- {t('detail.practiceSummary', {- hits: data.lessonStats.hits,- runs: data.runCount,- })}- </Text>- </Text>-- {data.runCount > 1 && (- <Text fontSize={13} type={'secondary'}>- {maturity?.usable- ? t('detail.subheadOk', {- ceiling: Math.round(maturity.pInf ?? 0),- shape: t(SHAPE_CLAUSE[maturity.plateauKind ?? 'growing']),- })- : t('detail.subheadUnusable')}- </Text>- )}-- {data.runCount === 1 ? (- <Block gap={6} padding={16} variant={'outlined'}>- <Text fontSize={13} weight={600}>- {t('detail.firstPracticeTitle')}- </Text>- <Text fontSize={12.5} lineHeight={1.7} type={'secondary'}>- {t('detail.firstPracticeDesc', { lessons: data.lessonStats.total })}- </Text>- </Block>- ) : (- <>- <Block gap={10} padding={16} variant={'outlined'}>- <Flexbox horizontal align={'center'} gap={5}>- <Flexbox gap={3} style={{ flex: 1, minWidth: 260 }}>- <Text fontSize={13} weight={600}>- {t('detail.chart.title')}- </Text>- <FitNote detail={data} />- </Flexbox>- </Flexbox>- <Flexbox horizontal align={'center'} gap={12} wrap={'wrap'}>- <Flexbox horizontal align={'center'} gap={5}>- <div- style={{ background: theme.colorSuccess, height: 3, width: 14 }}- />- <Text fontSize={11} type={'secondary'}>- {t('detail.chart.legendActual')}- </Text>- </Flexbox>- <Flexbox horizontal align={'center'} gap={5}>- <div- style={{- borderTop: `2px dashed ${theme.colorSuccess}`,- height: 0,- width: 14,- }}- />- <Text fontSize={11} type={'secondary'}>- {t('detail.chart.legendFit')}- </Text>- </Flexbox>- <Flexbox horizontal align={'center'} gap={5}>- <div- style={{- background: theme.colorFillSecondary,- height: 8,- width: 6,- }}- />- <div- style={{- background: theme.colorInfoBorder,- height: 8,- width: 6,- }}- />- <Text fontSize={11} type={'secondary'}>- {t('detail.chart.legendBars')}- </Text>- </Flexbox>- </Flexbox>- <FitCurve- maturity={data.maturity}- runCount={data.runCount}- series={data.series}- />- </Block>-- <FitMetrics detail={data} />- </>- )}-- <div className={styles.learningGrid}>- <CoverageCloud detail={data} />- <AsyncBoundary- data={lessons}- error={lessonsError}- isLoading={lessonsLoading}- loading={<Loading debugId={'SelfLearningDomainRules'} />}- onRetry={() => mutateLessons()}- >- {lessons && (- <RuleList- compact- lessonHref={(lessonId) => urlJoin(rulesPath, lessonId)}- lessons={lessons}- stats={data.lessonStats}- viewAllHref={rulesPath}- />- )}- </AsyncBoundary>- </div>-- <Block gap={7} padding={16} variant={'outlined'}>- <Text fontSize={13} weight={600}>- {t('detail.anchorTitle')}- </Text>- <Text fontSize={12.5} lineHeight={1.75}>- <Text as={'span'} weight={600}>- {t('detail.domainFilter')}- </Text>- {data.domain.domainFilter}- </Text>- {data.domain.outOfScope && (- <Text fontSize={12.5} lineHeight={1.75} type={'secondary'}>- <Text as={'span'} weight={600}>- {t('detail.outOfScope')}- </Text>- {data.domain.outOfScope}- </Text>- )}- </Block>- </>- )}- </Flexbox>- )}- </AsyncBoundary>- </WideScreenContainer>- </Flexbox>- </Flexbox>- );-});--/** 图下那一行:可信就说还要练多少次,不可信就说为什么不外推。 */-const FitNote = memo<{ detail: NonNullable<ReturnType<typeof useExpertiseDomain>['data']> }>(- ({ detail }) => {- const { t } = useTranslation('selfLearning');- const m = detail.maturity;- if (!m.usable) {- return (- <Text fontSize={11.5} lineHeight={1.7} type={'secondary'}>- {t('detail.chart.noProjection', { reason: t(`maturity.reason.${m.reason}`) })}- </Text>- );- }- const n90 = runsToRatio(m.tau ?? 1, 0.9);- const n95 = runsToRatio(m.tau ?? 1, 0.95);- return (- <Text fontSize={11.5} lineHeight={1.7} type={m.speculative ? 'warning' : 'secondary'}>- {m.speculative- ? t('detail.chart.speculative', {- n90,- span: (m.observedSpan ?? 0).toFixed(2),- tau: Math.round(m.tau ?? 0),- })- : t('detail.chart.trustworthy', {- n90,- n95,- remaining: Math.max(0, n90 - detail.runCount),- span: (m.observedSpan ?? 0).toFixed(1),- })}- </Text>- );- },-);--/**- * 四张指标卡。- *- * r² 和成熟度刻意并排:撞了 τ 上界的那几组回测 r² 同样漂亮 —— 贴合的是直线段。- * 把「拟合得好」和「外推可信」分开摆出来,读的人才不会把前者当成后者。- */-const FitMetrics = memo<{ detail: NonNullable<ReturnType<typeof useExpertiseDomain>['data']> }>(- ({ detail }) => {- const { t } = useTranslation('selfLearning');- const m = detail.maturity;- if (!m.usable && detail.runCount > 0) return null;- // 算不出的时候只留成熟度那张(它承载「为什么算不出」),其余三张整块不渲染。- // 一排「—」既没有信息又占掉整行,读起来像是坏了而不是「这次没算出来」。- const cards: [string, string, string][] = m.usable- ? [- [- t('detail.metric.maturity'),- `${Math.round((m.maturity ?? 0) * 100)}%`,- t('detail.metric.maturitySub', {- ceiling: Math.round(m.pInf ?? 0),- learned: detail.lessonStats.total,- }),- ],- [- t('detail.metric.rate'),- m.tau ? (1 / m.tau).toFixed(3) : '—',- m.tau ? t('detail.metric.rateSub', { tau: Math.round(m.tau) }) : '—',- ],- [- t('detail.metric.r2'),- m.fitR2 == null ? '—' : m.fitR2.toFixed(3),- m.fitSampleSize ? t('detail.metric.r2Sub', { count: m.fitSampleSize }) : '—',- ],- [- t('detail.metric.shape'),- m.plateauKind ? t(PLATEAU_KEY[m.plateauKind] ?? 'plateau.noisy') : '—',- t('detail.metric.shapeSub', { count: detail.tailGain }),- ],- ]- : [- [- t('detail.metric.maturity'),- t('detail.metric.cannot'),- t(`maturity.reason.${m.reason}`),- ],- ];-- return (- <Flexbox horizontal gap={12} wrap={'wrap'}>- {cards.map(([label, value, sub]) => (- <Block- gap={3}- key={label}- padding={16}- style={{ flex: 1, minWidth: 190 }}- variant={'outlined'}- >- <Text fontSize={11} type={'secondary'}>- {label}- </Text>- <Text fontSize={22} weight={700}>- {value}- </Text>- <Text fontSize={11} type={'secondary'}>- {sub}- </Text>- </Block>- ))}- </Flexbox>- );- },-);--FitNote.displayName = 'FitNote';-FitMetrics.displayName = 'FitMetrics';-DomainDetail.displayName = 'DomainDetail';--export default DomainDetail;diff --git a/src/features/SelfLearning/Portrait/AnchorCard.tsx b/src/features/SelfLearning/Portrait/AnchorCard.tsxnew file mode 100644index 00000000000..d86bc373cd3--- /dev/null+++ b/src/features/SelfLearning/Portrait/AnchorCard.tsx@@ -0,0 +1,162 @@+'use client';++import { Block, Flexbox, Icon, Text } from '@lobehub/ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { AnchorIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import type { ExpertiseDomainItem } from '@/services/expertise';++const styles = createStaticStyles(({ css }) => ({+ canonCard: css`+ display: flex;+ flex-direction: column;+ gap: 6px;++ min-width: 0;+ padding-block: 12px;+ padding-inline: 14px;+ border-radius: ${cssVar.borderRadiusLG};++ background: ${cssVar.colorFillQuaternary};+ `,+ definition: css`+ display: grid;+ grid-template-columns: 84px minmax(0, 1fr);+ gap: 6px 16px;+ align-items: baseline;+ `,+ grid: css`+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));+ gap: 10px;+ `,+ layerCell: css`+ display: flex;+ flex-direction: column;+ gap: 4px;++ min-width: 0;+ padding-inline-start: 12px;+ border-inline-start: 2px solid ${cssVar.colorBorderSecondary};+ `,+ layerIndex: css`+ font-family: ${cssVar.fontFamilyCode};+ font-size: 11px;+ color: ${cssVar.colorTextQuaternary};+ letter-spacing: 0.04em;+ `,+ sectionLabel: css`+ font-size: 12px;+ font-weight: 600;+ color: ${cssVar.colorTextSecondary};+ letter-spacing: 0.02em;+ `,+}));++/**+ * 它的锚 —— 这个方向拿什么标准在学:什么算实践、对照哪些经典原则、分成哪几层。+ * 建域时定下的东西,在详情里必须看得见;否则画像里的「层」和「覆盖」都无从解释。+ *+ * 排版:定义两行(标签列 + 正文)→ 经典依据卡片网格 → 分层横向条带。+ * 三块信息形态不同(句子 / 引文 / 层级),各用各的形状,不做成一列文字。+ */+const AnchorCard = memo<{ domain: ExpertiseDomainItem }>(({ domain }) => {+ const { t } = useTranslation('selfLearning');+ const canonRef =+ domain.layerSource === 'canonical' && domain.layerCanonRef ? domain.layerCanonRef : undefined;++ return (+ <Block padding={16} variant={'outlined'}>+ <Flexbox gap={18}>+ <Flexbox horizontal align={'center'} gap={8}>+ <Icon color={cssVar.colorTextTertiary} icon={AnchorIcon} size={15} />+ <Text weight={600}>{t('anchor.title')}</Text>+ <Text fontSize={12} type={'secondary'}>+ {t('anchor.subtitle')}+ </Text>+ </Flexbox>++ <div className={styles.definition}>+ <Text fontSize={12.5} type={'secondary'}>+ {t('anchor.filter')}+ </Text>+ <Text fontSize={13} lineHeight={1.7}>+ {domain.domainFilter}+ </Text>+ {domain.outOfScope && (+ <>+ <Text fontSize={12.5} type={'secondary'}>+ {t('anchor.outOfScope')}+ </Text>+ <Text fontSize={13} lineHeight={1.7} type={'secondary'}>+ {domain.outOfScope}+ </Text>+ </>+ )}+ </div>++ <Flexbox gap={10}>+ <Flexbox horizontal align={'baseline'} gap={8}>+ <span className={styles.sectionLabel}>{t('create.anchor.canon')}</span>+ <Text fontSize={12} type={'secondary'}>+ {domain.canonEntries.length > 0 ? t('create.anchor.canonHint') : t('anchor.noCanon')}+ </Text>+ </Flexbox>+ {domain.canonEntries.length > 0 && (+ <div className={styles.grid}>+ {domain.canonEntries.map((c) => (+ <div className={styles.canonCard} key={c.key}>+ <Text fontSize={13.5} weight={600}>+ {c.title}+ </Text>+ <Text fontSize={12.5} lineHeight={1.65} type={'secondary'}>+ {c.statement}+ </Text>+ <Text ellipsis fontSize={11.5} style={{ opacity: 0.75 }} type={'secondary'}>+ — {c.source}+ </Text>+ </div>+ ))}+ </div>+ )}+ </Flexbox>++ <Flexbox gap={10}>+ <Flexbox horizontal align={'baseline'} gap={8}>+ <span className={styles.sectionLabel}>{t('create.anchor.layers')}</span>+ <Text fontSize={12} type={'secondary'}>+ {domain.layers.length === 0+ ? t('anchor.noLayers')+ : canonRef+ ? t('create.anchor.layersFrom', { ref: canonRef })+ : t('create.anchor.layersInvented')}+ </Text>+ </Flexbox>+ {domain.layers.length > 0 && (+ <div className={styles.grid}>+ {domain.layers.map((l, i) => (+ <div className={styles.layerCell} key={l.key}>+ <span className={styles.layerIndex}>L{i + 1}</span>+ <Text fontSize={13.5} weight={600}>+ {l.title}+ </Text>+ {l.description && (+ <Text fontSize={12.5} lineHeight={1.6} type={'secondary'}>+ {l.description}+ </Text>+ )}+ </div>+ ))}+ </div>+ )}+ </Flexbox>+ </Flexbox>+ </Block>+ );+});++AnchorCard.displayName = 'ExpertiseAnchorCard';++export default AnchorCard;diff --git a/src/features/SelfLearning/Portrait/DomainList.tsx b/src/features/SelfLearning/Portrait/DomainList.tsxnew file mode 100644index 00000000000..e01d1976b08--- /dev/null+++ b/src/features/SelfLearning/Portrait/DomainList.tsx@@ -0,0 +1,79 @@+'use client';++import { Block, Flexbox, Icon, Text } from '@lobehub/ui';+import { ChevronRightIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import type { ExpertiseDomainItem } from '@/services/expertise';++import { countTiers } from '../helpers';+import { portraitStyles as styles } from './styles';+import TierBar from './TierBar';++interface DomainListProps {+ domains: ExpertiseDomainItem[];+ onOpen: (domainId: string) => void;+}++/** 多个方向时的方向清单:一根可靠度条 + 一个词。单方向时不渲染 —— 方向就是判断句的主语。 */+const DomainList = memo<DomainListProps>(({ domains, onOpen }) => {+ const { t } = useTranslation('selfLearning');+ return (+ <Flexbox gap={8}>+ <Text fontSize={12} type={'secondary'}>+ {t('domains.title')} {domains.length}+ </Text>+ <Block padding={0} variant={'outlined'}>+ {domains.map((d) => {+ const counts = countTiers(d.lessons);+ const word = counts.recurring+ ? t('domains.word.recurring', { count: counts.recurring })+ : counts.shaky+ ? t('domains.word.shaky', { count: counts.shaky })+ : d.lessons.length <= 3+ ? t('domains.word.fresh')+ : t('domains.word.stable');+ return (+ <Flexbox+ horizontal+ align={'center'}+ as={'button'}+ className={styles.row}+ gap={12}+ key={d.id}+ style={{+ background: 'transparent',+ color: 'inherit',+ textAlign: 'start',+ width: '100%',+ }}+ onClick={() => onOpen(d.id)}+ >+ <Text style={{ flex: 'none', width: 140 }} weight={500}>+ {d.title}+ </Text>+ <TierBar counts={counts} total={d.lessons.length} />+ <Text+ className={counts.recurring ? styles.accent : undefined}+ fontSize={12.5}+ style={{ flex: 1 }}+ type={counts.recurring ? undefined : 'secondary'}+ >+ {word}+ </Text>+ <Text fontSize={12} type={'secondary'}>+ {t('domains.meta', { habits: d.lessons.length, runs: d.runCount })}+ </Text>+ <Icon icon={ChevronRightIcon} size={13} style={{ flex: 'none', opacity: 0.4 }} />+ </Flexbox>+ );+ })}+ </Block>+ </Flexbox>+ );+});++DomainList.displayName = 'ExpertiseDomainList';++export default DomainList;diff --git a/src/features/SelfLearning/Portrait/GrowthCharts.tsx b/src/features/SelfLearning/Portrait/GrowthCharts.tsxnew file mode 100644index 00000000000..5f30857c791--- /dev/null+++ b/src/features/SelfLearning/Portrait/GrowthCharts.tsx@@ -0,0 +1,240 @@+'use client';++import { Block, Flexbox, Text } from '@lobehub/ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { memo, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import type { ExpertiseDomainItem } from '@/services/expertise';++import { earlyPassRate, passRateSeries, recentPassRate, zeroViolationStreak } from '../helpers';++const styles = createStaticStyles(({ css }) => ({+ chart: css`+ flex: 1;+ min-width: 0;++ .axis {+ font-size: 10px;+ fill: ${cssVar.colorTextQuaternary};+ }++ .grid {+ stroke: ${cssVar.colorBorderSecondary};+ }++ .line {+ fill: none;+ stroke: ${cssVar.colorSuccess};+ stroke-width: 1.75;+ }++ .area {+ fill: ${cssVar.colorSuccess};+ fill-opacity: 0.08;+ }++ .pt {+ fill: ${cssVar.colorSuccess};+ }++ .ref {+ stroke: ${cssVar.colorSuccess};+ stroke-dasharray: 3 3;+ stroke-opacity: 0.45;+ }++ .refLabel {+ font-size: 10px;+ fill: ${cssVar.colorSuccess};+ }+ `,+}));++const W = 380;+const H = 96;+const L = 6;+const R = 44;+const T = 10;+const B = 16;++interface GrowthChartsProps {+ domains: ExpertiseDomainItem[];+}++/**+ * 两块默认展示的成长曲线:累计学到(它懂了多少)+ 做对率(它可靠了没)。+ * 两条都往上走 —— 「学得多了、做得对了」同向,一眼读出「在变成专家」。+ * 多个方向时按实践序号对齐求和 / 求均。+ */+const GrowthCharts = memo<GrowthChartsProps>(({ domains }) => {+ const { t } = useTranslation('selfLearning');++ const { cum, rate, streak, runs } = useMemo(() => {+ if (domains.length === 1) {+ const d = domains[0];+ return {+ cum: d.series.map((p) => ({ n: p.n, run: p.run })),+ rate: passRateSeries(d.reliability),+ runs: d.runCount,+ streak: zeroViolationStreak(d.reliability),+ };+ }+ // Multi-domain: sum learned per run index across domains, average pass rate per run index.+ const maxRun = Math.max(0, ...domains.map((d) => d.runCount));+ const cumArr: { n: number; run: number }[] = [];+ const rateArr: { rate: number; run: number }[] = [];+ for (let run = 1; run <= maxRun; run++) {+ let n = 0;+ let pass = 0;+ let violation = 0;+ for (const d of domains) {+ const last = [...d.series].reverse().find((p) => p.run <= run);+ n += last?.n ?? 0;+ const rel = d.reliability.find((r) => r.run === run);+ if (rel) {+ pass += rel.pass;+ violation += rel.violation;+ }+ }+ cumArr.push({ n, run });+ if (pass + violation > 0) rateArr.push({ rate: pass / (pass + violation), run });+ }+ const merged = Array.from({ length: maxRun }, (_, i) => {+ let pass = 0;+ let violation = 0;+ for (const d of domains) {+ const rel = d.reliability.find((r) => r.run === i + 1);+ if (rel) {+ pass += rel.pass;+ violation += rel.violation;+ }+ }+ return { pass, run: i + 1, violation };+ });+ return { cum: cumArr, rate: rateArr, runs: maxRun, streak: zeroViolationStreak(merged) };+ }, [domains]);++ if (cum.length < 2) {+ return (+ <Text fontSize={12.5} type={'secondary'}>+ {t('charts.tooFew')}+ </Text>+ );+ }++ const n = cum.length;+ const x = (i: number, len: number) => L + (len === 1 ? 0 : (i / (len - 1)) * (W - L - R));+ const cmax = Math.max(1, ...cum.map((p) => p.n));+ const yc = (v: number) => T + (1 - v / cmax) * (H - T - B);+ const yr = (v: number) => T + (1 - v) * (H - T - B);+ const recent = recentPassRate(rate);+ const early = earlyPassRate(rate);+ const pct = (v: number | null) => (v === null ? '—' : `${Math.round(v * 100)}%`);++ return (+ <Block padding={'12px 14px'} variant={'outlined'}>+ <Flexbox horizontal gap={24}>+ <Flexbox className={styles.chart} gap={4}>+ <Flexbox horizontal align={'baseline'} gap={8}>+ <Text fontSize={12} type={'secondary'}>+ {t('charts.learned')}+ </Text>+ <Text fontSize={18} weight={700}>+ {t('charts.count', { count: cum.at(-1)!.n })}+ </Text>+ <Text fontSize={12} type={'secondary'}>+ {t('charts.learnedSub', { runs })}+ </Text>+ </Flexbox>+ <svg height={H} viewBox={`0 0 ${W} ${H}`} width={'100%'}>+ {[0, 0.5, 1].map((f) => (+ <g key={f}>+ <line className={'grid'} x1={L} x2={W - R} y1={yc(cmax * f)} y2={yc(cmax * f)} />+ <text className={'axis'} x={W - R + 4} y={yc(cmax * f) + 3}>+ {Math.round(cmax * f)}+ </text>+ </g>+ ))}+ <polygon+ className={'area'}+ points={`${x(0, n)},${yc(0)} ${cum.map((p, i) => `${x(i, n)},${yc(p.n)}`).join(' ')} ${x(n - 1, n)},${yc(0)}`}+ />+ <polyline+ className={'line'}+ points={cum.map((p, i) => `${x(i, n)},${yc(p.n)}`).join(' ')}+ />+ <circle className={'pt'} cx={x(n - 1, n)} cy={yc(cum.at(-1)!.n)} r={2.5} />+ <text className={'axis'} x={L} y={H - 3}>+ {t('charts.run1')}+ </text>+ <text className={'axis'} textAnchor={'end'} x={W - R} y={H - 3}>+ {t('charts.runN', { n: cum.at(-1)!.run })}+ </text>+ </svg>+ </Flexbox>++ <Flexbox className={styles.chart} gap={4}>+ <Flexbox horizontal align={'baseline'} gap={8} wrap={'wrap'}>+ <Text fontSize={12} type={'secondary'}>+ {t('charts.passRate')}+ </Text>+ <Text fontSize={18} weight={700}>+ {pct(recent)}+ </Text>+ <Text fontSize={12} type={'secondary'}>+ {streak >= 2+ ? t('charts.streak', { count: streak })+ : t('charts.recentAvg', { count: Math.min(4, rate.length) })}+ {early !== null && rate.length > 4+ ? ` · ${t('charts.early', { rate: Math.round(early * 100) })}`+ : ''}+ </Text>+ </Flexbox>+ <svg height={H} viewBox={`0 0 ${W} ${H}`} width={'100%'}>+ {[0, 0.5, 1].map((f) => (+ <g key={f}>+ <line className={'grid'} x1={L} x2={W - R} y1={yr(f)} y2={yr(f)} />+ <text className={'axis'} x={W - R + 4} y={yr(f) + 3}>+ {Math.round(f * 100)}%+ </text>+ </g>+ ))}+ <line className={'ref'} x1={L} x2={W - R} y1={yr(0.9)} y2={yr(0.9)} />+ <text className={'refLabel'} x={L + 2} y={yr(0.9) - 3}>+ {t('charts.refLine')}+ </text>+ {rate.length > 0 && (+ <>+ <polygon+ className={'area'}+ points={`${x(0, rate.length)},${yr(0)} ${rate.map((p, i) => `${x(i, rate.length)},${yr(p.rate)}`).join(' ')} ${x(rate.length - 1, rate.length)},${yr(0)}`}+ />+ <polyline+ className={'line'}+ points={rate.map((p, i) => `${x(i, rate.length)},${yr(p.rate)}`).join(' ')}+ />+ <circle+ className={'pt'}+ cx={x(rate.length - 1, rate.length)}+ cy={yr(rate.at(-1)!.rate)}+ r={2.5}+ />+ </>+ )}+ <text className={'axis'} x={L} y={H - 3}>+ {t('charts.run1')}+ </text>+ <text className={'axis'} textAnchor={'end'} x={W - R} y={H - 3}>+ {t('charts.runN', { n: cum.at(-1)!.run })}+ </text>+ </svg>+ </Flexbox>+ </Flexbox>+ </Block>+ );+});++GrowthCharts.displayName = 'ExpertiseGrowthCharts';++export default GrowthCharts;diff --git a/src/features/SelfLearning/Portrait/HabitList.tsx b/src/features/SelfLearning/Portrait/HabitList.tsxnew file mode 100644index 00000000000..4164356a555--- /dev/null+++ b/src/features/SelfLearning/Portrait/HabitList.tsx@@ -0,0 +1,314 @@+'use client';++import { ActionIcon, Block, Flexbox, Icon, SearchBar, Tag, Text, Tooltip } from '@lobehub/ui';+import type { DropdownItem } from '@lobehub/ui/base-ui';+import { Button, DropdownMenu, toast } from '@lobehub/ui/base-ui';+import dayjs from 'dayjs';+import {+ ArchiveIcon,+ ChevronDownIcon,+ ChevronUpIcon,+ MessageSquareTextIcon,+ MoreHorizontalIcon,+ PencilIcon,+} from 'lucide-react';+import { Fragment, memo, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { useNavigate } from 'react-router';+import urlJoin from 'url-join';++import type { ExpertiseHabit } from '@/services/expertise';+import { expertiseService } from '@/services/expertise';++import { countTiers, type HabitTier, habitTier, TIER_ORDER } from '../helpers';+import { portraitStyles as styles } from './styles';+import TeachBox from './TeachBox';++interface HabitListProps {+ agentId: string;+ /** Present when the list mixes several domains, so each row can say which one it belongs to. */+ domainTitles?: Record<string, string>;+ habits: (ExpertiseHabit & { domainId: string })[];+ onChanged: () => void;+}++const RecentDots = memo<{ recent: ExpertiseHabit['recent'] }>(({ recent }) => {+ const { t } = useTranslation('selfLearning');+ const tip =+ recent.length === 0+ ? t('habit.recentTip.none')+ : t('habit.recentTip.title', {+ count: recent.length,+ list: recent+ .map((r) => (r.pass ? t('habit.recentTip.pass') : t('habit.recentTip.violation')))+ .join(' '),+ });+ return (+ <Tooltip title={tip}>+ <Flexbox horizontal gap={3} style={{ flex: 'none' }}>+ {recent.length === 0+ ? [0, 1, 2].map((i) => <span className={`${styles.dot} ${styles.dotNone}`} key={i} />)+ : recent.map((r, i) => (+ <span className={`${styles.dot} ${r.pass ? styles.dotOk : styles.dotBad}`} key={i} />+ ))}+ </Flexbox>+ </Tooltip>+ );+});++RecentDots.displayName = 'ExpertiseRecentDots';++interface HabitRowProps {+ agentId: string;+ domainTitle?: string;+ habit: ExpertiseHabit & { domainId: string };+ onChanged: () => void;+ tier: HabitTier;+}++const HabitRow = memo<HabitRowProps>(({ agentId, domainTitle, habit, onChanged, tier }) => {+ const { t } = useTranslation('selfLearning');+ const navigate = useNavigate();+ const [teaching, setTeaching] = useState(false);++ const hint = useMemo(() => {+ if (habit.taughtByUser && habit.recent.length === 0) return t('habit.hint.taughtPending');+ const bad = habit.recent.filter((r) => !r.pass);+ const lastBad = [...bad].reverse()[0];+ const topic = lastBad?.subjectTitle ?? undefined;+ switch (tier) {+ case 'recurring': {+ return topic+ ? t('habit.hint.recurring', { bad: bad.length, topic, total: habit.recent.length })+ : t('habit.hint.recurringNoTopic', { bad: bad.length, total: habit.recent.length });+ }+ case 'shaky': {+ return topic+ ? t('habit.hint.shaky', { topic, total: habit.recent.length })+ : t('habit.hint.shakyNoTopic', { total: habit.recent.length });+ }+ case 'fresh': {+ return habit.recent.length === 0 ? t('habit.hint.freshNone') : t('habit.hint.freshOne');+ }+ default: {+ return t('habit.hint.stable', { count: habit.hitCount });+ }+ }+ }, [habit, t, tier]);++ const revise = async (text: string) => {+ try {+ await expertiseService.reviseLesson({ lessonId: habit.id, text });+ toast.success(t('habit.teach.done'));+ setTeaching(false);+ onChanged();+ } catch {+ toast.error(t('habit.teach.failed'));+ }+ };++ const retire = async () => {+ try {+ await expertiseService.retireLesson(habit.id);+ toast.success(t('habit.teach.forgot'));+ onChanged();+ } catch {+ toast.error(t('habit.teach.failed'));+ }+ };++ const lessonPath = urlJoin('/agent', agentId, 'self-learning', habit.domainId, 'rules', habit.id);+ const menu: DropdownItem[] = [+ {+ icon: <Icon icon={PencilIcon} />,+ key: 'correct',+ label: t('habit.action.correct'),+ onClick: () => setTeaching(true),+ },+ {+ icon: <Icon icon={MessageSquareTextIcon} />,+ key: 'source',+ label: t('habit.action.source'),+ onClick: () => navigate(lessonPath),+ },+ { type: 'divider' },+ {+ danger: true,+ icon: <Icon icon={ArchiveIcon} />,+ key: 'forget',+ label: t('habit.action.forget'),+ onClick: retire,+ },+ ];++ return (+ <Flexbox className={styles.row} gap={6}>+ <Flexbox horizontal align={'flex-start'} gap={12}>+ <Text code fontSize={12} style={{ flex: 'none', marginTop: 2 }} type={'secondary'}>+ {habit.code}+ </Text>+ <Flexbox gap={2} style={{ flex: 1, minWidth: 0 }}>+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>+ <Text fontSize={13.5} weight={500}>+ {habit.title}+ </Text>+ {habit.taughtByUser && (+ <Tag>+ {t('habit.taughtTag')} · {dayjs(habit.createdAt).fromNow()}+ </Tag>+ )}+ {domainTitle && <Tag>{domainTitle}</Tag>}+ </Flexbox>+ <Text fontSize={12} type={'secondary'}>+ {hint}+ </Text>+ </Flexbox>+ <RecentDots recent={habit.recent} />+ <Flexbox horizontal align={'center'} className={'teach'} gap={4} style={{ flex: 'none' }}>+ {(tier === 'recurring' || tier === 'shaky') && (+ <Button+ size={'small'}+ type={tier === 'recurring' ? 'primary' : 'default'}+ onClick={() => setTeaching((v) => !v)}+ >+ {t('habit.action.teachAgain')}+ </Button>+ )}+ <DropdownMenu items={menu}>+ <ActionIcon icon={MoreHorizontalIcon} size={'small'} />+ </DropdownMenu>+ </Flexbox>+ </Flexbox>+ {teaching && (+ <Flexbox style={{ paddingInlineStart: 48 }}>+ <TeachBox+ autoFocus+ placeholder={+ tier === 'recurring'+ ? t('habit.teach.placeholderRecurring')+ : t('habit.teach.placeholderCorrect')+ }+ onSubmit={revise}+ />+ </Flexbox>+ )}+ </Flexbox>+ );+});++HabitRow.displayName = 'ExpertiseHabitRow';++/**+ * 习惯清单,按可靠度分组:老毛病 → 还不稳 → 刚学的 展开,已养成 折起。+ * 值得看的都在上面,稳的收起来 —— 用户不需要有精力逐条过。+ */+const HabitList = memo<HabitListProps>(({ agentId, domainTitles, habits, onChanged }) => {+ const { t } = useTranslation('selfLearning');+ const [search, setSearch] = useState('');+ const [stableOpen, setStableOpen] = useState(false);++ const counts = useMemo(() => countTiers(habits), [habits]);+ const grouped = useMemo(() => {+ const g: Record<HabitTier, HabitListProps['habits']> = {+ fresh: [],+ recurring: [],+ shaky: [],+ stable: [],+ };+ const q = search.trim().toLowerCase();+ for (const h of habits) {+ if (q && !h.title.toLowerCase().includes(q) && !h.code.toLowerCase().includes(q)) continue;+ g[habitTier(h.recent)].push(h);+ }+ return g;+ }, [habits, search]);++ const stableVisible = stableOpen || !!search.trim();++ return (+ <Flexbox gap={10}>+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'} wrap={'wrap'}>+ <Flexbox horizontal align={'baseline'} gap={8}>+ <Text weight={600}>{t('habits.title')}</Text>+ <Text fontSize={12} type={'secondary'}>+ {t('habits.summary', counts)}+ </Text>+ </Flexbox>+ <SearchBar+ placeholder={t('habits.search')}+ style={{ width: 200 }}+ value={search}+ variant={'filled'}+ onChange={(e) => setSearch(e.target.value)}+ />+ </Flexbox>+ <Block padding={0} variant={'outlined'}>+ {TIER_ORDER.filter((tier) => tier !== 'stable').map((tier) => {+ const rows = grouped[tier];+ if (rows.length === 0) return null;+ return (+ <Fragment key={tier}>+ <Flexbox horizontal align={'center'} className={styles.groupHead} gap={8}>+ <Text+ className={tier === 'recurring' ? styles.accent : undefined}+ fontSize={12.5}+ weight={600}+ >+ {t(`tier.${tier}`)} {rows.length}+ </Text>+ <Text fontSize={12} type={'secondary'}>+ {t(`tier.${tier}Sub`)}+ </Text>+ </Flexbox>+ {rows.map((h) => (+ <HabitRow+ agentId={agentId}+ domainTitle={domainTitles?.[h.domainId]}+ habit={h}+ key={h.id}+ tier={tier}+ onChanged={onChanged}+ />+ ))}+ </Fragment>+ );+ })}+ <Flexbox+ horizontal+ align={'center'}+ as={'button'}+ className={styles.groupHead}+ gap={8}+ justify={'space-between'}+ style={{ background: undefined, color: 'inherit', cursor: 'pointer', width: '100%' }}+ onClick={() => setStableOpen((v) => !v)}+ >+ <Flexbox horizontal align={'center'} gap={8}>+ <Text fontSize={12.5} weight={600}>+ {t('tier.stable')} {grouped.stable.length}+ </Text>+ <Text fontSize={12} type={'secondary'}>+ {t('tier.stableSub')}+ </Text>+ </Flexbox>+ <Icon icon={stableVisible ? ChevronUpIcon : ChevronDownIcon} size={14} />+ </Flexbox>+ {stableVisible &&+ grouped.stable.map((h) => (+ <HabitRow+ agentId={agentId}+ domainTitle={domainTitles?.[h.domainId]}+ habit={h}+ key={h.id}+ tier={'stable'}+ onChanged={onChanged}+ />+ ))}+ </Block>+ </Flexbox>+ );+});++HabitList.displayName = 'ExpertiseHabitList';++export default HabitList;diff --git a/src/features/SelfLearning/Portrait/LayerProfile.tsx b/src/features/SelfLearning/Portrait/LayerProfile.tsxnew file mode 100644index 00000000000..b2eb5f21185--- /dev/null+++ b/src/features/SelfLearning/Portrait/LayerProfile.tsx@@ -0,0 +1,62 @@+'use client';++import { Block, Flexbox, Text } from '@lobehub/ui';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import type { ExpertiseDomainItem } from '@/services/expertise';++import { countTiers, profileWord } from '../helpers';+import { portraitStyles as styles } from './styles';+import TierBar from './TierBar';++/** 「它在哪儿强、哪儿弱」—— 按领域自己的分层,一层一行。 */+const LayerProfile = memo<{ domain: ExpertiseDomainItem }>(({ domain }) => {+ const { t } = useTranslation('selfLearning');+ if (domain.layers.length === 0 || domain.lessons.length === 0) return null;++ return (+ <Block padding={'10px 14px'} variant={'outlined'}>+ <Flexbox gap={8}>+ <Text fontSize={12} type={'secondary'}>+ {t('profile.title')}+ </Text>+ {domain.layers.map((layer) => {+ const habits = domain.lessons.filter((l) => l.layer === layer.key);+ const counts = countTiers(habits);+ const word = profileWord(counts, habits.length);+ const weak = word === 'weak';+ const parts = [+ t('profile.counts', { count: habits.length }),+ counts.recurring ? t('profile.recurring', { count: counts.recurring }) : null,+ counts.shaky ? t('profile.shaky', { count: counts.shaky }) : null,+ counts.fresh ? t('profile.fresh', { count: counts.fresh }) : null,+ ].filter(Boolean);+ return (+ <Flexbox horizontal align={'center'} gap={12} key={layer.key}>+ <Text fontSize={13} style={{ flex: 'none', width: 96 }} weight={500}>+ {layer.title}+ </Text>+ <TierBar counts={counts} total={habits.length} />+ <Text+ className={weak ? styles.accent : undefined}+ fontSize={12.5}+ type={weak ? undefined : 'secondary'}+ weight={weak ? 600 : undefined}+ >+ {t(`profile.word.${word}`)}+ </Text>+ <Text fontSize={12} type={'secondary'}>+ {parts.join(' · ')}+ </Text>+ </Flexbox>+ );+ })}+ </Flexbox>+ </Block>+ );+});++LayerProfile.displayName = 'ExpertiseLayerProfile';++export default LayerProfile;diff --git a/src/features/SelfLearning/Portrait/TaughtList.tsx b/src/features/SelfLearning/Portrait/TaughtList.tsxnew file mode 100644index 00000000000..c0fe225a048--- /dev/null+++ b/src/features/SelfLearning/Portrait/TaughtList.tsx@@ -0,0 +1,65 @@+'use client';++import { Block, Flexbox, Text } from '@lobehub/ui';+import dayjs from 'dayjs';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import type { ExpertiseHabit } from '@/services/expertise';++import { habitTier } from '../helpers';+import { portraitStyles as styles } from './styles';++/**+ * 教学的回响:你教过的每一件事,现在怎么样了。+ * 「用上了」这一档要等注入回路才会真的发生 —— 在那之前它只会停在「还没机会用」。+ */+const TaughtList = memo<{ habits: ExpertiseHabit[] }>(({ habits }) => {+ const { t } = useTranslation('selfLearning');+ const taught = habits.filter((h) => h.taughtByUser);+ if (taught.length === 0) return null;++ return (+ <Block padding={'10px 14px'} variant={'outlined'}>+ <Flexbox gap={6}>+ <Text fontSize={12} type={'secondary'}>+ {t('taught.title', { count: taught.length })}+ </Text>+ {taught.map((h) => {+ const tier = habitTier(h.recent);+ const arc =+ tier === 'recurring'+ ? 'recurring'+ : tier === 'shaky'+ ? 'shaky'+ : h.recent.length > 0+ ? 'used'+ : 'pending';+ const bad = arc === 'recurring' || arc === 'shaky';+ return (+ <Flexbox horizontal align={'center'} gap={10} key={h.id}>+ <Text fontSize={12} style={{ flex: 'none', width: 64 }} type={'secondary'}>+ {dayjs(h.createdAt).fromNow()}+ </Text>+ <Text ellipsis fontSize={13} style={{ flex: 1 }}>+ {h.title}+ </Text>+ <Text+ className={bad ? styles.accent : undefined}+ fontSize={12.5}+ type={bad ? undefined : 'secondary'}+ weight={bad ? 600 : undefined}+ >+ {t(`taught.arc.${arc}`)}+ </Text>+ </Flexbox>+ );+ })}+ </Flexbox>+ </Block>+ );+});++TaughtList.displayName = 'ExpertiseTaughtList';++export default TaughtList;diff --git a/src/features/SelfLearning/Portrait/TeachBox.tsx b/src/features/SelfLearning/Portrait/TeachBox.tsxnew file mode 100644index 00000000000..157c2f28891--- /dev/null+++ b/src/features/SelfLearning/Portrait/TeachBox.tsx@@ -0,0 +1,55 @@+'use client';++import { Flexbox, TextArea } from '@lobehub/ui';+import { Button } from '@lobehub/ui/base-ui';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++interface TeachBoxProps {+ autoFocus?: boolean;+ onSubmit: (text: string) => Promise<void> | void;+ placeholder: string;+}++/** 一句话教它。教学动作全是随手的,所以这里只有一个输入框和一个按钮。 */+const TeachBox = memo<TeachBoxProps>(({ autoFocus, onSubmit, placeholder }) => {+ const { t } = useTranslation('selfLearning');+ const [value, setValue] = useState('');+ const [busy, setBusy] = useState(false);++ const submit = async () => {+ const text = value.trim();+ if (!text || busy) return;+ setBusy(true);+ try {+ await onSubmit(text);+ setValue('');+ } finally {+ setBusy(false);+ }+ };++ return (+ <Flexbox horizontal align={'flex-end'} gap={8} width={'100%'}>+ <TextArea+ autoFocus={autoFocus}+ autoSize={{ maxRows: 4, minRows: 1 }}+ disabled={busy}+ placeholder={placeholder}+ style={{ flex: 1 }}+ value={value}+ onChange={(e) => setValue(e.target.value)}+ onKeyDown={(e) => {+ if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') void submit();+ }}+ />+ <Button disabled={!value.trim()} loading={busy} type={'primary'} onClick={submit}>+ {t('habit.teach.send')}+ </Button>+ </Flexbox>+ );+});++TeachBox.displayName = 'ExpertiseTeachBox';++export default TeachBox;diff --git a/src/features/SelfLearning/Portrait/TierBar.tsx b/src/features/SelfLearning/Portrait/TierBar.tsxnew file mode 100644index 00000000000..b92feba6343--- /dev/null+++ b/src/features/SelfLearning/Portrait/TierBar.tsx@@ -0,0 +1,24 @@+'use client';++import { memo } from 'react';++import type { TierCounts } from '../helpers';+import { portraitStyles as styles } from './styles';++/** 已养成 = 灰、有错 = 琥珀(老毛病实心、还不稳半透)、刚学 = 留白。 */+const TierBar = memo<{ counts: TierCounts; total: number }>(({ counts, total }) => {+ const denom = total || 1;+ const seg = (n: number, cls: string, key: string) =>+ n > 0 ? <div className={cls} key={key} style={{ width: `${(n / denom) * 100}%` }} /> : null;+ return (+ <div className={styles.bar}>+ {seg(counts.stable, styles.segOk, 'stable')}+ {seg(counts.shaky, styles.segShaky, 'shaky')}+ {seg(counts.recurring, styles.segBad, 'recurring')}+ </div>+ );+});++TierBar.displayName = 'ExpertiseTierBar';++export default TierBar;diff --git a/src/features/SelfLearning/Portrait/WarmupCard.tsx b/src/features/SelfLearning/Portrait/WarmupCard.tsxnew file mode 100644index 00000000000..f6588c0bac0--- /dev/null+++ b/src/features/SelfLearning/Portrait/WarmupCard.tsx@@ -0,0 +1,100 @@+'use client';++import { Block, Flexbox, Icon, Text } from '@lobehub/ui';+import { Button } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, keyframes } from 'antd-style';+import { GraduationCapIcon, HistoryIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import type { useHistoryWarmup } from './useHistoryWarmup';++/** 从左往右填满再淡出、循环 —— 读起来是「在进行」,不会被读成「从右边开始的进度条」。 */+const fill = keyframes`+ 0% { width: 0; opacity: 1; }+ 80% { width: 100%; opacity: 1; }+ 100% { width: 100%; opacity: 0; }+`;++const styles = createStaticStyles(({ css }) => ({+ track: css`+ position: relative;++ overflow: hidden;++ width: 160px;+ height: 6px;+ border-radius: 3px;++ background: ${cssVar.colorFillSecondary};++ &::after {+ content: '';++ position: absolute;+ inset-block: 0;+ inset-inline-start: 0;++ border-radius: 3px;++ background: ${cssVar.colorSuccess};++ animation: ${fill} 1.8s ease-in-out infinite;+ }+ `,+}));++interface WarmupCardProps {+ candidateCount?: number;+ domainTitle: string;+ warmup: ReturnType<typeof useHistoryWarmup>;+}++/**+ * 让它温习历史对话 —— 不是审批流:学到的立刻开始用,卡片只负责让「正在学」可感。+ * 单行布局:左边说明,右边动作 / 进度。后端不报进度,所以条是流动的,数字才是真实的。+ */+const WarmupCard = memo<WarmupCardProps>(({ candidateCount, domainTitle, warmup }) => {+ const { t } = useTranslation('selfLearning');++ return (+ <Block padding={'12px 16px'} variant={'outlined'}>+ <Flexbox horizontal align={'center'} gap={16} justify={'space-between'}>+ <Flexbox gap={2} style={{ minWidth: 0 }}>+ <Flexbox horizontal align={'center'} gap={8}>+ <Icon icon={GraduationCapIcon} size={15} />+ <Text weight={600}>{t('warmup.title', { name: domainTitle })}</Text>+ </Flexbox>+ <Text fontSize={12.5} type={'secondary'}>+ {warmup.phase === 'idle' &&+ (candidateCount ? t('warmup.idle', { count: candidateCount }) : t('warmup.idleNone'))}+ {warmup.phase === 'running' &&+ t('warmup.running', { count: warmup.candidateCount, learned: warmup.learned })}+ {warmup.phase === 'done' && t('warmup.done', { learned: warmup.learned })}+ </Text>+ </Flexbox>++ <Flexbox horizontal align={'center'} gap={10} style={{ flex: 'none' }}>+ {warmup.phase === 'idle' && !!candidateCount && (+ <Button+ icon={HistoryIcon}+ loading={warmup.starting}+ type={'primary'}+ onClick={() => void warmup.start()}+ >+ {t('warmup.start', { count: candidateCount })}+ </Button>+ )}+ {warmup.phase === 'running' && <div className={styles.track} />}+ {warmup.phase === 'done' && (+ <Button onClick={warmup.dismiss}>{t('warmup.dismiss')}</Button>+ )}+ </Flexbox>+ </Flexbox>+ </Block>+ );+});++WarmupCard.displayName = 'ExpertiseWarmupCard';++export default WarmupCard;diff --git a/src/features/SelfLearning/Portrait/styles.ts b/src/features/SelfLearning/Portrait/styles.tsnew file mode 100644index 00000000000..e2b0c09e011--- /dev/null+++ b/src/features/SelfLearning/Portrait/styles.ts@@ -0,0 +1,92 @@+import { createStaticStyles, cssVar } from 'antd-style';++/**+ * 整页只有一种强调色,只标一件事:它做错的地方。+ * 「对 / 已养成 / 用上了」是默认态,不发信号;成长曲线用 success 色,和错点分开。+ */+export const portraitStyles = createStaticStyles(({ css }) => ({+ accent: css`+ color: ${cssVar.colorWarning} !important;+ `,+ bar: css`+ overflow: hidden;+ display: flex;+ flex: none;++ width: 120px;+ height: 5px;+ border-radius: 3px;++ background: ${cssVar.colorFillSecondary};+ `,+ dot: css`+ display: inline-block;++ box-sizing: border-box;+ width: 7px;+ height: 7px;+ border-radius: 50%;+ `,+ dotBad: css`+ background: ${cssVar.colorWarning};+ `,+ dotNone: css`+ border: 1px solid ${cssVar.colorBorder};+ background: transparent;+ `,+ dotOk: css`+ background: ${cssVar.colorTextQuaternary};+ `,+ groupHead: css`+ padding-block: 8px;+ padding-inline: 14px;+ border: 0;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};++ font: inherit;++ background: ${cssVar.colorFillQuaternary};+ `,+ row: css`+ padding-block: 10px;+ padding-inline: 14px;+ border: 0;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};++ font: inherit;++ &:last-child {+ border-block-end: none;+ }++ .teach {+ opacity: 0;+ transition: opacity 0.15s;+ }++ &:hover,+ &:focus-within {+ background: ${cssVar.colorFillQuaternary};++ .teach {+ opacity: 1;+ }+ }+ `,+ segBad: css`+ background: ${cssVar.colorWarning};+ `,+ segOk: css`+ background: ${cssVar.colorTextQuaternary};+ `,+ segShaky: css`+ opacity: 0.55;+ background: ${cssVar.colorWarning};+ `,+ sentence: css`+ font-size: 22px;+ font-weight: 700;+ line-height: 1.4;+ text-wrap: balance;+ `,+}));diff --git a/src/features/SelfLearning/Portrait/useHistoryWarmup.ts b/src/features/SelfLearning/Portrait/useHistoryWarmup.tsnew file mode 100644index 00000000000..b6f2ca36a73--- /dev/null+++ b/src/features/SelfLearning/Portrait/useHistoryWarmup.ts@@ -0,0 +1,125 @@+import { toast } from '@lobehub/ui/base-ui';+import { useCallback, useEffect, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { expertiseService } from '@/services/expertise';++/** 温习结束的判定:连续这么久没有新经验进来就算完(后端不报进度)。 */+const QUIET_MS = 60_000;+/** 无论如何,超过这个时长就收尾,别让页面永远在轮询。 */+const MAX_MS = 10 * 60_000;+export const WARMUP_POLL_MS = 4000;++type WarmupPhase = 'done' | 'idle' | 'running';++interface WarmupRecord {+ baseline: number;+ candidateCount: number;+ lastChangeAt: number;+ lastCount: number;+ startedAt: number;+}++const storageKey = (agentId: string) => `self-learning:warmup:${agentId}`;++const read = (agentId: string): WarmupRecord | null => {+ try {+ const raw = sessionStorage.getItem(storageKey(agentId));+ return raw ? (JSON.parse(raw) as WarmupRecord) : null;+ } catch {+ return null;+ }+};+const write = (agentId: string, rec: WarmupRecord | null) => {+ if (rec) sessionStorage.setItem(storageKey(agentId), JSON.stringify(rec));+ else sessionStorage.removeItem(storageKey(agentId));+};++/**+ * 「让它温习历史对话」的本地状态机。+ * 后端只告诉我们启动了几个对话,不报进度;进度感来自新经验一条条流进来(靠轮询)。+ */+export const useHistoryWarmup = (agentId: string | undefined, learnedTotal: number) => {+ const { t } = useTranslation('selfLearning');+ const [rec, setRec] = useState<WarmupRecord | null>(() => (agentId ? read(agentId) : null));+ const [phase, setPhase] = useState<WarmupPhase>(() => (rec ? 'running' : 'idle'));+ const [starting, setStarting] = useState(false);++ useEffect(() => {+ if (!agentId) return;+ const r = read(agentId);+ setRec(r);+ setPhase(r ? 'running' : 'idle');+ }, [agentId]);++ // Advance the record as lessons arrive; decide when the review is over.+ useEffect(() => {+ if (!agentId || phase !== 'running' || !rec) return;+ const now = Date.now();+ let next = rec;+ if (learnedTotal !== rec.lastCount) {+ next = { ...rec, lastChangeAt: now, lastCount: learnedTotal };+ setRec(next);+ write(agentId, next);+ }+ const quietFor = now - next.lastChangeAt;+ const total = now - next.startedAt;+ if ((quietFor > QUIET_MS && total > QUIET_MS / 2) || total > MAX_MS) {+ setPhase('done');+ write(agentId, null);+ }+ }, [agentId, learnedTotal, phase, rec]);++ // Re-check the quiet timer even when no new data arrives.+ useEffect(() => {+ if (phase !== 'running') return;+ const id = setInterval(() => setRec((r) => (r ? { ...r } : r)), WARMUP_POLL_MS);+ return () => clearInterval(id);+ }, [phase]);++ const start = useCallback(async () => {+ if (!agentId || starting) return;+ setStarting(true);+ try {+ const result = await expertiseService.ingestHistory(agentId);+ if (result.candidateCount === 0) {+ toast.info(t('warmup.idleNone'));+ return;+ }+ const now = Date.now();+ const next: WarmupRecord = {+ baseline: learnedTotal,+ candidateCount: result.candidateCount,+ lastChangeAt: now,+ lastCount: learnedTotal,+ startedAt: now,+ };+ write(agentId, next);+ setRec(next);+ setPhase('running');+ } catch {+ toast.error(t('warmup.failed'));+ } finally {+ setStarting(false);+ }+ }, [agentId, learnedTotal, starting, t]);++ const dismiss = useCallback(() => {+ setPhase('idle');+ setRec(null);+ if (agentId) write(agentId, null);+ }, [agentId]);++ return useMemo(+ () => ({+ candidateCount: rec?.candidateCount ?? 0,+ dismiss,+ learned: rec ? Math.max(0, learnedTotal - rec.baseline) : 0,+ phase,+ refreshInterval: phase === 'running' ? WARMUP_POLL_MS : undefined,+ start,+ starting,+ }),+ [dismiss, learnedTotal, phase, rec, start, starting],+ );+};diff --git a/src/features/SelfLearning/RuleList.tsx b/src/features/SelfLearning/RuleList.tsxdeleted file mode 100644index fe1aa1323a4..00000000000--- a/src/features/SelfLearning/RuleList.tsx+++ /dev/null@@ -1,150 +0,0 @@-'use client';--import { Block, Flexbox, Tag, Text, Tooltip } from '@lobehub/ui';-import { Button, Select } from '@lobehub/ui/base-ui';-import { createStaticStyles } from 'antd-style';-import { ArrowRightIcon } from 'lucide-react';-import { memo, useMemo, useState } from 'react';-import { useTranslation } from 'react-i18next';-import { Link } from 'react-router';--import type { ExpertiseDomainDetail, ExpertiseLessonItem } from '@/services/expertise';--import { groupLessons } from './ruleListHelpers';-import type { ExpertiseTier } from './types';--const styles = createStaticStyles(({ css }) => ({- content: css`- overflow: hidden;- min-width: 0;- `,- code: css`- align-self: center;- width: 40px;- `,- row: css`- display: grid;- grid-template-columns: 40px minmax(0, 1fr) 72px;- column-gap: 8px;- align-items: center;-- padding-block: 7px;- padding-inline: 8px;- border-radius: 8px;-- color: inherit;- text-decoration: none;-- &:hover {- background: var(--ant-color-fill-quaternary);- }- `,- usage: css`- overflow: hidden;- height: 5px;- border-radius: 4px;- background: var(--ant-color-fill-quaternary);- `,-}));--interface RuleListProps {- compact?: boolean;- lessonHref?: (lessonId: string) => string;- lessons: ExpertiseLessonItem[];- stats: ExpertiseDomainDetail['lessonStats'];- viewAllHref?: string;-}--/**- * 骨干经验,按命中降序。- *- * 排序按命中而不是时间:流水账才按时间排,判断系统按「实际用上过多少次」排。- * 「一次都没用上」单独成组且不折叠 —— 它是让人做减法的信号,藏起来就没人做减法了。- */-const RuleList = memo<RuleListProps>(({ compact, lessonHref, lessons, stats, viewAllHref }) => {- const { t } = useTranslation('selfLearning');- const [tierFilter, setTierFilter] = useState<ExpertiseTier | 'all'>('all');-- const grouped = useMemo(() => {- return groupLessons(lessons, compact ? 5 : undefined);- }, [compact, lessons]);-- const visibleGroups = useMemo(() => {- const filtered = tierFilter === 'all' ? grouped : grouped.filter((g) => g.tier === tierFilter);- return filtered;- }, [grouped, tierFilter]);- const maxHits = Math.max(1, ...lessons.map((lesson) => lesson.hitCount));-- return (- <Block gap={10} padding={16} variant={'outlined'}>- <Flexbox horizontal align={'center'} gap={12} justify={'space-between'}>- <Flexbox gap={2}>- <Text fontSize={13} weight={600}>- {t('rules.title')}- </Text>- <Text fontSize={11} type={'secondary'}>- {t('rules.stats', { hits: stats.hits, total: stats.total, unused: stats.unused })}- </Text>- </Flexbox>- {compact && lessons.length > 5 && viewAllHref ? (- <Button href={viewAllHref} type={'text'}>- {t('rules.viewAll', { count: lessons.length })}- <ArrowRightIcon size={14} />- </Button>- ) : !compact ? (- <Select- size={'small'}- style={{ width: 112 }}- value={tierFilter}- variant={'filled'}- options={[- { label: t('rules.filter.all'), value: 'all' },- { label: t('rules.filter.core'), value: 'core' },- { label: t('rules.filter.niche'), value: 'niche' },- { label: t('rules.filter.unused'), value: 'unused' },- ]}- onChange={(value) => value && setTierFilter(value as ExpertiseTier | 'all')}- />- ) : null}- </Flexbox>-- {visibleGroups.map(({ tier, items }) => (- <Flexbox gap={4} key={tier}>- {items.map((lesson) => (- <Link className={styles.row} key={lesson.id} to={lessonHref?.(lesson.id) ?? '#'}>- <Text className={styles.code} fontSize={10.5} type={'secondary'}>- {lesson.code}- </Text>- <Flexbox horizontal align={'center'} className={styles.content} gap={8}>- <Text ellipsis fontSize={12} lineHeight={1.5} style={{ flex: 1 }}>- {lesson.title}- </Text>- {!lesson.canonAnchor && (- <Tag size={'small'} style={{ flex: 'none' }}>- {t('rules.unanchored')}- </Tag>- )}- </Flexbox>- <Tooltip title={t('rules.hitCount', { count: lesson.hitCount })}>- <div className={styles.usage}>- <div- style={{- background: 'var(--ant-color-primary)',- height: '100%',- opacity: lesson.hitCount === 0 ? 0 : 0.65,- width: `${(lesson.hitCount / maxHits) * 100}%`,- }}- />- </div>- </Tooltip>- </Link>- ))}- </Flexbox>- ))}- </Block>- );-});--RuleList.displayName = 'RuleList';--export default RuleList;diff --git a/src/features/SelfLearning/RulesDetail/index.tsx b/src/features/SelfLearning/RulesDetail/index.tsxdeleted file mode 100644index ee31c58b9b3..00000000000--- a/src/features/SelfLearning/RulesDetail/index.tsx+++ /dev/null@@ -1,123 +0,0 @@-'use client';--import { Flexbox, Input, Text } from '@lobehub/ui';-import { createStaticStyles } from 'antd-style';-import { SearchIcon } from 'lucide-react';-import { memo, useEffect, useState } from 'react';-import { useTranslation } from 'react-i18next';-import { Link, useNavigate, useParams } from 'react-router';-import urlJoin from 'url-join';--import AsyncBoundary from '@/components/AsyncBoundary';-import Loading from '@/components/Loading/BrandTextLoading';-import AgentBreadcrumb from '@/features/AgentBreadcrumb';-import NavHeader from '@/features/NavHeader';-import WideScreenContainer from '@/features/WideScreenContainer';-import { useAgentStore } from '@/store/agent';--import { useExpertiseDomain, useExpertiseLessons } from '../hooks';-import RuleList from '../RuleList';--const styles = createStaticStyles(({ css }) => ({- body: css`- overflow-y: auto;- display: flex;- `,-}));--const RulesDetail = memo(() => {- const { t } = useTranslation('selfLearning');- const navigate = useNavigate();- const { domainId } = useParams();- const activeAgentId = useAgentStore((s) => s.activeAgentId);- const { data, error, isLoading, mutate } = useExpertiseDomain(domainId);- const [search, setSearch] = useState('');- const {- data: lessons,- error: lessonsError,- isLoading: lessonsLoading,- mutate: mutateLessons,- } = useExpertiseLessons(domainId, undefined, search.trim() || undefined);- const domainPath =- activeAgentId && domainId- ? urlJoin('/agent', activeAgentId, 'self-learning', domainId)- : undefined;-- useEffect(() => {- if (!isLoading && !error && !data && activeAgentId) {- navigate(urlJoin('/agent', activeAgentId, 'self-learning'), { replace: true });- }- }, [activeAgentId, data, error, isLoading, navigate]);-- return (- <Flexbox height={'100%'} width={'100%'}>- <NavHeader- styles={{ left: { paddingInlineStart: 24 } }}- left={- activeAgentId ? (- <AgentBreadcrumb- agentId={activeAgentId}- title={t('title')}- extraItems={- data?.domain.title- ? [- <Link key={'domain'} to={domainPath ?? '#'}>- {data.domain.title}- </Link>,- t('rules.allTitle'),- ]- : undefined- }- />- ) : null- }- />- <Flexbox className={styles.body} flex={1} width={'100%'}>- <WideScreenContainer>- <AsyncBoundary- data={data}- error={error}- errorVariant={'page'}- isLoading={isLoading}- loading={<Loading debugId={'SelfLearningRules'} />}- onRetry={() => mutate()}- >- {data && (- <Flexbox gap={16} paddingBlock={'26px 64px'}>- <Text fontSize={26} weight={700}>- {t('rules.allTitle')}- </Text>- <Input- allowClear- placeholder={t('rules.searchPlaceholder')}- prefix={<SearchIcon size={14} />}- value={search}- onChange={(event) => setSearch(event.target.value)}- />- <AsyncBoundary- data={lessons}- error={lessonsError}- isLoading={lessonsLoading}- loading={<Loading debugId={'SelfLearningRulesList'} />}- onRetry={() => mutateLessons()}- >- {lessons && (- <RuleList- lessonHref={(lessonId) => urlJoin(domainPath ?? '', 'rules', lessonId)}- lessons={lessons}- stats={data.lessonStats}- />- )}- </AsyncBoundary>- </Flexbox>- )}- </AsyncBoundary>- </WideScreenContainer>- </Flexbox>- </Flexbox>- );-});--RulesDetail.displayName = 'RulesDetail';--export default RulesDetail;diff --git a/src/features/SelfLearning/helpers.test.ts b/src/features/SelfLearning/helpers.test.tsnew file mode 100644index 00000000000..2a2007e98a1--- /dev/null+++ b/src/features/SelfLearning/helpers.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it } from 'vitest';++import {+ earlyPassRate,+ habitTier,+ passRateSeries,+ profileWord,+ recentPassRate,+ zeroViolationStreak,+} from './helpers';++const p = { pass: true };+const v = { pass: false };++describe('habitTier', () => {+ it('treats fewer than two hits as fresh even when one failed', () => {+ expect(habitTier([])).toBe('fresh');+ expect(habitTier([v])).toBe('fresh');+ });++ it('flags two or more recent violations as a recurring problem', () => {+ expect(habitTier([p, v, p, v, v, p])).toBe('recurring');+ });++ it('flags a single recent violation as shaky', () => {+ expect(habitTier([p, p, v, p, p, p])).toBe('shaky');+ });++ it('calls a clean recent record stable', () => {+ expect(habitTier([p, p, p])).toBe('stable');+ });+});++describe('profileWord', () => {+ it('prefers weak over unstable when both are present', () => {+ expect(profileWord({ fresh: 0, recurring: 1, shaky: 2, stable: 5 }, 8)).toBe('weak');+ });+ it('is fresh for an empty layer', () => {+ expect(profileWord({ fresh: 0, recurring: 0, shaky: 0, stable: 0 }, 0)).toBe('fresh');+ });+ it('is stable only when everything is stable', () => {+ expect(profileWord({ fresh: 1, recurring: 0, shaky: 0, stable: 3 }, 4)).toBe('mostlyStable');+ expect(profileWord({ fresh: 0, recurring: 0, shaky: 0, stable: 4 }, 4)).toBe('stable');+ });+});++describe('reliability series', () => {+ const rel = [+ { pass: 2, run: 1, violation: 2 },+ { pass: 0, run: 2, violation: 0 },+ { pass: 3, run: 3, violation: 1 },+ { pass: 4, run: 4, violation: 0 },+ { pass: 5, run: 5, violation: 0 },+ ];++ it('drops runs that judged nothing', () => {+ expect(passRateSeries(rel).map((s) => s.run)).toEqual([1, 3, 4, 5]);+ });++ it('counts the trailing zero-violation streak only across runs that judged something', () => {+ expect(zeroViolationStreak(rel)).toBe(2);+ expect(zeroViolationStreak([{ pass: 0, run: 1, violation: 0 }])).toBe(0);+ });++ it('averages recent and early windows', () => {+ const s = passRateSeries(rel);+ expect(recentPassRate(s, 2)).toBe(1);+ expect(earlyPassRate(s, 2)).toBeCloseTo((0.5 + 0.75) / 2);+ expect(recentPassRate([])).toBeNull();+ });+});diff --git a/src/features/SelfLearning/helpers.ts b/src/features/SelfLearning/helpers.tsnew file mode 100644index 00000000000..c752cc4a262--- /dev/null+++ b/src/features/SelfLearning/helpers.ts@@ -0,0 +1,73 @@+import type { ExpertiseDomainItem, ExpertiseHabit } from '@/services/expertise';++/**+ * 可靠度分档 —— 页面的感知单位是「习惯 + 它靠不靠谱」,不是「学到几条」。+ * 全部由 hits.outcome(pass / violation)折出来;阈值集中在这一处。+ *+ * recurring 老毛病 有规则却反复违反(近期 ≥2 次 violation)+ * shaky 还不稳 近期 1 次 violation+ * fresh 刚学的 命中太少(<2),还没检验+ * stable 已养成 近期全 pass+ */+export type HabitTier = 'fresh' | 'recurring' | 'shaky' | 'stable';++export const TIER_ORDER: HabitTier[] = ['recurring', 'shaky', 'fresh', 'stable'];++export const habitTier = (recent: { pass: boolean }[]): HabitTier => {+ if (recent.length < 2) return 'fresh';+ const bad = recent.filter((r) => !r.pass).length;+ if (bad >= 2) return 'recurring';+ if (bad === 1) return 'shaky';+ return 'stable';+};++export type TierCounts = Record<HabitTier, number>;++export const emptyCounts = (): TierCounts => ({ fresh: 0, recurring: 0, shaky: 0, stable: 0 });++export const countTiers = (habits: ExpertiseHabit[]): TierCounts => {+ const c = emptyCounts();+ for (const h of habits) c[habitTier(h.recent)] += 1;+ return c;+};++/** 一层 / 一个方向的一句话评语,从分档数推出来。 */+export type ProfileWord = 'fresh' | 'mostlyStable' | 'stable' | 'unstable' | 'weak';++export const profileWord = (c: TierCounts, total: number): ProfileWord => {+ if (total === 0) return 'fresh';+ if (c.recurring > 0) return 'weak';+ if (c.shaky > 0) return 'unstable';+ if (c.fresh === total) return 'fresh';+ if (c.stable === total) return 'stable';+ return 'mostlyStable';+};++/** 做对率序列:只有真的命中过习惯的实践才有一个点。 */+export const passRateSeries = (reliability: ExpertiseDomainItem['reliability']) =>+ reliability+ .filter((r) => r.pass + r.violation > 0)+ .map((r) => ({ rate: r.pass / (r.pass + r.violation), run: r.run }));++/** 连续零错的实践次数(从最近往前数)。 */+export const zeroViolationStreak = (reliability: ExpertiseDomainItem['reliability']) => {+ let n = 0;+ for (let i = reliability.length - 1; i >= 0; i--) {+ if (reliability[i].violation === 0 && reliability[i].pass > 0) n += 1;+ else break;+ }+ return n;+};++/** 最近 k 个点的平均做对率;不足 k 个就用全部。 */+export const recentPassRate = (series: { rate: number }[], k = 4) => {+ const tail = series.slice(-k);+ if (tail.length === 0) return null;+ return tail.reduce((a, b) => a + b.rate, 0) / tail.length;+};++export const earlyPassRate = (series: { rate: number }[], k = 4) => {+ const head = series.slice(0, k);+ if (head.length === 0) return null;+ return head.reduce((a, b) => a + b.rate, 0) / head.length;+};diff --git a/src/features/SelfLearning/hooks.ts b/src/features/SelfLearning/hooks.tsindex be3aa46cdb2..79d993df0b8 100644--- a/src/features/SelfLearning/hooks.ts+++ b/src/features/SelfLearning/hooks.ts@@ -1,10 +1,16 @@import { useClientDataSWR } from '@/libs/swr';import { swrKeys } from '@/libs/swr/keys';-import { type ExpertiseMaturity, expertiseService } from '@/services/expertise';+import { expertiseService } from '@/services/expertise';-export const useExpertiseOverview = (agentId?: string) =>- useClientDataSWR(agentId ? swrKeys.expertise.overview(agentId) : null, () =>- expertiseService.listByAgent(agentId!),+/**+ * The portrait query. `refreshInterval` is only set while a history warm-up is running so+ * newly learned habits stream in without a manual reload.+ */+export const useExpertiseOverview = (agentId?: string, refreshInterval?: number) =>+ useClientDataSWR(+ agentId ? swrKeys.expertise.overview(agentId) : null,+ () => expertiseService.listByAgent(agentId!),+ { refreshInterval },);export const useExpertiseDomain = (domainId?: string) =>@@ -12,62 +18,12 @@ export const useExpertiseDomain = (domainId?: string) =>expertiseService.getDomain(domainId!),);-export const useExpertiseLessons = (domainId?: string, layer?: string, search?: string) =>- useClientDataSWR(domainId ? swrKeys.expertise.lessons(domainId, layer, search) : null, () =>- expertiseService.listLessons({ domainId: domainId!, layer, search }),- );-export const useExpertiseLesson = (lessonId?: string) =>useClientDataSWR(lessonId ? swrKeys.expertise.lesson(lessonId) : null, () =>expertiseService.getLesson(lessonId!),);-/** 到达渐近线某个比例所需的实践次数:P(n)=P∞(1−e^(−n/τ)) ⇒ n = −τ·ln(1−r)。 */-export const runsToRatio = (tau: number, ratio: number) => Math.ceil(-tau * Math.log(1 - ratio));--/**- * 曲线形态 —— 图上那四条线的图例就是这四种。- *- * 刻意不只读 plateauKind:它描述拟合出的形状,而「掉头」是规则被退休的结果,- * 在形状上仍然可能被拟合成 saturated。两者一起判断才对得上用户看见的那条线。- */-export type ExpertiseShape = 'flat' | 'rising' | 'declining' | 'stuck' | 'fresh';--export const shapeOf = (- maturity: ExpertiseMaturity,- delta: number,- runCount = 1,-): ExpertiseShape => {- // 一次都没练过 ≠ 练了没学到。前者是还没开始,后者是花了力气没有产出 ——- // 把刚建好的专长标成「练了没学到」,等于开局先给人判个不及格。- if (runCount === 0) return 'fresh';- if (delta < 0) return 'declining';- if (maturity.usable && (maturity.maturity ?? 0) >= 0.9) return 'flat';- if (delta === 0) return 'stuck';- return 'rising';-};--/**- * 把拟合参数展开成外推曲线。- *- * 起点接在今天的真实值上而不是模型值上 —— 否则外推段会从曲线末端跳一下,- * 那个跳变会被读成「数据出错了」。偏差按 τ 指数衰减地并回模型。- */-export const projectSeries = (- pInf: number,- tau: number,- fromRun: number,- fromValue: number,- toRun: number,- steps = 90,-) => {- const model = (n: number) => pInf * (1 - Math.exp(-n / tau));- const offset = fromValue - model(fromRun);- return Array.from({ length: steps }, (_, k) => {- const run = fromRun + (k / (steps - 1)) * (toRun - fromRun);- return {- n: Math.min(pInf, model(run) + offset * Math.exp(-(run - fromRun) / tau)),- run,- };- });-};+export const useHistoryCount = (agentId?: string) =>+ useClientDataSWR(agentId ? swrKeys.expertise.historyCount(agentId) : null, () =>+ expertiseService.countHistory(agentId!),+ );diff --git a/src/features/SelfLearning/index.tsx b/src/features/SelfLearning/index.tsxindex f6b0c464959..1255c93e63b 100644--- a/src/features/SelfLearning/index.tsx+++ b/src/features/SelfLearning/index.tsx@@ -1,17 +1,12 @@'use client';-import { Block, Center, Empty, Flexbox, Icon, Tag, Text } from '@lobehub/ui';+import { Block, Center, Empty, Flexbox, Text } from '@lobehub/ui';import { Button, toast } from '@lobehub/ui/base-ui';-import { createStaticStyles, cssVar, useTheme } from 'antd-style';-import {- ChevronRightIcon,- GraduationCapIcon,- HistoryIcon,- PlusIcon,- SparklesIcon,-} from 'lucide-react';-import { memo, useMemo, useState } from 'react';+import { createStaticStyles } from 'antd-style';+import { GraduationCapIcon, HistoryIcon, PlusIcon } from 'lucide-react';+import { memo, useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';+import { Link, useParams } from 'react-router';import urlJoin from 'url-join';import AsyncBoundary from '@/components/AsyncBoundary';@@ -25,172 +20,186 @@ import { expertiseService } from '@/services/expertise';import { useAgentStore } from '@/store/agent';import { openCreateDomainModal } from './CreateDomainModal';-import Curves from './Curves';-import { type ExpertiseShape, shapeOf, useExpertiseOverview } from './hooks';+import { countTiers, habitTier } from './helpers';+import { useExpertiseOverview, useHistoryCount } from './hooks';+import AnchorCard from './Portrait/AnchorCard';+import DomainList from './Portrait/DomainList';+import GrowthCharts from './Portrait/GrowthCharts';+import HabitList from './Portrait/HabitList';+import LayerProfile from './Portrait/LayerProfile';+import { portraitStyles } from './Portrait/styles';+import TaughtList from './Portrait/TaughtList';+import TeachBox from './Portrait/TeachBox';+import { useHistoryWarmup } from './Portrait/useHistoryWarmup';+import WarmupCard from './Portrait/WarmupCard';const styles = createStaticStyles(({ css }) => ({body: css`overflow-y: auto;display: flex;`,- insight: css`- cursor: pointer;-- padding-block: 14px;- padding-inline: 16px;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: 10px;-- &:hover {- border-color: ${cssVar.colorBorder};- background: ${cssVar.colorFillQuaternary};- }-- &:focus-visible {- outline: 2px solid ${cssVar.colorPrimary};- outline-offset: 2px;- }- `,- row: css`- cursor: pointer;- padding-block: 11px;- padding-inline: 14px;- border-block-end: 1px solid ${cssVar.colorBorderSecondary};-- &:last-child {- border-block-end: none;- }-- &:hover {- background: ${cssVar.colorFillQuaternary};- }-- &:focus-visible {- outline: 2px solid ${cssVar.colorPrimary};- outline-offset: -2px;- }- `,- sentence: css`- font-size: 26px;- font-weight: 700;- line-height: 1.5;- `,- swatch: css`- width: 14px;- height: 3px;- border-radius: 2px;- `,}));-/** 线尾带标签的那几条的配色,按 focus 顺序取。 */-const FOCUS_MAX = 3;--const useShapeLabels = () => {- const { t } = useTranslation('selfLearning');- const theme = useTheme();- return {- declining: { color: theme.colorWarning, label: t('shape.declining') },- fresh: { color: theme.colorTextQuaternary, label: t('shape.fresh') },- flat: { color: theme.colorSuccess, label: t('shape.flat') },- rising: { color: theme.colorInfo, label: t('shape.rising') },- stuck: { color: theme.colorTextTertiary, label: t('shape.stuck') },- } satisfies Record<ExpertiseShape, { color: string; label: string }>;-};-+/**+ * 成长画像 —— 自进化的 L0,也是单方向时的全部。+ *+ * 感知单位是「习惯 + 它靠不靠谱」,不是「学到几条」:判断句、按层画像、习惯分组、做对率曲线+ * 全部由 hits.outcome 折出来。这里没有任何必办事项 —— 教学台,不是审批台。+ * 带 :domainId 进来时就是同一张画像收窄到一个方向。+ */const SelfLearning = memo(() => {const { t } = useTranslation('selfLearning');const navigate = useWorkspaceAwareNavigate();+ const { domainId } = useParams();const activeAgentId = useAgentStore((s) => s.activeAgentId);- const { data, error, isLoading, mutate } = useExpertiseOverview(activeAgentId ?? undefined);- const [hoverId, setHoverId] = useState<string>();- const [isImportingHistory, setIsImportingHistory] = useState(false);- const shapes = useShapeLabels();+ const [teachOpen, setTeachOpen] = useState(false);+ const [teachDomainId, setTeachDomainId] = useState<string>();- const domains = useMemo(() => data?.domains ?? [], [data]);- /** 全都还没练过的时候,坐标轴会退化成一排「第 1 次」—— 那张空网格不如不画。 */- const hasCurves = domains.some((d) => d.series.length > 1);+ // Two-phase: read once to know how many lessons exist, then let the warm-up hook decide the poll.+ const first = useExpertiseOverview(activeAgentId ?? undefined);+ const learnedTotal = useMemo(+ () => first.data?.domains.reduce((a, d) => a + d.lessons.length, 0) ?? 0,+ [first.data],+ );+ const warmup = useHistoryWarmup(activeAgentId ?? undefined, learnedTotal);+ const { data, error, isLoading, mutate } = useExpertiseOverview(+ activeAgentId ?? undefined,+ warmup.refreshInterval,+ );+ const { data: history } = useHistoryCount(activeAgentId ?? undefined);- const openDomain = (domainId: string) => {- if (!activeAgentId) return;- navigate(urlJoin('/agent', activeAgentId, 'self-learning', domainId));- };+ const allDomains = useMemo(() => data?.domains ?? [], [data]);+ const scoped = useMemo(+ () => (domainId ? allDomains.filter((d) => d.id === domainId) : allDomains),+ [allDomains, domainId],+ );+ const single = scoped.length === 1;+ const current: ExpertiseDomainItem | undefined = single ? scoped[0] : undefined;+ const habits = useMemo(+ () => scoped.flatMap((d) => d.lessons.map((l) => ({ ...l, domainId: d.id }))),+ [scoped],+ );+ const runs = scoped.reduce((a, d) => a + d.runCount, 0);+ const domainTitles = useMemo(+ () => Object.fromEntries(allDomains.map((d) => [d.id, d.title])),+ [allDomains],+ );- const importHistory = async () => {- if (!activeAgentId || isImportingHistory) return;- setIsImportingHistory(true);+ /**+ * 判断句永远说一件具体的事 —— 多个方向时也是先挑最值得说的那个方向(老毛病 > 还不稳),+ * 「N 个方向、M 个习惯」这种盘点放到副标题里。+ */+ const sentenceFor = useCallback(+ (d: ExpertiseDomainItem): { detail?: string; headline: string } => {+ const name = d.title;+ const list = d.lessons;+ const c = countTiers(list);+ if (d.runCount === 0) return { headline: t('headline.single.notPracticed', { name }) };+ const recurring = list.find((h) => habitTier(h.recent) === 'recurring');+ if (recurring)+ return {+ detail: t('headline.detail.recurring', {+ title:+ recurring.title.length > 18 ? `${recurring.title.slice(0, 17)}…` : recurring.title,+ }),+ headline: t('headline.single.recurring', { name, runs: d.runCount }),+ };+ if (c.shaky > 0)+ return {+ detail: t('headline.detail.shaky', { count: c.shaky }),+ headline: t('headline.single.shaky', { name, runs: d.runCount }),+ };+ if (c.stable === 0)+ return {+ headline: t('headline.single.fresh', { count: list.length, name, runs: d.runCount }),+ };+ return { headline: t('headline.single.stable', { name, runs: d.runCount }) };+ },+ [t],+ );++ const sentence = useMemo(() => {+ if (scoped.length === 0) return { headline: '' };+ if (single && current) return sentenceFor(current);+ const rank = (d: ExpertiseDomainItem) => {+ const c = countTiers(d.lessons);+ return c.recurring > 0 ? 0 : c.shaky > 0 ? 1 : d.runCount === 0 ? 3 : 2;+ };+ const focus = [...scoped].sort((a, b) => rank(a) - rank(b))[0];+ return rank(focus) <= 1+ ? sentenceFor(focus)+ : { headline: t('headline.multi.ok', { domains: scoped.length }) };+ }, [current, scoped, sentenceFor, single, t]);++ const subline = [+ sentence.detail,+ single+ ? t('headline.subline', { habits: habits.length, runs })+ : t('headline.sublineMulti', { domains: scoped.length, habits: habits.length }),+ ]+ .filter(Boolean)+ .join(' · ');++ // The warm-up card is front and centre only for a direction that has never been practiced.+ const freshDomain = scoped.find((d) => d.runCount === 0 && d.lessons.length === 0);+ const showWarmup = warmup.phase !== 'idle' || !!freshDomain;+ const warmupTitle = freshDomain?.title ?? current?.title ?? scoped[0]?.title ?? '';++ const teach = async (text: string) => {+ const target = teachDomainId ?? current?.id ?? scoped[0]?.id;+ if (!target) return;try {- const result = await expertiseService.ingestHistory(activeAgentId);- if (result.candidateCount === 0) {- toast.info(t('history.empty'));- } else {- toast.success(t('history.started', { count: result.candidateCount }));- }+ await expertiseService.teachLesson({ domainId: target, text });+ toast.success(t('habit.teach.done'));+ setTeachOpen(false);+ void mutate();} catch {- toast.error(t('history.failed'));- } finally {- setIsImportingHistory(false);+ toast.error(t('habit.teach.failed'));}};- /**- * 主图只给三条线上色,其余淡成背景 —— 十个专长十条彩线就是一团糊。- * 挑的是「练得最多」的三个:练得越多,曲线的形状越是结论而不是噪声。- *- * **颜色编码的是形状,不是排名。** 图例说的就是这四种形状,颜色要是按名次发的,- * 图例就成了摆设 —— 一条被标成「掉头 = 能力在退」的黄线其实在涨,比不上色更糟。- */- const { colors, focusIds } = useMemo(() => {- const ids = [...domains]- .sort((a, b) => b.runCount - a.runCount)- .slice(0, FOCUS_MAX)- .map((d) => d.id);- return {- colors: Object.fromEntries(- domains.map((d) => [d.id, shapes[shapeOf(d.maturity, d.delta, d.runCount)].color]),- ),- focusIds: ids,- };- }, [domains, shapes]);-- /** 一句判断句放在最前面 —— 用户先要的是结论,不是图。 */- const headline = useMemo(() => {- if (domains.length === 0) return null;- const withShape = domains.map((d) => ({ d, shape: shapeOf(d.maturity, d.delta, d.runCount) }));- const flat = withShape.find((x) => x.shape === 'flat');- const declining = withShape.find((x) => x.shape === 'declining');- const rising = withShape.find((x) => x.shape === 'rising');- const lead = flat- ? t('headline.flat', { name: flat.d.title })- : rising- ? t('headline.rising', { name: rising.d.title })- : t('headline.none');- const restParts = [- rising && flat ? t('headline.alsoRising', { name: rising.d.title }) : null,- declining ? t('headline.alsoDeclining', { name: declining.d.title }) : null,- ].filter(Boolean);- return { lead, rest: restParts.join('') };- }, [domains, t]);+ const openCreate = () => {+ if (!activeAgentId) return;+ openCreateDomainModal({ agentId: activeAgentId, onCreated: () => void mutate() });+ };return (<Flexbox height={'100%'} width={'100%'}><NavHeader- left={activeAgentId ? <AgentBreadcrumb agentId={activeAgentId} title={t('title')} /> : null}styles={{ left: { paddingInlineStart: 24 } }}- right={+ left={activeAgentId ? (+ <AgentBreadcrumb+ agentId={activeAgentId}+ extraItems={domainId && current ? [current.title] : undefined}+ title={+ domainId && current ? (+ <Link to={urlJoin('/agent', activeAgentId, 'self-learning')}>{t('title')}</Link>+ ) : (+ t('title')+ )+ }+ />+ ) : null+ }+ right={+ activeAgentId && allDomains.length > 0 ? (<Flexbox horizontal gap={8}>- {domains.length > 0 && (- <Button icon={HistoryIcon} loading={isImportingHistory} onClick={importHistory}>- {t('history.entry')}+ <Button icon={PlusIcon} onClick={() => setTeachOpen((v) => !v)}>+ {t('nav.teach')}+ </Button>+ {!showWarmup && (+ <Button+ icon={HistoryIcon}+ loading={warmup.starting}+ type={'text'}+ onClick={() => void warmup.start()}+ >+ {t('nav.warmup')}</Button>)}- <Button- icon={PlusIcon}- onClick={() =>- openCreateDomainModal({ agentId: activeAgentId, onCreated: () => void mutate() })- }- >- {t('create.entry')}+ <Button type={'text'} onClick={openCreate}>+ {t('nav.newDomain')}</Button></Flexbox>) : null@@ -202,7 +211,7 @@ const SelfLearning = memo(() => {data={data}error={error}errorVariant={'page'}- isEmpty={!error && domains.length === 0}+ isEmpty={!error && allDomains.length === 0}isLoading={isLoading}loading={<Loading debugId="SelfLearning" />}empty={@@ -214,18 +223,8 @@ const SelfLearning = memo(() => {style={{ maxWidth: 420 }}title={t('empty.title')}action={- <Button- icon={PlusIcon}- type={'primary'}- onClick={() => {- if (!activeAgentId) return;- openCreateDomainModal({- agentId: activeAgentId,- onCreated: () => void mutate(),- });- }}- >- {t('create.entry')}+ <Button icon={PlusIcon} type={'primary'} onClick={openCreate}>+ {t('nav.newDomain')}</Button>}/>@@ -233,206 +232,86 @@ const SelfLearning = memo(() => {}onRetry={() => mutate()}>- <Flexbox gap={24} paddingBlock={'26px 64px'}>- {headline && (- <Text className={styles.sentence}>- {headline.lead}- {headline.rest && (- <>- <br />- <Text className={styles.sentence} type={'secondary'}>- {headline.rest}- </Text>- </>- )}- </Text>- )}+ <Flexbox gap={20} paddingBlock={'22px 64px'}>+ <Flexbox gap={4}>+ <Text className={portraitStyles.sentence}>{sentence.headline}</Text>+ <Text type={'secondary'}>{subline}</Text>+ </Flexbox>- {!!data?.insights.length && (- <Flexbox gap={10}>- <Flexbox horizontal align={'center'} justify={'space-between'}>- <Flexbox horizontal align={'center'} gap={7}>- <Icon icon={SparklesIcon} size={14} />- <Text fontSize={13} weight={600}>- {t('insights.title')}- </Text>- </Flexbox>- <Text fontSize={12.5} type={'secondary'}>- {t('overview.totals', {- domains: data.totals.domains,- lessons: data.totals.lessons,- })}- </Text>- </Flexbox>- {data.insights.map((it) => (- <Flexbox- as={'button'}- className={styles.insight}- gap={7}- key={it.id}- style={{ background: 'transparent', color: 'inherit', textAlign: 'start' }}- onClick={() => it.domainId && openDomain(it.domainId)}- >- <Text fontSize={11.5} type={'secondary'}>- {it.headline}- </Text>- <Text fontSize={14.5} lineHeight={1.7}>- {it.body}+ {teachOpen && (+ <Block padding={12} variant={'outlined'}>+ <Flexbox gap={8}>+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>+ <Text fontSize={12} type={'secondary'}>+ {t('teachNew.help')}</Text>- {it.actionLabel && (- <Flexbox horizontal>- <Text fontSize={12.5} type={'info'}>- {it.actionLabel} ›+ {!single && (+ <Flexbox horizontal align={'center'} gap={6}>+ <Text fontSize={12} type={'secondary'}>+ {t('teachNew.domain')}</Text>+ {scoped.map((d) => (+ <Button+ key={d.id}+ size={'small'}+ type={+ (teachDomainId ?? scoped[0].id) === d.id ? 'primary' : 'default'+ }+ onClick={() => setTeachDomainId(d.id)}+ >+ {d.title}+ </Button>+ ))}</Flexbox>)}</Flexbox>- ))}- </Flexbox>- )}-- <Flexbox gap={8}>- <Text fontSize={12} type={'secondary'}>- {t('overview.allDomains', { count: domains.length })}- </Text>- <Block padding={0} variant={'outlined'}>- {domains.map((domain) => (- <DomainRow- color={colors[domain.id]}- domain={domain}- key={domain.id}- onHover={setHoverId}- onOpen={openDomain}- />- ))}- </Block>- </Flexbox>-- {hasCurves && (- <Block gap={10} padding={16} variant={'outlined'}>- <Curves- colors={colors}- domains={domains}- focusIds={focusIds}- hoverId={hoverId}- onHover={setHoverId}- onOpen={openDomain}- />- <Flexbox horizontal align={'center'} gap={14} wrap={'wrap'}>- {(['flat', 'rising', 'declining', 'stuck'] as ExpertiseShape[]).map((key) => (- <Flexbox horizontal align={'center'} gap={6} key={key}>- <div className={styles.swatch} style={{ background: shapes[key].color }} />- <Text fontSize={11.5} type={'secondary'}>- {shapes[key].label}- </Text>- </Flexbox>- ))}+ <TeachBox autoFocus placeholder={t('teachNew.placeholder')} onSubmit={teach} /></Flexbox></Block>)}- </Flexbox>- </AsyncBoundary>- </WideScreenContainer>- </Flexbox>- </Flexbox>- );-});-interface DomainRowProps {- color?: string;- domain: ExpertiseDomainItem;- onHover: (id?: string) => void;- onOpen: (id: string) => void;-}+ {showWarmup && (+ <WarmupCard+ candidateCount={history?.candidateCount}+ domainTitle={warmupTitle}+ warmup={warmup}+ />+ )}-/**- * 一行一个专长,右边是它自己的累计柱。- *- * 柱高 = 当时的成熟度,所以**涨到顶就是满了** —— 用新增柱的话得先让人理解- * 「柱子变矮是好事」,那是一层不必要的翻译。- */-const DomainRow = memo<DomainRowProps>(({ domain, color, onOpen, onHover }) => {- const { t } = useTranslation('selfLearning');- const theme = useTheme();- const shape = shapeOf(domain.maturity, domain.delta, domain.runCount);- const ceiling = domain.maturity.usable- ? (domain.maturity.pInf ?? 0)- : Math.max(1, ...domain.series.map((p) => p.n));+ {runs > 0 && <GrowthCharts domains={scoped} />}- return (- <Flexbox- horizontal- align={'center'}- as={'button'}- className={styles.row}- gap={12}- style={{ background: 'transparent', color: 'inherit', textAlign: 'start', width: '100%' }}- onClick={() => onOpen(domain.id)}- onMouseEnter={() => onHover(domain.id)}- onMouseLeave={() => onHover(undefined)}- >- <Flexbox gap={2} style={{ flex: 1, minWidth: 0 }}>- <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>- <Text fontSize={13.5} weight={500}>- {domain.title}- </Text>- <Tag>{domain.runCount === 1 ? t('overview.firstPractice') : t(`shape.tag.${shape}`)}</Tag>- </Flexbox>- <Text fontSize={11} type={'secondary'}>- {t('overview.rowMeta', { lessons: domain.lessonCount, runs: domain.runCount })}- </Text>- </Flexbox>+ {current && <LayerProfile domain={current} />}- {domain.series.length > 1 && (- <svg height={18} style={{ flex: 'none' }} viewBox={'0 0 64 18'} width={64}>- {domain.series.map((p, k) => {- const w = 64 / Math.max(1, domain.series.length);- const h = Math.max((p.n / ceiling) * 16, 1.2);- return (- <rect- fill={color ?? theme.colorTextQuaternary}- height={h}- key={p.run}- opacity={0.5 + (p.n / ceiling) * 0.5}- rx={0.8}- width={Math.max(w - 1.4, 1.4)}- x={k * w}- y={18 - h}- />- );- })}- </svg>- )}+ <TaughtList habits={habits} />- {domain.runCount === 1 ? (- <Text fontSize={12} type={'secondary'}>- {t('overview.trendPending')}- </Text>- ) : (- <>- <Text- fontSize={12.5}- style={{ flex: 'none', textAlign: 'right', width: 68 }}- type={domain.maturity.usable ? undefined : 'secondary'}- weight={600}- >- {domain.maturity.usable ? `${Math.round((domain.maturity.maturity ?? 0) * 100)}%` : '—'}- </Text>- <Text- fontSize={12}- style={{ flex: 'none', textAlign: 'right', width: 42 }}- type={domain.delta > 0 ? 'success' : domain.delta < 0 ? 'warning' : 'secondary'}- >- {domain.delta > 0 ? `+${domain.delta}` : domain.delta < 0 ? domain.delta : '—'}- </Text>- </>- )}- <Icon icon={ChevronRightIcon} size={13} style={{ flex: 'none' }} />+ {habits.length > 0 && activeAgentId && (+ <HabitList+ agentId={activeAgentId}+ domainTitles={single ? undefined : domainTitles}+ habits={habits}+ onChanged={() => void mutate()}+ />+ )}++ {current && <AnchorCard domain={current} />}++ {!single && !domainId && (+ <DomainList+ domains={allDomains}+ onOpen={(id) => {+ if (!activeAgentId) return;+ navigate(urlJoin('/agent', activeAgentId, 'self-learning', id));+ }}+ />+ )}+ </Flexbox>+ </AsyncBoundary>+ </WideScreenContainer>+ </Flexbox></Flexbox>);});-DomainRow.displayName = 'DomainRow';SelfLearning.displayName = 'SelfLearning';export default SelfLearning;diff --git a/src/features/SelfLearning/ruleListHelpers.test.ts b/src/features/SelfLearning/ruleListHelpers.test.tsdeleted file mode 100644index d510b505cfa..00000000000--- a/src/features/SelfLearning/ruleListHelpers.test.ts+++ /dev/null@@ -1,31 +0,0 @@-import { describe, expect, it } from 'vitest';--import type { ExpertiseLessonItem } from '@/services/expertise';--import { groupLessons } from './ruleListHelpers';--const lesson = (id: string, hitCount: number, tier: string): ExpertiseLessonItem =>- ({ hitCount, id, tier }) as ExpertiseLessonItem;--describe('groupLessons', () => {- it('keeps only the five most-used lessons in compact mode', () => {- const groups = groupLessons(- [- lesson('low', 1, 'core'),- lesson('sixth', 5, 'niche'),- lesson('first', 10, 'core'),- lesson('third', 8, 'unused'),- lesson('second', 9, 'niche'),- lesson('fifth', 6, 'core'),- lesson('fourth', 7, 'niche'),- ],- 5,- );-- const ids = groups.flatMap((group) => group.items.map((item) => item.id));- expect(ids).toHaveLength(5);- expect(ids).toEqual(expect.arrayContaining(['first', 'second', 'third', 'fourth', 'fifth']));- expect(ids).not.toContain('sixth');- expect(ids).not.toContain('low');- });-});diff --git a/src/features/SelfLearning/ruleListHelpers.ts b/src/features/SelfLearning/ruleListHelpers.tsdeleted file mode 100644index cb087813a6f..00000000000--- a/src/features/SelfLearning/ruleListHelpers.ts+++ /dev/null@@ -1,19 +0,0 @@-import type { ExpertiseLessonItem } from '@/services/expertise';--import type { ExpertiseTier } from './types';--export const TIER_ORDER: ExpertiseTier[] = ['core', 'niche', 'unused'];--export const groupLessons = (lessons: ExpertiseLessonItem[], limit?: number) => {- const selected = [...lessons].sort((a, b) => b.hitCount - a.hitCount).slice(0, limit);- const map = new Map<ExpertiseTier, ExpertiseLessonItem[]>();-- for (const lesson of selected) {- const tier = lesson.tier as ExpertiseTier;- map.set(tier, [...(map.get(tier) ?? []), lesson]);- }-- return TIER_ORDER.map((tier) => ({ items: map.get(tier) ?? [], tier })).filter(- (group) => group.items.length > 0,- );-};diff --git a/src/features/SelfLearning/types.ts b/src/features/SelfLearning/types.tsdeleted file mode 100644index 6309ce1e389..00000000000--- a/src/features/SelfLearning/types.ts+++ /dev/null@@ -1,2 +0,0 @@-/** 命中梯队。切点在服务端算(见 ExpertiseModel),前端只负责分组呈现。 */-export type ExpertiseTier = 'core' | 'niche' | 'unused';diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 41e41c08743..5f0063a7040 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -924,13 +924,11 @@ export const messengerKeys = {// ---- verify (deliverable judging) ---------------------------------------export const expertiseKeys = {domain: def('expertise:domain', (domainId: string) => ['expertise:domain', domainId]),- lesson: def('expertise:lesson', (lessonId: string) => ['expertise:lesson', lessonId]),- lessons: def('expertise:lessons', (domainId: string, layer?: string, search?: string) => [- 'expertise:lessons',- domainId,- layer ?? '',- search ?? '',+ historyCount: def('expertise:historyCount', (agentId: string) => [+ 'expertise:historyCount',+ agentId,]),+ lesson: def('expertise:lesson', (lessonId: string) => ['expertise:lesson', lessonId]),overview: def('expertise:overview', (agentId: string) => ['expertise:overview', agentId]),};diff --git a/src/routes/(main)/agent/self-learning/[domainId]/index.tsx b/src/routes/(main)/agent/self-learning/[domainId]/index.tsxindex ea09ad51649..caea22b32fb 100644--- a/src/routes/(main)/agent/self-learning/[domainId]/index.tsx+++ b/src/routes/(main)/agent/self-learning/[domainId]/index.tsx@@ -3,11 +3,12 @@import { memo, Suspense } from 'react';import Loading from '@/components/Loading/BrandTextLoading';-import DomainDetail from '@/features/SelfLearning/Detail';+import SelfLearning from '@/features/SelfLearning';+/** The domain page is the same growth portrait, scoped to one direction via :domainId. */const AgentSelfLearningDomainPage = memo(() => (<Suspense fallback={<Loading debugId="SelfLearningDomain" />}>- <DomainDetail />+ <SelfLearning /></Suspense>));diff --git a/src/routes/(main)/agent/self-learning/[domainId]/rules/index.tsx b/src/routes/(main)/agent/self-learning/[domainId]/rules/index.tsxindex 17fa287301a..5947b30b222 100644--- a/src/routes/(main)/agent/self-learning/[domainId]/rules/index.tsx+++ b/src/routes/(main)/agent/self-learning/[domainId]/rules/index.tsx@@ -3,11 +3,12 @@import { memo, Suspense } from 'react';import Loading from '@/components/Loading/BrandTextLoading';-import RulesDetail from '@/features/SelfLearning/RulesDetail';+import SelfLearning from '@/features/SelfLearning';+/** Kept for deep links: the habit list now lives on the domain portrait itself. */const AgentSelfLearningRulesPage = memo(() => (<Suspense fallback={<Loading debugId={'SelfLearningRules'} />}>- <RulesDetail />+ <SelfLearning /></Suspense>));diff --git a/src/services/expertise.ts b/src/services/expertise.tsindex a9c6f3576a5..c864cd8a3e6 100644--- a/src/services/expertise.ts+++ b/src/services/expertise.ts@@ -4,35 +4,44 @@ export type ExpertiseOverview = Awaited<ReturnType<typeof lambdaClient.expertise.listByAgent.query>>;export type ExpertiseDomainItem = ExpertiseOverview['domains'][number];-export type ExpertiseInsightItem = ExpertiseOverview['insights'][number];+export type ExpertiseHabit = ExpertiseDomainItem['lessons'][number];export type ExpertiseDomainDetail = NonNullable<Awaited<ReturnType<typeof lambdaClient.expertise.getDomain.query>>>;-export type ExpertiseLessonItem = Awaited<- ReturnType<typeof lambdaClient.expertise.listLessons.query>->[number];export type ExpertiseLessonDetail = NonNullable<Awaited<ReturnType<typeof lambdaClient.expertise.getLesson.query>>>;-/** Maturity is a union: usable results expose a value, while unusable results expose a reason. */-export type ExpertiseMaturity = ExpertiseDomainItem['maturity'];+export type ExpertiseDomainDraft = Awaited<+ ReturnType<typeof lambdaClient.expertise.draftDomain.mutate>+>;class ExpertiseService {listByAgent = async (agentId: string) => lambdaClient.expertise.listByAgent.query({ agentId });getDomain = async (domainId: string) => lambdaClient.expertise.getDomain.query({ domainId });- listLessons = async (params: { domainId: string; layer?: string; search?: string }) =>- lambdaClient.expertise.listLessons.query(params);-getLesson = async (lessonId: string) => lambdaClient.expertise.getLesson.query({ lessonId });- createDomain = async (params: { agentId: string; brief: string }) =>+ draftDomain = async (params: { agentId: string; brief: string }) =>+ lambdaClient.expertise.draftDomain.mutate(params);++ createDomain = async (params: ExpertiseDomainDraft & { agentId: string; brief: string }) =>lambdaClient.expertise.createDomain.mutate(params);+ countHistory = async (agentId: string) => lambdaClient.expertise.countHistory.query({ agentId });+ingestHistory = async (agentId: string) =>lambdaClient.expertise.ingestHistory.mutate({ agentId });+ teachLesson = async (params: { domainId: string; text: string }) =>+ lambdaClient.expertise.teachLesson.mutate(params);++ reviseLesson = async (params: { lessonId: string; text: string }) =>+ lambdaClient.expertise.reviseLesson.mutate(params);++ retireLesson = async (lessonId: string) =>+ lambdaClient.expertise.retireLesson.mutate({ lessonId });+dismissInsight = async (insightId: string, reason?: string) =>lambdaClient.expertise.dismissInsight.mutate({ insightId, reason });}