🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(goal): keep a batch's plan as a user skill and learn from each gate break (#20833)
Arvin Xu9c8ca7fc07f5
diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.tsindex 1cf9d91ffb5..3fd4c617365 100644--- a/apps/server/src/routers/lambda/index.ts+++ b/apps/server/src/routers/lambda/index.ts@@ -104,6 +104,7 @@ import { usageRouter } from './usage';import { userRouter } from './user';import { userMemoriesRouter } from './userMemories';import { userMemoryRouter } from './userMemory';+import { userSkillRouter } from './userSkill';import { verifyRouter } from './verify';import { videoRouter } from './video';import { webBrowsingRouter } from './webBrowsing';@@ -197,6 +198,7 @@ export const lambdaRouter = router({user: userRouter,userMemories: userMemoriesRouter,userMemory: userMemoryRouter,+ userSkill: userSkillRouter,verify: verifyRouter,video: videoRouter,webBrowsing: webBrowsingRouter,diff --git a/apps/server/src/routers/lambda/userSkill.ts b/apps/server/src/routers/lambda/userSkill.tsnew file mode 100644index 00000000000..2a1492353bb--- /dev/null+++ b/apps/server/src/routers/lambda/userSkill.ts@@ -0,0 +1,29 @@+import { z } from 'zod';++import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';+import { router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { UserSkillService } from '@/server/services/userSkill';++/** The user's own skill library: skills that belong to the user, not to one agent. */+const userSkillProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {+ const { ctx } = opts;+ return opts.next({+ ctx: {+ userSkillService: new UserSkillService(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ ),+ },+ });+});++export const userSkillRouter = router({+ /** One skill with every version it went through, oldest first. */+ get: userSkillProcedure+ .input(z.object({ id: z.string() }))+ .query(async ({ ctx, input }) => (await ctx.userSkillService.getSkill(input.id)) ?? null),+});++export type UserSkillRouter = typeof userSkillRouter;diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.tsindex 11a4d89c55d..eee18d2540b 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.ts@@ -18,6 +18,8 @@ const {mockGetComposioManifests,mockGetLobehubSkillManifests,mockHasDocuments,+ mockListUserSkillCatalog,+ mockLoadUserSkills,mockMessageCreate,mockPluginQuery,mockSkillFindAll,@@ -35,6 +37,8 @@ const {mockGetComposioManifests: vi.fn().mockResolvedValue([]),mockGetLobehubSkillManifests: vi.fn().mockResolvedValue([]),mockHasDocuments: vi.fn().mockResolvedValue(false),+ mockListUserSkillCatalog: vi.fn().mockResolvedValue([]),+ mockLoadUserSkills: vi.fn().mockResolvedValue([]),mockMessageCreate: vi.fn(),mockPluginQuery: vi.fn().mockResolvedValue([]),mockSkillFindAll: vi.fn().mockResolvedValue({ data: [], total: 0 }),@@ -99,6 +103,12 @@ vi.mock('@/server/services/agentDocuments', () => ({}),}));+vi.mock('@/server/services/userSkill', () => ({+ UserSkillService: vi.fn().mockImplementation(function () {+ return { listCatalog: mockListUserSkillCatalog, loadRuntimeSkills: mockLoadUserSkills };+ }),+}));+vi.mock('@/database/models/plugin', () => ({PluginModel: vi.fn().mockImplementation(function () {return { query: mockPluginQuery };@@ -255,6 +265,30 @@ describe('AiAgentService.execAgent - pinned skill content injection', () => {);mockGetAgentSkills.mockResolvedValue([]);mockHasDocuments.mockResolvedValue(false);+ const planSkill = {+ description: 'How each unit is done',+ generated: true,+ identifier: 'user-skills:goal-plan-x',+ name: 'user-skills:goal-plan-x',+ title: 'Plan',+ };+ const handMade = {+ description: 'My review checklist',+ generated: false,+ identifier: 'user-skills:review',+ name: 'user-skills:review',+ title: 'Review',+ };+ // The catalog query honours `includeGenerated`, as the real one does.+ mockListUserSkillCatalog.mockImplementation(async (options?: { includeGenerated?: boolean }) =>+ options?.includeGenerated === false ? [handMade] : [planSkill, handMade],+ );+ // Only bodies the run asks for come back, as the real loader does.+ mockLoadUserSkills.mockImplementation(async (ids: string[]) =>+ ids.includes(planSkill.identifier)+ ? [{ ...planSkill, body: 'PLAN BODY', content: 'PLAN BODY + FILES' }]+ : [],+ );service = new AiAgentService({} as any, 'test-user-id');});@@ -405,6 +439,49 @@ describe('AiAgentService.execAgent - pinned skill content injection', () => {expect(mockSkillFindByIds).toHaveBeenCalledWith([]);});+ it('lists the user skill library to every run, content-less until a run names a skill', async () => {+ mockGetAgentConfig.mockResolvedValue({+ chatConfig: {},+ id: 'agent-1',+ model: 'gpt-4',+ plugins: [],+ provider: 'openai',+ systemRole: 'You are a helper',+ });++ await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);++ // A hand-made skill is listed, without its body.+ expect(skillById('user-skills:review')).toBeDefined();+ expect(skillById('user-skills:review')?.content).toBeUndefined();+ // A batch's generated plan skill is not listed to an unrelated run, and the+ // catalog is asked to leave generated skills out.+ expect(skillById('user-skills:goal-plan-x')).toBeUndefined();+ expect(mockListUserSkillCatalog).toHaveBeenCalledWith({ includeGenerated: false });+ // Listing the library reads no body: none was asked for.+ expect(mockLoadUserSkills.mock.calls[0][0]).not.toContain('user-skills:goal-plan-x');+ });++ it('injects a user skill the run names in its plugins, as a goal batch unit does', async () => {+ mockGetAgentConfig.mockResolvedValue({+ chatConfig: {},+ id: 'agent-1',+ model: 'gpt-4',+ plugins: [],+ provider: 'openai',+ systemRole: 'You are a helper',+ });++ await service.execAgent({+ additionalPluginIds: ['lobe-task', 'user-skills:goal-plan-x'],+ agentId: 'agent-1',+ prompt: 'Hello',+ } as any);++ expect(operationSkillSetArg()?.enabledPluginIds).toContain('user-skills:goal-plan-x');+ expect(skillById('user-skills:goal-plan-x')?.content).toBe('PLAN BODY + FILES');+ });+it('appends the resource tree to a pinned skill body, mirroring activateSkill', async () => {mockGetAgentConfig.mockResolvedValue({chatConfig: {},diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 20fdec54177..9adc99b6500 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -1430,6 +1430,7 @@ export class AiAgentService {// instead of on the send path.const initRequest = buildOperationInitRequest({additionalPluginIds,+ taskId: operationTaskId,agentSlug,approvalOwnerAssistantId,approvedToolEntries,diff --git a/apps/server/src/services/aiAgent/pipeline/operationInit.ts b/apps/server/src/services/aiAgent/pipeline/operationInit.tsindex f81a3861f8d..c9e4b3dba65 100644--- a/apps/server/src/services/aiAgent/pipeline/operationInit.ts+++ b/apps/server/src/services/aiAgent/pipeline/operationInit.ts@@ -71,6 +71,8 @@ export interface OperationInitRequest {resumeToolResult?: InternalExecAgentParams['resumeToolResult'];runAttachments: RunAttachments;selectedToolIds?: string[];+ /** The Task this run executes, when it runs inside the Task system. */+ taskId?: string;topicBoundDeviceId?: string | null;}@@ -213,6 +215,7 @@ export const runOperationInit = async (operationId: request.operationId,runAttachments: request.runAttachments,runFromHistory: request.resumeFromHistory,+ taskId: request.taskId,throwIfExecutionAborted: deps.throwIfExecutionAborted,},),diff --git a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts b/apps/server/src/services/aiAgent/pipeline/operationPrep.tsindex dc9f03e900c..654c49a4a47 100644--- a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts+++ b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts@@ -21,6 +21,7 @@ import { DeviceModel } from '@/database/models/device';import { ExpertiseModel } from '@/database/models/expertise';import { GoalGraphModel } from '@/database/models/goalGraph';import type { MessageModel } from '@/database/models/message';+import { TaskModel } from '@/database/models/task';import type { TopicModel } from '@/database/models/topic';import { UserPersonaModel } from '@/database/models/userMemory/persona';import { isDeviceCapablePlan } from '@/helpers/executionTarget';@@ -29,6 +30,7 @@ import type { AgentDocumentsService } from '@/server/services/agentDocuments';import { deviceGateway } from '@/server/services/deviceGateway';import { FileService } from '@/server/services/file';import { redisService } from '@/server/services/redis';+import { readTaskSkillIds, UserSkillService } from '@/server/services/userSkill';import { afterUnscoped } from '@/server/utils/scheduleAfterResponse';import { pruneRegeneratedBranch } from '../pruneRegeneratedBranch';@@ -196,6 +198,8 @@ export interface OperationPrepInput {operationId: string;runAttachments: RunAttachments;runFromHistory: boolean;+ /** The Task this run executes; the skills it names are trusted for this run. */+ taskId?: string;throwIfExecutionAborted: (stage: string) => Promise<void>;}@@ -840,6 +844,58 @@ export const prepareOperation = async (name: skill.name,}));+ // The user's own skill library: listed to every run, and injected up front+ // when the agent pins one or the run names it in its plugins — a goal+ // batch's unit runs name the batch's plan skill that way.+ // The catalog carries no bodies; only the pinned / run-named skills read+ // theirs, so a library that grows with every batch stays cheap to list.+ // A workspace-public agent never reads its caller's private skills — every+ // user skill is private — so its runs see none of them.+ const userSkills = new UserSkillService(+ deps.db,+ deps.userId,+ deps.workspaceId,+ deps.workspaceId ? await deps.agentModel.getAgentVisibility(resolvedAgentId) : undefined,+ );+ // The skills the run's own Task names (a goal batch's plan) load even+ // through a public agent — and only those; nothing the model or a picker+ // supplies widens that.+ const taskSkillIds = input.taskId+ ? readTaskSkillIds(+ (await new TaskModel(deps.db, deps.userId, deps.workspaceId).findById(input.taskId))+ ?.config,+ )+ : [];+ const namedUserSkills = await userSkills.loadRuntimeSkills(+ [...pinnedSkillIds, ...(agentPlugins ?? []), ...taskSkillIds],+ { trustedGenerated: taskSkillIds },+ );+ // Skills the system generated for one job (a goal batch's plan) are not+ // listed to every run — one accumulates per batch, so the query leaves them+ // out — only joined where the run pins or names them, as that batch's units+ // do. Those come in with their bodies.+ const listed = await userSkills.listCatalog({ includeGenerated: false });+ const listedIds = new Set(listed.map((skill) => skill.identifier));+ const namedContent = new Map(+ namedUserSkills.map((skill) => [skill.identifier, skill.content] as const),+ );+ const userSkillMetas = [+ ...listed.map((skill) => ({+ content: namedContent.get(skill.identifier),+ description: skill.description,+ identifier: skill.identifier,+ name: skill.name,+ })),+ ...namedUserSkills+ .filter((skill) => !listedIds.has(skill.identifier))+ .map((skill) => ({+ content: skill.content,+ description: skill.description,+ identifier: skill.identifier,+ name: skill.name,+ })),+ ];+const projectMetas = workspaceInit.workspace.skills.map((s) => ({description: s.description ?? '',identifier: `${s.scope === 'device' ? 'device' : 'project'}:${s.name}`,@@ -884,7 +940,7 @@ export const prepareOperation = async (// load time.const shareAllowedSkillIds = shareGate? filterSkillsByShareGate(- [...projectMetas, ...dbMetas, ...agentSkillMetas, ...builtinMetas].map(+ [...projectMetas, ...dbMetas, ...agentSkillMetas, ...userSkillMetas, ...builtinMetas].map((skill) => skill.identifier,),shareGate,@@ -911,7 +967,7 @@ export const prepareOperation = async (// command execution is gated at the device tool layer.operationSkillSet = assembleSkillPool({- agentSkills: agentSkillMetas,+ agentSkills: [...agentSkillMetas, ...userSkillMetas],builtin: builtinMetas,db: dbMetas,project: projectMetas,diff --git a/apps/server/src/services/goal/batchPlanSkill.test.ts b/apps/server/src/services/goal/batchPlanSkill.test.tsnew file mode 100644index 00000000000..67d7f2dcfd1--- /dev/null+++ b/apps/server/src/services/goal/batchPlanSkill.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from 'vitest';++import { learnedRulesClause, planSkillName, planUnitBrief } from './batchPlanSkill';++describe('planSkillName', () => {+ it('turns a node id into a short, valid skill name', () => {+ expect(planSkillName('13b47c2a-5b56-4e8d-b53a-41e2b418d58a')).toBe('goal-plan-13b47c2a');+ expect(planSkillName('gnd_AbC123xyz')).toBe('goal-plan-gndabc12');+ });+});++describe('planUnitBrief', () => {+ it('names the plan skill and keeps the plan at dispatch as a fallback', () => {+ const brief = planUnitBrief('Unit 3', {+ outline: 'Swap the store for replica',+ skill: { id: 'docs_1', name: 'goal-plan-x' },+ });+ expect(brief).toContain('Unit: Unit 3');+ expect(brief).toContain('`user-skills:goal-plan-x`');+ // A run that cannot load the skill still has the plan to work from.+ expect(brief).toContain('If that skill is not loaded in this run');+ expect(brief).toContain('Swap the store for replica');+ });++ it('copies the plan when the batch has no skill', () => {+ expect(planUnitBrief('Unit 3', { outline: 'Swap the store' })).toBe(+ 'Swap the store\n\nUnit: Unit 3',+ );+ });+});++describe('learnedRulesClause', () => {+ it('carries every rule in full, not its truncated title', () => {+ const rule = `${'先确认 generation_batches 已在 replica 建表,'.repeat(4)}最后补一条回滚脚本`;+ const clause = learnedRulesClause([{ rule, title: `${rule.slice(0, 79)}…` }]);+ expect(clause).toContain(`- ${rule}`);+ expect(clause).toContain('最后补一条回滚脚本');+ });++ it('falls back to the title for a rule recorded before the full text was kept', () => {+ expect(learnedRulesClause([{ title: 'Seed SSR first' }])).toContain('- Seed SSR first');+ expect(learnedRulesClause([])).toBeUndefined();+ });+});diff --git a/apps/server/src/services/goal/batchPlanSkill.ts b/apps/server/src/services/goal/batchPlanSkill.tsnew file mode 100644index 00000000000..7bc6b3c2dca--- /dev/null+++ b/apps/server/src/services/goal/batchPlanSkill.ts@@ -0,0 +1,242 @@+import { buildUserSkillIdentifier } from '@lobechat/const';+import type { LobeChatDatabase } from '@lobechat/database';+import type { GoalRolloutLearning, GoalRolloutPlanSkill } from '@lobechat/types';+import { and, eq, isNull, sql } from 'drizzle-orm';++import { type ExpertiseCarrier, ExpertiseModel } from '@/database/models/expertise';+import { expertiseBindings, expertiseDomains } from '@/database/schemas';++import { UserSkillService } from '../userSkill';++/**+ * A batch's execution plan lives as a skill in the user's own library, not as+ * text copied into every unit: units load the skill, each Template revision is+ * one of its versions, and the skill outlives the goal for reuse elsewhere.+ *+ * A gate break also teaches the batch. Its guidance becomes a rule in the+ * batch's expertise domain, and every later unit's acceptance adds it as a+ * clause it must meet (see `learnedRulesClause`) on top of the unit's own+ * contract — so a break revises the plan, the executor and the verifier+ * together.+ */++const MAX_TITLE = 80;+const MAX_DESCRIPTION = 240;++const oneLine = (text: string, max: number) => {+ const line = text.replaceAll(/\s+/g, ' ').trim();+ return line.length > max ? `${line.slice(0, max - 1)}…` : line;+};++/**+ * A short skill name for a batch: `goal-plan-` and the first characters of its+ * id. The library keeps names unique, suffixing a clash.+ */+export const planSkillName = (batchNodeId: string) =>+ `goal-plan-${batchNodeId+ .toLowerCase()+ .replaceAll(/[^\da-z]+/g, '')+ .slice(0, 8)}`;++export const planSkillIdentifier = (skill: GoalRolloutPlanSkill) =>+ buildUserSkillIdentifier(skill.name);++/**+ * A unit's brief. With a plan skill the brief names the skill — the run loads+ * its latest version — and still carries the plan as it stood at dispatch, so a+ * run that could not load the skill (deleted, or a failed read) works from the+ * plan rather than from nothing.+ */+export const planUnitBrief = (+ title: string,+ plan: { outline?: string; skill?: GoalRolloutPlanSkill },+): string =>+ plan.skill+ ? [+ `Unit: ${title}`,+ `Do this unit by the batch's execution plan, the skill \`${planSkillIdentifier(plan.skill)}\` loaded for this run. Follow its latest version.`,+ plan.outline &&+ `If that skill is not loaded in this run, follow the plan as it stood at dispatch:\n\n${plan.outline}`,+ ]+ .filter(Boolean)+ .join('\n\n')+ : [plan.outline, `Unit: ${title}`].filter(Boolean).join('\n\n');++/**+ * The clause a batch unit's acceptance adds for what the batch learned: every+ * rule in full (the title is a truncated label), on top of the unit's own+ * contract.+ */+export const learnedRulesClause = (+ learnings: readonly Pick<GoalRolloutLearning, 'rule' | 'title'>[],+): string | undefined =>+ learnings.length+ ? `Rules this batch learned from its release gate (each must also hold):\n${learnings+ .map((learning) => `- ${(learning.rule ?? learning.title).trim()}`)+ .join('\n')}`+ : undefined;++/** The one expertise domain a carrier keeps for every goal batch it runs. */+export const BATCH_DOMAIN_TITLE = 'Goal batch rules';+/** Its gate question — with the title, how a generated batch domain is recognized. */+const BATCH_DOMAIN_FILTER = 'Doing or verifying a unit of a goal batch.';++export class BatchPlanSkillService {+ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,+ ) {}++ /** Writes v1 of a batch's plan as a user skill. */+ create = async (params: {+ batchNodeId: string;+ goalId: string;+ goalTitle: string;+ plan: string;+ }): Promise<GoalRolloutPlanSkill> => {+ const skill = await new UserSkillService(this.db, this.userId, this.workspaceId).createSkill({+ body: params.plan,+ description: oneLine(+ `How each unit of "${params.goalTitle}" is done. Revised whenever the batch's release gate sends it back.`,+ MAX_DESCRIPTION,+ ),+ name: planSkillName(params.batchNodeId),+ origin: { batchNodeId: params.batchNodeId, goalId: params.goalId, revision: 1 },+ title: oneLine(params.goalTitle, MAX_TITLE),+ });+ return { id: skill.id, name: skill.name };+ };++ /**+ * Moves a batch that predates plan skills into one: the plan's earlier+ * versions, oldest first, become the skill's versions, so version N still+ * reads as round N.+ */+ adopt = async (params: {+ batchNodeId: string;+ goalId: string;+ goalTitle: string;+ versions: string[];+ }): Promise<GoalRolloutPlanSkill | undefined> => {+ const [first, ...rest] = params.versions.filter((text) => text.trim());+ if (!first) return undefined;+ const skill = await this.create({ ...params, plan: first });+ for (const [index, plan] of rest.entries()) {+ await this.revise(skill, { goalId: params.goalId, plan, revision: index + 2 });+ }+ return skill;+ };++ /** Writes the plan's next version; returns its number. */+ revise = async (+ skill: GoalRolloutPlanSkill,+ params: { goalId: string; guidance?: string; plan: string; revision: number },+ ) =>+ new UserSkillService(this.db, this.userId, this.workspaceId).reviseSkill(skill.id, {+ body: params.plan,+ note: params.guidance,+ origin: { goalId: params.goalId, revision: params.revision },+ });++ /**+ * Teaches the batch what a break found: a rule in its expertise domain+ * (opened on the first break). Nothing is compiled from it: later units'+ * acceptance carries the rule as a clause of its requirement.+ */+ /**+ * The batch domain bound to exactly this carrier, if it has one. Not the+ * carrier's inherited list: an agent also sees the owner's domains, and a+ * rule meant for one agent must not land in a domain every agent inherits.+ */+ private findBatchDomain = async (carrier: ExpertiseCarrier) => {+ const binding =+ carrier.type === 'agent'+ ? eq(expertiseBindings.agentId, carrier.id)+ : carrier.type === 'project'+ ? eq(expertiseBindings.projectId, carrier.id)+ : and(+ this.workspaceId+ ? eq(expertiseBindings.boundWorkspaceId, this.workspaceId)+ : eq(expertiseBindings.boundUserId, this.userId),+ isNull(expertiseBindings.agentId),+ isNull(expertiseBindings.projectId),+ );+ const [row] = await this.db+ .select({ id: expertiseDomains.id })+ .from(expertiseBindings)+ .innerJoin(expertiseDomains, eq(expertiseDomains.id, expertiseBindings.domainId))+ .where(+ and(+ binding,+ eq(expertiseDomains.userId, this.userId),+ eq(expertiseDomains.title, BATCH_DOMAIN_TITLE),+ eq(expertiseDomains.domainFilter, BATCH_DOMAIN_FILTER),+ ),+ )+ .limit(1);+ return row?.id;+ };++ learn = async (params: {+ /** Where the domain is mounted: the executing agent, else the user. */+ carrier: ExpertiseCarrier;+ domainId?: string;+ /** What the gate found, in words. */+ found: string;+ goalTitle: string;+ guidance: string;+ planSkill?: GoalRolloutPlanSkill;+ revision: number;+ }): Promise<{ domainId: string; learning: GoalRolloutLearning } | undefined> => {+ const expertise = new ExpertiseModel(this.db, this.userId, this.workspaceId);+ // Two goals on the same carrier can break at once, each under only its own+ // goal lock: serialize finding-or-creating the carrier's domain, so the+ // second sees the first's instead of creating another. Held until the+ // enclosing transaction ends.+ const carrierKey =+ params.carrier.type === 'user'+ ? `user:${this.workspaceId ?? this.userId}`+ : `${params.carrier.type}:${params.carrier.id}`;+ await this.db.execute(+ sql`SELECT pg_advisory_xact_lock(hashtext(${`goal-batch-domain:${carrierKey}`}))`,+ );+ // One domain per carrier for every batch it runs, not one per batch: each+ // run's expertise snapshot loads every domain its agent carries, so a+ // domain per batch would grow that load with every batch ever run.+ const domainId =+ params.domainId ??+ (await this.findBatchDomain(params.carrier)) ??+ (await expertise.createDomain({+ brief: 'What the release gates of goal batches have learned.',+ carrier: params.carrier,+ domainFilter: BATCH_DOMAIN_FILTER,+ title: BATCH_DOMAIN_TITLE,+ }));+ const scope = params.planSkill+ ? `the batch plan ${planSkillIdentifier(params.planSkill)}`+ : `the batch of "${params.goalTitle}"`;++ const title = oneLine(params.guidance, MAX_TITLE);+ const lesson = await expertise.createRule({+ compilability: 'compilable',+ domainId,+ enforcement: 'block',+ how: params.guidance,+ title,+ why: `The release gate of round ${params.revision} of ${scope} sent it back: ${params.found}`,+ });+ if (!lesson) return undefined;++ return {+ domainId,+ learning: {+ lessonCode: lesson.code,+ lessonId: lesson.id,+ revision: params.revision,+ rule: params.guidance,+ title,+ },+ };+ };+}diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.tsindex c1804ac257d..206458ca178 100644--- a/apps/server/src/services/goal/index.test.ts+++ b/apps/server/src/services/goal/index.test.ts@@ -14,6 +14,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { getTestDB } from '@/database/core/getTestDB';import { AcceptanceModel } from '@/database/models/acceptance';import { AgentOperationModel } from '@/database/models/agentOperation';+import { ExpertiseModel } from '@/database/models/expertise';import { GoalModel } from '@/database/models/goal';import { GoalGraphModel } from '@/database/models/goalGraph';import { MetricModel } from '@/database/models/metric';@@ -33,6 +34,7 @@ import {goals,metricPoints,metrics,+ projects,tasks,taskTopics,topics,@@ -46,6 +48,7 @@ import { AiAgentService } from '@/server/services/aiAgent';import { deviceGateway } from '../deviceGateway';import { TaskService } from '../task';import { TaskRunnerService } from '../taskRunner';+import { UserSkillService } from '../userSkill';import { VerifyPlanGeneratorService } from '../verify/planGenerator';import { GoalCriteriaGeneratorService } from './criteriaGenerator';import {@@ -83,6 +86,8 @@ afterEach(async () => {await serverDB.delete(metrics);await serverDB.delete(acceptances);await serverDB.delete(agentOperations);+ // A project holds its coordinator agent; it goes before the agents do.+ await serverDB.delete(projects);await serverDB.delete(taskTopics);await serverDB.delete(topics);await serverDB.delete(tasks);@@ -2335,8 +2340,11 @@ describe('GoalService', () => {// probes — later waves only read `policy.spec.recipeOutline`, so a note kept// only on the Template would never reach the tasks meant to test it.expect(after.goal.config!.rollout!.spec?.recipeOutline).toContain('补上 SSR 播种这一步');+ // The re-opened probes load the plan skill, whose latest version carries it.const openedProbe = after.nodes.find((n) => next.probeNodeIds.includes(n.id))!;- expect(openedProbe.description).toContain('补上 SSR 播种这一步');+ expect(openedProbe.description).toContain(`user-skills:${next.planSkill!.name}`);+ const skill = await new UserSkillService(serverDB, userId).getSkill(next.planSkill!.id);+ expect(skill?.content).toContain('补上 SSR 播种这一步');});it('materializes and answers a pattern-break gate on a full rollout', async () => {@@ -2702,6 +2710,57 @@ describe('GoalService', () => {expect((await pendingBreak(service, graph.goal.id)).id).toBe(decision.id);});+ it('fails the fork, keeping the question open, when the old rules cannot be retired', async () => {+ decompose();+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ config: { rollout: { minHomogeneousUnits: 5, trigger: 'canary' } },+ title: 'Fork with a stuck rule',+ });+ await service.tick(graph.goal.id);+ const openGate = (+ service as unknown as {+ openPatternBreakGate: (+ g: unknown,+ message: string,+ effects: unknown[],+ ) => Promise<unknown>;+ }+ ).openPatternBreakGate.bind(service);+ await openGate(await service.graph(graph.goal.id), 'Unit 1 did not pass', []);+ let decision = await pendingBreak(service, graph.goal.id);+ await service.decide(graph.goal.id, decision.id, 'revise', '补上冷启动这一步');+ await openGate(await service.graph(graph.goal.id), 'Unit 1 did not pass', []);+ decision = await pendingBreak(service, graph.goal.id);++ // Retiring the old rule fails.+ await serverDB.execute(sql`+ CREATE OR REPLACE FUNCTION fail_lesson_retire() RETURNS trigger AS $$+ BEGIN+ IF NEW.status = 'retired' THEN RAISE EXCEPTION 'retire failed'; END IF;+ RETURN NEW;+ END $$ LANGUAGE plpgsql+ `);+ await serverDB.execute(sql`+ CREATE TRIGGER fail_lesson_retire BEFORE UPDATE ON expertise_lessons+ FOR EACH ROW EXECUTE FUNCTION fail_lesson_retire()+ `);+ try {+ await expect(+ service.decide(graph.goal.id, decision.id, 'new_class', '按新类型处理'),+ ).rejects.toThrow();+ } finally {+ await serverDB.execute(sql`DROP TRIGGER IF EXISTS fail_lesson_retire ON expertise_lessons`);+ await serverDB.execute(sql`DROP FUNCTION IF EXISTS fail_lesson_retire()`);+ }++ // The batch still knows the rule (so retiring it can be retried), and the+ // question is still there to answer.+ const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ expect(state.learnings).toHaveLength(1);+ expect((await pendingBreak(service, graph.goal.id)).id).toBe(decision.id);+ });+it('forks a new class from the original outline, not the revised plan', async () => {decompose();const service = new GoalService(serverDB, userId);@@ -2723,6 +2782,7 @@ describe('GoalService', () => {await openGate(await service.graph(graph.goal.id), 'Unit 1 did not pass', []);let decision = await pendingBreak(service, graph.goal.id);await service.decide(graph.goal.id, decision.id, 'revise', '补上冷启动这一步');+ const [taught] = (await service.graph(graph.goal.id)).goal.config!.rolloutState!.learnings!;await openGate(await service.graph(graph.goal.id), 'Unit 1 did not pass', []);decision = await pendingBreak(service, graph.goal.id);await service.decide(graph.goal.id, decision.id, 'new_class', '按新类型处理');@@ -2734,6 +2794,13 @@ describe('GoalService', () => {// The v2 correction belongs to the old class; the fork starts clean.expect(plan.description).not.toContain('补上冷启动这一步');expect(plan.description).toContain('把 store 换成 replica 支撑的实现');+ // …and so do its rules: the old class's learnings do not bind the new one.+ expect(after.goal.config!.rolloutState!.learnings).toBeUndefined();+ expect(after.goal.config!.rolloutState!.learningDomainId).toBeUndefined();+ // The old class's rule also stops reaching runs: retired in the shared domain.+ expect((await new ExpertiseModel(serverDB, userId).findLesson(taught.lessonId))?.status).toBe(+ 'retired',+ );});});@@ -3017,6 +3084,320 @@ describe('GoalService', () => {// The new canary is a fresh round: the old wave's retired member no longer// counts against its gate (it would re-open the same break at once).expect(next.massNodeIds).toBeUndefined();++ // The plan lives as a skill in the user's library: v1 at decomposition,+ // v2 when the break revised it — each version kept whole.+ const planSkill = next.planSkill!;+ expect(planSkill.name).toMatch(/^goal-plan-/);+ const skill = await new UserSkillService(serverDB, userId).getSkill(planSkill.id);+ expect(skill?.versions.map((version) => version.version)).toEqual([1, 2]);+ expect(skill?.content).toContain('### v2\n补上冷启动这一步');+ expect(skill?.versions[0].content).not.toContain('### v2');+ // A re-opened unit names the skill, which carries every later revision…+ expect(reopened.description).toContain(`user-skills:${planSkill.name}`);+ // …and still carries the revised plan, in case the skill does not load.+ expect(reopened.description).toContain('### v2\n补上冷启动这一步');++ // The break taught the batch: a rule in its expertise, which later units'+ // acceptance adds as a clause — no standalone criterion that nothing mounts.+ expect(next.learnings).toMatchObject([{ revision: 1, title: '补上冷启动这一步' }]);+ const [learning] = next.learnings!;+ expect(learning.criterionId).toBeUndefined();+ const lesson = await new ExpertiseModel(serverDB, userId).findLesson(learning.lessonId);+ expect(lesson).toMatchObject({+ compilability: 'compilable',+ compiledCriterionId: null,+ enforcement: 'block',+ });++ // A unit dispatched after the break loads the skill on every run and is+ // judged by what the batch learned.+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ await service.tick(graph.goal.id);+ const dispatched = (await service.graph(graph.goal.id)).nodes.find(+ (node) => next.probeNodeIds.includes(node.id) && node.taskId,+ )!;+ const task = await new TaskModel(serverDB, userId).findById(dispatched.taskId!);+ expect(task?.config).toMatchObject({ skills: [`user-skills:${planSkill.name}`] });+ const acceptance = await new AcceptanceModel(serverDB, userId).findBySubject(+ 'task',+ dispatched.taskId!,+ );+ // The learned rule is added to the unit's own contract, not substituted for+ // it: configured criteria would make the verifier check only those.+ expect(acceptance?.config?.verifyCriteriaIds).toBeUndefined();+ expect(acceptance?.requirement).toContain(dispatched.title);+ expect(acceptance?.requirement).toContain('- 补上冷启动这一步');+ });++ it('falls back to copying the revised plan when the skill revision does not land', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: '把 50 个同构的 store 迁移到 replica',+ rollout: {+ recipeOutline: '把 store 换成 replica 支撑的实现',+ repeatable: true,+ unitCount: 50,+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),+ variants: [],+ },+ tasks: Array.from({ length: 5 }, (_, i) => ({+ dependsOn: [],+ instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,+ title: `Unit ${i + 1}`,+ })),+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Migrate stores' });+ await service.tick(graph.goal.id);++ const graphModel = new GoalGraphModel(serverDB, userId);+ const goalModel = new GoalModel(serverDB, userId);+ const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ // The plan skill was deleted from the library in the meantime.+ await serverDB.delete(documents).where(eq(documents.id, state.planSkill!.id));++ const decision = await graphModel.createDecision(graph.goal.id, state.assayNodeId!, {+ authority: 'user',+ options: [{ id: 'revise', label: 'Revise' }],+ question: 'Batch gate blocked',+ requestedUserId: userId,+ });+ await graphModel.updateNodeStatus(graph.goal.id, state.assayNodeId!, 'waiting');+ await goalModel.updateRolloutState(graph.goal.id, { ...state, phase: 'pattern_break' });+ await serverDB.update(goals).set({ status: 'paused' }).where(eq(goals.id, graph.goal.id));++ await service.decide(graph.goal.id, decision!.id, 'revise', '补上冷启动这一步');++ // The new round does not point units at a skill that lacks the revision:+ // they carry the revised plan themselves.+ const after = await service.graph(graph.goal.id);+ const next = after.goal.config!.rolloutState!;+ expect(next.planSkill).toBeUndefined();+ const probe = after.nodes.find((node) => node.id === next.probeNodeIds[0])!;+ expect(probe.description).toContain('### v2\n补上冷启动这一步');+ expect(probe.description).not.toContain('user-skills:');+ });++ it('mounts what a break taught on the agent that runs the units, even in a project', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: '把 50 个同构的 store 迁移到 replica',+ rollout: {+ recipeOutline: '把 store 换成 replica 支撑的实现',+ repeatable: true,+ unitCount: 50,+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),+ variants: [],+ },+ tasks: Array.from({ length: 5 }, (_, i) => ({+ dependsOn: [],+ instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,+ title: `Unit ${i + 1}`,+ })),+ });+ await serverDB.insert(agents).values([{ id: 'agt_batch', slug: 'agt-batch', userId }]);+ await serverDB.insert(projects).values({+ coordinatorAgentId: 'agt_batch',+ id: 'proj_batch',+ identifier: 'BAT',+ name: 'Batch project',+ userId,+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ agentId: 'agt_batch',+ projectId: 'proj_batch',+ title: 'Migrate stores in a project',+ });+ await service.tick(graph.goal.id);++ const graphModel = new GoalGraphModel(serverDB, userId);+ const goalModel = new GoalModel(serverDB, userId);+ const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ const decision = await graphModel.createDecision(graph.goal.id, state.assayNodeId!, {+ authority: 'user',+ options: [{ id: 'revise', label: 'Revise' }],+ question: 'Batch gate blocked',+ requestedUserId: userId,+ });+ await graphModel.updateNodeStatus(graph.goal.id, state.assayNodeId!, 'waiting');+ await goalModel.updateRolloutState(graph.goal.id, { ...state, phase: 'pattern_break' });+ await serverDB.update(goals).set({ status: 'paused' }).where(eq(goals.id, graph.goal.id));+ await service.decide(graph.goal.id, decision!.id, 'revise', '补上冷启动这一步');++ // A run's expertise snapshot reads the executing agent's domains, so that+ // is where the batch's rules must live for its units to receive them.+ const next = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ const domains = await new ExpertiseModel(serverDB, userId).listDomainsForAgent('agt_batch');+ expect(domains.map(({ domain }) => domain.id)).toContain(next.learningDomainId);+ });++ it('learns into one shared domain per agent, through the executor fallback', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: '把 50 个同构的 store 迁移到 replica',+ rollout: {+ recipeOutline: '把 store 换成 replica 支撑的实现',+ repeatable: true,+ unitCount: 50,+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),+ variants: [],+ },+ tasks: Array.from({ length: 5 }, (_, i) => ({+ dependsOn: [],+ instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,+ title: `Unit ${i + 1}`,+ })),+ });+ await serverDB.insert(agents).values([+ { id: 'agt_goal_main', slug: 'agt-goal-main', userId },+ { id: 'agt_gone_exec', slug: 'agt-gone-exec', userId },+ ]);+ const service = new GoalService(serverDB, userId);+ const graphModel = new GoalGraphModel(serverDB, userId);+ const goalModel = new GoalModel(serverDB, userId);+ const breakAndRevise = async (title: string) => {+ const graph = await service.create({+ agentId: 'agt_goal_main',+ config: { taskAgentId: 'agt_gone_exec' },+ title,+ });+ await service.tick(graph.goal.id);+ const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ const decision = await graphModel.createDecision(graph.goal.id, state.assayNodeId!, {+ authority: 'user',+ options: [{ id: 'revise', label: 'Revise' }],+ question: 'Batch gate blocked',+ requestedUserId: userId,+ });+ await graphModel.updateNodeStatus(graph.goal.id, state.assayNodeId!, 'waiting');+ await goalModel.updateRolloutState(graph.goal.id, { ...state, phase: 'pattern_break' });+ await serverDB.update(goals).set({ status: 'paused' }).where(eq(goals.id, graph.goal.id));+ // The dedicated executor is deleted before the break is answered.+ await serverDB.delete(agents).where(eq(agents.id, 'agt_gone_exec'));+ await service.decide(graph.goal.id, decision!.id, 'revise', '补上冷启动这一步');+ return (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ };++ // The owner already keeps a batch domain of their own, inherited by every+ // agent: an agent's rule must not land there.+ const ownerDomainId = await new ExpertiseModel(serverDB, userId).createDomain({+ brief: 'What the release gates of goal batches have learned.',+ carrier: { type: 'user' },+ domainFilter: 'Doing or verifying a unit of a goal batch.',+ title: 'Goal batch rules',+ });++ const first = await breakAndRevise('First batch');+ expect(first.learningDomainId).not.toBe(ownerDomainId);+ // Learned despite the stale executor: mounted on the goal agent it falls back to.+ expect(first.learnings).toHaveLength(1);+ const expertise = new ExpertiseModel(serverDB, userId);+ expect(+ (await expertise.listDomainsForAgent('agt_goal_main')).map(({ domain }) => domain.id),+ ).toContain(first.learningDomainId);++ // A second batch on the same agent reuses that domain instead of adding one.+ await serverDB+ .insert(agents)+ .values({ id: 'agt_gone_exec', slug: 'agt-gone-exec', userId })+ .onConflictDoNothing();+ const second = await breakAndRevise('Second batch');+ expect(second.learningDomainId).toBe(first.learningDomainId);+ });++ it('creates one batch domain when two goals on an agent learn at the same time', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: '把 50 个同构的 store 迁移到 replica',+ rollout: {+ recipeOutline: '把 store 换成 replica 支撑的实现',+ repeatable: true,+ unitCount: 50,+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),+ variants: [],+ },+ tasks: Array.from({ length: 5 }, (_, i) => ({+ dependsOn: [],+ instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,+ title: `Unit ${i + 1}`,+ })),+ });+ await serverDB.insert(agents).values([{ id: 'agt_shared', slug: 'agt-shared', userId }]);+ const service = new GoalService(serverDB, userId);+ const graphModel = new GoalGraphModel(serverDB, userId);+ const goalModel = new GoalModel(serverDB, userId);+ const openBreak = async (title: string) => {+ const graph = await service.create({ agentId: 'agt_shared', title });+ await service.tick(graph.goal.id);+ const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ const decision = await graphModel.createDecision(graph.goal.id, state.assayNodeId!, {+ authority: 'user',+ options: [{ id: 'revise', label: 'Revise' }],+ question: 'Batch gate blocked',+ requestedUserId: userId,+ });+ await graphModel.updateNodeStatus(graph.goal.id, state.assayNodeId!, 'waiting');+ await goalModel.updateRolloutState(graph.goal.id, { ...state, phase: 'pattern_break' });+ await serverDB.update(goals).set({ status: 'paused' }).where(eq(goals.id, graph.goal.id));+ return { decisionId: decision!.id, goalId: graph.goal.id };+ };+ const a = await openBreak('Batch A');+ const b = await openBreak('Batch B');++ // Both first breaks are answered at once.+ await Promise.all([+ service.decide(a.goalId, a.decisionId, 'revise', '补上冷启动这一步'),+ service.decide(b.goalId, b.decisionId, 'revise', '补上 SSR 播种这一步'),+ ]);++ const domainOf = async (goalId: string) =>+ (await service.graph(goalId)).goal.config!.rolloutState!.learningDomainId;+ expect(await domainOf(a.goalId)).toBe(await domainOf(b.goalId));+ const bound = await new ExpertiseModel(serverDB, userId).listDomainsForAgent('agt_shared');+ expect(bound.filter(({ domain }) => domain.title === 'Goal batch rules')).toHaveLength(1);+ });++ it('moves a batch from before plan skills into one at its next revision', async () => {+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({+ problemStatement: '把 50 个同构的 store 迁移到 replica',+ rollout: {+ recipeOutline: '把 store 换成 replica 支撑的实现',+ repeatable: true,+ unitCount: 50,+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),+ variants: [],+ },+ tasks: Array.from({ length: 5 }, (_, i) => ({+ dependsOn: [],+ instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,+ title: `Unit ${i + 1}`,+ })),+ });+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Migrate stores' });+ await service.tick(graph.goal.id);++ const graphModel = new GoalGraphModel(serverDB, userId);+ const goalModel = new GoalModel(serverDB, userId);+ const { planSkill: _written, ...legacy } = (await service.graph(graph.goal.id)).goal.config!+ .rolloutState!;+ const decision = await graphModel.createDecision(graph.goal.id, legacy.assayNodeId!, {+ authority: 'user',+ options: [{ description: '修订配方', id: 'revise', label: '修订配方并重探' }],+ question: 'Batch gate blocked',+ requestedUserId: userId,+ });+ await graphModel.updateNodeStatus(graph.goal.id, legacy.assayNodeId!, 'waiting');+ await goalModel.updateRolloutState(graph.goal.id, { ...legacy, phase: 'pattern_break' });+ await serverDB.update(goals).set({ status: 'paused' }).where(eq(goals.id, graph.goal.id));++ await service.decide(graph.goal.id, decision!.id, 'revise', '补上 SSR 播种这一步');++ const next = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;+ const skill = await new UserSkillService(serverDB, userId).getSkill(next.planSkill!.id);+ // The plan's earlier version becomes v1 and the revision v2, so version N+ // still reads as round N.+ expect(skill?.versions.map((version) => version.version)).toEqual([1, 2]);+ expect(skill?.versions[0].content).toContain('把 store 换成 replica 支撑的实现');+ expect(skill?.versions[1].content).toContain('### v2\n补上 SSR 播种这一步');});it('persists the planned recipe when the caller already chose a canary rollout', async () => {diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.tsindex 85ce4a373bf..97b396d33da 100644--- a/apps/server/src/services/goal/index.ts+++ b/apps/server/src/services/goal/index.ts@@ -48,6 +48,7 @@ import { sql } from 'drizzle-orm';import { AgentModel } from '@/database/models/agent';import { AgentOperationModel } from '@/database/models/agentOperation';+import { type ExpertiseCarrier, ExpertiseModel } from '@/database/models/expertise';import { GoalModel } from '@/database/models/goal';import { GoalGraphModel } from '@/database/models/goalGraph';import { MetricModel } from '@/database/models/metric';@@ -66,6 +67,7 @@ import { TaskService } from '../task';import { TaskRunnerService } from '../taskRunner';import { AcceptanceService } from '../verify/acceptanceService';import { VerifyPlanGeneratorService } from '../verify/planGenerator';+import { BatchPlanSkillService, learnedRulesClause, planSkillIdentifier } from './batchPlanSkill';import { GoalCriteriaGeneratorService, type GoalDecompositionDraft } from './criteriaGenerator';import {compareMetric,@@ -2790,9 +2792,18 @@ export class GoalService {].filter(Boolean).join('\n\n');+ // A batch unit loads the batch's plan skill on every run, and is judged+ // by every rule the batch's breaks have taught.+ const rollout = graph.goal.config?.rolloutState;+ const batchUnit = frontier.kind === 'task' && this.isBatchMember(graph, frontier.id);+ const planSkill = batchUnit ? rollout?.planSkill : undefined;+ const learnedRules = batchUnit ? (rollout?.learnings ?? []) : [];task = await this.taskService.createTask({assigneeAgentId: await this.resolveTaskAssignee(graph.goal),- config: { checkpoint: { topic: { after: false } } },+ config: {+ checkpoint: { topic: { after: false } },+ ...(planSkill ? { skills: [planSkillIdentifier(planSkill)] } : {}),+ },description: description?.slice(0, TASK_DESCRIPTION_MAX_LENGTH),instruction: this.buildTaskInstruction(graph, frontier.title, description),name: frontier.title,@@ -2811,11 +2822,16 @@ export class GoalService {enabled: true,...(goalCriteriaIds?.length ? { verifyCriteriaIds: goalCriteriaIds } : {}),},- requirement: this.buildTaskAcceptanceRequirement(- graph,- frontier.title,- frontier.description,- ),+ // A batch unit is judged on its own delivery and, on top of it, on every+ // rule the batch's breaks taught. Configured criteria would replace the+ // prose contract (the verify plan materializes only them), so the+ // rules join the requirement instead of standing in for it.+ requirement: [+ this.buildTaskAcceptanceRequirement(graph, frontier.title, frontier.description),+ learnedRulesClause(learnedRules),+ ]+ .filter(Boolean)+ .join('\n\n'),});acceptanceId = acceptance.id;const bound = await this.coordinatorGraph.bindTask(goalId, frontier.id, task.id);@@ -3804,6 +3820,12 @@ export class GoalService {canarySize,goalId,goalModel,+ planSkillOwner: {+ db: tx,+ goalTitle: graph.goal.title,+ userId: this.userId,+ workspaceId: this.workspaceId,+ },policy: existingRollout,problemId: currentProblem.id,probes: draftTasks,@@ -4009,7 +4031,7 @@ export class GoalService {goalId,state.batchNodeId,title,- policy.spec?.recipeOutline,+ { outline: policy.spec?.recipeOutline, skill: state.planSkill },policy.unitBriefs?.[title],);if (nodeId) {@@ -4248,6 +4270,16 @@ export class GoalService {// goal row's lock, so a failure part-way leaves the question open to answer// again rather than consumed beside half a round; and a second answer// racing this one finds the break already restarted.+ // What a break teaches is mounted on the agent that runs the batch's units+ // (a run's expertise snapshot reads the executing agent's domains, not the+ // project's) — resolved like the task assignee, so a deleted executor falls+ // back to the goal agent rather than a binding that cannot be written. Read+ // before the transaction, which holds the goal row.+ const carrierAgentId = await this.resolveTaskAssignee(graph.goal);+ const carrier: ExpertiseCarrier = carrierAgentId+ ? { id: carrierAgentId, type: 'agent' }+ : { type: 'user' };+const committed = await this.db.transaction(async (tx) => {const goalModel = new GoalModel(tx, this.userId, this.workspaceId);const current = (await goalModel.lockById(goalId))?.config?.rolloutState;@@ -4275,6 +4307,88 @@ export class GoalService {await writer.createEdge(goalId, template.id, state.templateNodeId, 'revises');}+ // The plan skill takes the revision as its next version, and the break+ // teaches the batch: a rule the executor reads, compiled into a criterion+ // the verifier judges every later unit by. A fork starts a new class of+ // units — its correction describes them, it is not a rule for the old+ // ones. Each runs in its own savepoint: a failure there costs the skill+ // version or the lesson, never the round the answer opens.+ const inSavepoint = <T>(label: string, run: (db: typeof tx) => Promise<T>) =>+ tx.transaction(run).catch((error) => {+ log('restartRolloutLoop: %s failed: %O', label, error);+ return undefined;+ });+ let planSkill = state.planSkill;+ if (planSkill && revisedOutline) {+ const skill = planSkill;+ const version = await inSavepoint('plan skill revision', (db) =>+ new BatchPlanSkillService(db, this.userId, this.workspaceId).revise(skill, {+ goalId,+ guidance: correction || undefined,+ plan: revisedOutline,+ revision,+ }),+ );+ // The revision did not land (the skill was deleted, or the write+ // failed): units must not load a skill that lacks it. They fall back to+ // copying the revised plan, and the batch drops the stale reference.+ if (version === undefined) planSkill = undefined;+ } else if (!planSkill && revisedOutline) {+ // A batch from before plans were skills moves into one now, carrying+ // every earlier version of its plan.+ const inBatch = new Set(+ graph.edges+ .filter((edge) => edge.kind === 'contains' && edge.sourceNodeId === batchId)+ .map((edge) => edge.targetNodeId),+ );+ const earlier = graph.nodes+ .filter(+ (node) =>+ node.kind === 'finding' &&+ node.title === GOAL_BATCH_TEMPLATE_TITLE &&+ inBatch.has(node.id),+ )+ .sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime())+ .map((node) => node.description?.trim() ?? '');+ planSkill = await inSavepoint('plan skill adoption', (db) =>+ new BatchPlanSkillService(db, this.userId, this.workspaceId).adopt({+ batchNodeId: batchId,+ goalId,+ goalTitle: graph.goal.title,+ versions: [...earlier, revisedOutline],+ }),+ );+ }+ // A fork starts a new class: the old class's rules must stop reaching+ // runs too, not only its acceptance — retire them in the shared domain,+ // where the executor's expertise would otherwise keep injecting them.+ // Not in a forgiving savepoint: the fork clears the batch's record of+ // them below, so a failure here fails the fork (the question stays open+ // to answer again) rather than leaving them active and forgotten.+ if (optionId === 'new_class' && state.learnings?.length) {+ const expertise = new ExpertiseModel(tx, this.userId, this.workspaceId);+ for (const learning of state.learnings) await expertise.retireLesson(learning.lessonId);+ }+ const learned =+ correction && optionId !== 'new_class'+ ? await inSavepoint('break learning', (db) =>+ new BatchPlanSkillService(db, this.userId, this.workspaceId).learn({+ carrier,+ domainId: state.learningDomainId,+ // What the gate found: this round's latest hold, in its own words.+ found:+ state.gateLog?.findLast(+ (entry) =>+ entry.outcome === 'blocked' && entry.revision === state.templateRevision,+ )?.message ?? 'the release gate held',+ goalTitle: graph.goal.title,+ guidance: correction,+ planSkill,+ revision: state.templateRevision,+ }),+ )+ : undefined;+// 2. Retire the members that broke or were superseded, never delete them —// the new round is `derived_from` them (decision #4). A member an earlier// round already re-opened is history, not a unit to re-open again.@@ -4368,7 +4482,7 @@ export class GoalService {goalId,batchId,unit.title,- revisedOutline || baseOutline,+ { outline: revisedOutline || baseOutline, skill: planSkill },unit.brief,);if (!nodeId) continue;@@ -4402,6 +4516,17 @@ export class GoalService {phase: 'probe',probeNodeIds: probeIds,releasedCount: opened.length,+ // A fork starts a new class of units: the old class's rules do not+ // bind it, so its learnings start empty.+ learningDomainId:+ optionId === 'new_class' ? undefined : (learned?.domainId ?? state.learningDomainId),+ learnings:+ optionId === 'new_class'+ ? undefined+ : learned+ ? [...(state.learnings ?? []), learned.learning]+ : state.learnings,+ planSkill,templateNodeId: template?.id ?? state.templateNodeId,templateRevision: state.templateRevision + 1,unitTitles: remaining,diff --git a/apps/server/src/services/goal/manager.ts b/apps/server/src/services/goal/manager.tsindex 37520914128..677115d388a 100644--- a/apps/server/src/services/goal/manager.ts+++ b/apps/server/src/services/goal/manager.ts@@ -1687,6 +1687,12 @@ export class GoalManagerService {createdByAgentId: agentId,goalId: goal.id,goalModel: new GoalModel(db, this.userId, this.workspaceId),+ planSkillOwner: {+ db,+ goalTitle: goal.title,+ userId: this.userId,+ workspaceId: this.workspaceId,+ },policy,problemId: problemId!,probes: plan.tasks.map((task) => ({ instruction: task.description, title: task.title })),diff --git a/apps/server/src/services/goal/rolloutBatch.ts b/apps/server/src/services/goal/rolloutBatch.tsindex f357ec92eb4..81ef5231e7d 100644--- a/apps/server/src/services/goal/rolloutBatch.ts+++ b/apps/server/src/services/goal/rolloutBatch.ts@@ -4,11 +4,22 @@ import {GOAL_BATCH_TITLE,ROLLOUT_WAVE_SIZE_DEFAULT,} from '@lobechat/const/goal';-import type { GoalRolloutPolicy, GoalRolloutState, GoalRolloutVariantAxis } from '@lobechat/types';+import type { LobeChatDatabase } from '@lobechat/database';+import type {+ GoalRolloutPlanSkill,+ GoalRolloutPolicy,+ GoalRolloutState,+ GoalRolloutVariantAxis,+} from '@lobechat/types';+import debug from 'debug';import type { GoalModel } from '@/database/models/goal';import type { GoalGraphModel } from '@/database/models/goalGraph';+import { BatchPlanSkillService, planUnitBrief } from './batchPlanSkill';++const log = debug('lobe-server:goal-rollout');+/** Upper bound on a batch roster; a planner that over-lists cannot swamp the config. */export const MAX_ROLLOUT_ROSTER = 60;@@ -63,22 +74,19 @@ export const carriedUnitBrief = (node: { description?: string | null; title: str* recipe applied to this unit — the probes carry the full first-hand brief, the* units promoted later reuse what the Template already proved. A unit that came* with its own notes (an agent-declared roster), or a re-opened unit, also keeps- * that brief.+ * that brief. With a plan skill the brief names the skill rather than copying+ * the plan.*/export const createRecipeUnitTask = async (writer: GoalGraphModel,goalId: string,batchNodeId: string,title: string,- recipeOutline?: string,+ plan: { outline?: string; skill?: GoalRolloutPlanSkill },unitBrief?: string,): Promise<string | undefined> => {const node = await writer.createNode(goalId, {- description: [- recipeOutline,- `Unit: ${title}`,- unitBrief && `${UNIT_BRIEF_HEADING}\n${unitBrief}`,- ]+ description: [planUnitBrief(title, plan), unitBrief && `${UNIT_BRIEF_HEADING}\n${unitBrief}`].filter(Boolean).join('\n\n'),kind: 'task',@@ -102,6 +110,18 @@ export interface MaterializeRolloutBatchInput {createdByAgentId?: string;goalId: string;goalModel: GoalModel;+ /**+ * Where the batch's plan is written as a skill in the user's library (v1 of+ * it): the caller's transaction and owner. Units then load the skill rather+ * than copy the plan; without it, or when writing fails, they carry the+ * outline as before.+ */+ planSkillOwner?: {+ db: LobeChatDatabase;+ goalTitle: string;+ userId: string;+ workspaceId?: string;+ };/** The policy the caller already chose (trigger, sizes); persisted underneath. */policy?: GoalRolloutPolicy;probes: RolloutBatchProbe[];@@ -131,6 +151,7 @@ export const materializeRolloutBatch = async ({createdByAgentId,goalId,goalModel,+ planSkillOwner,policy,problemId,probes,@@ -160,6 +181,30 @@ export const materializeRolloutBatch = async ({});if (!template) throw new Error('Failed to create a batch template');+ // The plan as a skill in the user's library: units load it rather than copy+ // it, and it stays reusable after the goal. A savepoint keeps a failed write+ // from aborting the batch; the units then fall back to the copied outline.+ let planSkill: GoalRolloutPlanSkill | undefined;+ const outline = recipeOutline?.trim();+ if (outline && planSkillOwner) {+ try {+ planSkill = await planSkillOwner.db.transaction((savepoint) =>+ new BatchPlanSkillService(+ savepoint as unknown as LobeChatDatabase,+ planSkillOwner.userId,+ planSkillOwner.workspaceId,+ ).create({+ batchNodeId: batch.id,+ goalId,+ goalTitle: planSkillOwner.goalTitle,+ plan: outline,+ }),+ );+ } catch (error) {+ log('rollout batch: plan skill not written: %O', error);+ }+ }+// The Assay is the gate. It is a `decision` node so a failed gate has// somewhere to hang the human question, but it carries NO pending// decision yet — opening one now would park the goal before a probe ran.@@ -218,7 +263,7 @@ export const materializeRolloutBatch = async ({goalId,batch.id,title,- recipeOutline,+ { outline: recipeOutline, skill: planSkill },unitBriefs?.[title],);if (nodeId) massNodeIds.push(nodeId);@@ -230,6 +275,7 @@ export const materializeRolloutBatch = async ({assayNodeId: assay?.id,massNodeIds: massNodeIds.length ? massNodeIds : undefined,phase: trigger === 'full' ? 'mass' : 'probe',+ planSkill,probeNodeIds: probeIds,releasedCount: probeIds.length + massNodeIds.length,templateNodeId: template.id,diff --git a/apps/server/src/services/goal/start.ts b/apps/server/src/services/goal/start.tsindex b5eea84e97b..0962db9678e 100644--- a/apps/server/src/services/goal/start.ts+++ b/apps/server/src/services/goal/start.ts@@ -264,6 +264,12 @@ export class GoalStartService {createdByAgentId: goal.agentId ?? undefined,goalId: goal.id,goalModel: new GoalModel(db, this.userId, this.workspaceId),+ planSkillOwner: {+ db,+ goalTitle: goal.title,+ userId: this.userId,+ workspaceId: this.workspaceId,+ },policy,problemId: problem.id,probes: probeDrafts,diff --git a/apps/server/src/services/taskRunner/index.ts b/apps/server/src/services/taskRunner/index.tsindex 63dd79bf12a..e6b2c6d4d5f 100644--- a/apps/server/src/services/taskRunner/index.ts+++ b/apps/server/src/services/taskRunner/index.ts@@ -17,6 +17,7 @@ import type { LobeChatDatabase } from '@/database/type';import { AiAgentService } from '@/server/services/aiAgent';import { resolveFailedRunStatus } from '@/server/services/goal/recoveryPolicy';import { createTaskRunHooks } from '@/server/services/task/runHooks';+import { readTaskSkillIds } from '@/server/services/userSkill';import { buildTaskPrompt } from './buildTaskPrompt';import {@@ -244,6 +245,9 @@ export class TaskRunnerService {if (additionalPluginIds) pluginIds.push(...additionalPluginIds);const taskConfig = (task.config ?? {}) as Record<string, unknown>;+ // Skills the task itself names for every run — a goal batch's units name+ // the batch's plan skill — so a re-run or a manual run loads them too.+ pluginIds.push(...readTaskSkillIds(taskConfig));// Backfill model snapshot for tasks created before the snapshot logic// landed, or whose assignee was set after creation. Once written, thediff --git a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts b/apps/server/src/services/toolExecution/serverRuntimes/skills.tsindex c1cd8b15079..51c65c97f09 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts@@ -29,6 +29,7 @@ import debug from 'debug';import { AgentModel } from '@/database/models/agent';import { AgentSkillModel } from '@/database/models/agentSkill';import { FileModel } from '@/database/models/file';+import { TaskModel } from '@/database/models/task';import { UserModel } from '@/database/models/user';import type { LobeChatDatabase } from '@/database/type';import { filterBuiltinSkills } from '@/helpers/skillFilters';@@ -50,6 +51,11 @@ import {isLhCommand,preprocessLhCommand,} from '@/server/services/toolExecution/preprocessLhCommand';+import {+ canonicalUserSkillIdentifier,+ readTaskSkillIds,+ UserSkillService,+} from '@/server/services/userSkill';import { resolveContentWorkspaceId, resolveRunWorkspaceId } from './resolveWorkspaceScope';import { type ServerRuntimeRegistration } from './types';@@ -1078,6 +1084,49 @@ export const skillsRuntime: ServerRuntimeRegistration = {projectSkills: projectSkills?.filter((skill) =>isSkillReachable(`${skill.source ?? 'project'}:${skill.name}`),),+ // The user's own skill library is read per call, for the one name asked+ // for — it grows with every goal batch, and this factory runs per tool+ // call. Same carrier shape as above, under the recovered workspace (a+ // dispatched or resumed run may not carry it on the context).+ resolveSkill: async (requested) => {+ // Models vary the casing of a name, as the preloaded lookup tolerates.+ const name = canonicalUserSkillIdentifier(requested);+ if (!name || !isSkillReachable(name)) return undefined;+ const [skill] = await new UserSkillService(+ context.serverDB!,+ context.userId!,+ workspaceId,+ context.agentVisibility,+ )+ .loadRuntimeSkills([name], {+ // Only the generated skills this run's own Task names are trusted+ // past a public agent's visibility — never a name the model chose.+ trustedGenerated: context.taskId+ ? readTaskSkillIds(+ (+ await new TaskModel(context.serverDB!, context.userId!, workspaceId).findById(+ context.taskId,+ )+ )?.config,+ )+ : [],+ })+ .catch((error) => {+ log('failed to load user skill %s: %O', name, error);+ return [];+ });+ return (+ skill && {+ content: skill.body,+ description: skill.description,+ identifier: skill.identifier,+ name: skill.name,+ resources: skill.resources,+ source: 'builtin' as const,+ title: skill.title,+ }+ );+ },service,});},diff --git a/apps/server/src/services/userSkill/index.test.ts b/apps/server/src/services/userSkill/index.test.tsnew file mode 100644index 00000000000..c1ab20716c7--- /dev/null+++ b/apps/server/src/services/userSkill/index.test.ts@@ -0,0 +1,54 @@+import { describe, expect, it } from 'vitest';++import { canonicalUserSkillIdentifier, isUserSkillIdentifier, toRuntimeSkill } from './index';++const skill = {+ content: '---\nname: migrate-slice\ndescription: Move one slice\n---\nDo it.',+ createdAt: new Date(),+ description: 'Move one slice',+ files: [] as { content: string; language?: string; path: string }[],+ id: 'docs_1',+ name: 'migrate-slice',+ title: 'Migrate a slice',+ updatedAt: new Date(),+ version: 2,+};++describe('toRuntimeSkill', () => {+ it('names a library skill under the user-skills prefix', () => {+ const runtime = toRuntimeSkill(skill);+ expect(runtime).toMatchObject({+ content: skill.content,+ identifier: 'user-skills:migrate-slice',+ name: 'user-skills:migrate-slice',+ title: 'Migrate a slice',+ });+ expect(runtime.resources).toBeUndefined();+ expect(isUserSkillIdentifier(runtime.identifier)).toBe(true);+ });++ it('serves scripts as resources and lists them after SKILL.md when injected', () => {+ const runtime = toRuntimeSkill({+ ...skill,+ files: [{ content: 'echo ok', language: 'bash', path: 'scripts/check.sh' }],+ });+ expect(runtime.body).toBe(skill.content);+ expect(runtime.resources?.['scripts/check.sh']).toMatchObject({ content: 'echo ok', size: 7 });+ expect(runtime.content).toContain('check.sh');+ expect(runtime.content).toContain('readReference');+ expect(runtime.content.startsWith(skill.content)).toBe(true);+ });+});++describe('canonicalUserSkillIdentifier', () => {+ it('accepts a user skill name in any casing', () => {+ expect(canonicalUserSkillIdentifier('User-Skills:Goal-Plan-X')).toBe('user-skills:goal-plan-x');+ expect(canonicalUserSkillIdentifier(' user-skills:goal-plan-x ')).toBe(+ 'user-skills:goal-plan-x',+ );+ });++ it('rejects a name that is not a user skill', () => {+ expect(canonicalUserSkillIdentifier('agent-skills:foo')).toBeUndefined();+ });+});diff --git a/apps/server/src/services/userSkill/index.ts b/apps/server/src/services/userSkill/index.tsnew file mode 100644index 00000000000..f7ad58911d9--- /dev/null+++ b/apps/server/src/services/userSkill/index.ts@@ -0,0 +1,210 @@+import { buildUserSkillIdentifier, USER_SKILLS_IDENTIFIER_PREFIX } from '@lobechat/const';+import type { LobeChatDatabase } from '@lobechat/database';+import { resourcesTreePrompt } from '@lobechat/prompts';+import type { SkillResourceMeta } from '@lobechat/types';+import { sha256 } from 'js-sha256';++import {+ type UserSkillFile,+ type UserSkillItem,+ UserSkillModel,+ type UserSkillOrigin,+ type UserSkillVersion,+} from '@/database/models/userSkill';++import { renderSkillIndexContent, validateSkillName } from '../skillManagement/frontmatter';++/**+ * The user's own skill library: skills that belong to the user rather than to+ * one agent, so any agent or run can load them — a goal batch's execution plan+ * is one, and stays reusable after the goal ends.+ *+ * Every run lists the library (name and description) and can activate a skill+ * by name; a run that names a skill in its plugins — `user-skills:<name>` — gets+ * its content injected up front, scripts included.+ */++export const isUserSkillIdentifier = (id: string) => id.startsWith(USER_SKILLS_IDENTIFIER_PREFIX);++/** The skill identifiers a task's config names under `skills`. */+export const readTaskSkillIds = (config: unknown): string[] => {+ const skills = (config as { skills?: unknown } | null | undefined)?.skills;+ return Array.isArray(skills)+ ? skills.filter((id): id is string => typeof id === 'string' && !!id)+ : [];+};++const toName = (identifier: string) => identifier.slice(USER_SKILLS_IDENTIFIER_PREFIX.length);++/**+ * The canonical identifier of a user skill a model named, or undefined when+ * the name is not one. Models vary casing; user skill names are lowercase+ * slugs, so the lowercased name is the canonical one.+ */+export const canonicalUserSkillIdentifier = (name: string): string | undefined => {+ const canonical = name.trim().toLowerCase();+ return isUserSkillIdentifier(canonical) ? canonical : undefined;+};++/** A skill as the skill pool and the skills runtime take it. */+export interface UserRuntimeSkill {+ /** `SKILL.md` alone — `activateSkill` appends the tree of its scripts itself. */+ body: string;+ /** `SKILL.md`, then the tree of its scripts: what a run injects up front. */+ content: string;+ description: string;+ identifier: string;+ name: string;+ resources?: Record<string, SkillResourceMeta>;+ title: string;+}++export interface UserSkillDetail extends UserSkillItem {+ identifier: string;+ versions: UserSkillVersion[];+}++const MAX_NAME_ATTEMPTS = 50;++const toResources = (files: UserSkillFile[]): Record<string, SkillResourceMeta> | undefined =>+ files.length+ ? Object.fromEntries(+ files.map((file) => [+ file.path,+ { content: file.content, fileHash: sha256(file.content), size: file.content.length },+ ]),+ )+ : undefined;++export const toRuntimeSkill = (skill: UserSkillItem): UserRuntimeSkill => {+ const identifier = buildUserSkillIdentifier(skill.name);+ const resources = toResources(skill.files);+ return {+ body: skill.content,+ content: resources+ ? `${skill.content}\n\n${resourcesTreePrompt(identifier, resources)}`+ : skill.content,+ description: skill.description,+ identifier,+ // The name a model activates it by, the same way agent-document skills do.+ name: identifier,+ resources,+ title: skill.title,+ };+};++export class UserSkillService {+ private model: UserSkillModel;++ /**+ * `callerAgentVisibility` is the run's agent: a workspace-public agent reads+ * none of its caller's (private) skills.+ */+ constructor(+ db: LobeChatDatabase,+ userId: string,+ workspaceId?: string,+ callerAgentVisibility?: 'private' | 'public' | null,+ ) {+ this.model = new UserSkillModel(db, userId, workspaceId, callerAgentVisibility);+ }++ /** A free name from `base`: `base`, then `base-2`, `base-3`, … */+ private freeName = async (base: string) => {+ const name = validateSkillName(base);+ for (let attempt = 1; attempt <= MAX_NAME_ATTEMPTS; attempt++) {+ const candidate = attempt === 1 ? name : `${name}-${attempt}`;+ if (!(await this.model.nameTaken(candidate))) return candidate;+ }+ throw new Error(`No free skill name for ${name}`);+ };++ /** Creates a skill at v1; the name is made unique within the library. */+ createSkill = async (params: {+ body: string;+ description: string;+ files?: UserSkillFile[];+ name: string;+ note?: string;+ origin?: UserSkillOrigin;+ title: string;+ }): Promise<UserSkillItem> => {+ const name = await this.freeName(params.name);+ return this.model.create({+ content: renderSkillIndexContent({+ bodyMarkdown: params.body,+ description: params.description,+ name,+ }),+ description: params.description,+ files: params.files,+ name,+ note: params.note,+ origin: params.origin,+ title: params.title,+ });+ };++ /** Writes the next version of a skill's body. Returns its number. */+ reviseSkill = async (+ id: string,+ params: { body: string; note?: string; origin?: UserSkillOrigin },+ ): Promise<number | undefined> => {+ const skill = await this.model.findById(id);+ if (!skill) return undefined;+ return this.model.revise(id, {+ content: renderSkillIndexContent({+ bodyMarkdown: params.body,+ description: skill.description,+ name: skill.name,+ }),+ note: params.note,+ origin: params.origin,+ });+ };++ getSkill = async (id: string): Promise<UserSkillDetail | undefined> => {+ const skill = await this.model.findById(id);+ if (!skill) return undefined;+ return {+ ...skill,+ identifier: buildUserSkillIdentifier(skill.name),+ versions: await this.model.listVersions(id),+ };+ };++ /** Every skill in the library, shaped for a run. */+ listRuntimeSkills = async (): Promise<UserRuntimeSkill[]> =>+ (await this.model.findAll()).map(toRuntimeSkill);++ /**+ * What every run lists: identifier, name and description of each library+ * skill, without reading any body. Cheap however large the library grows.+ */+ listCatalog = async (options?: { includeGenerated?: boolean }) =>+ (await this.model.listCatalog(options)).map((skill) => {+ const identifier = buildUserSkillIdentifier(skill.name);+ return {+ description: skill.description,+ generated: skill.generated,+ identifier,+ name: identifier,+ title: skill.title,+ };+ });++ /**+ * Bodies (and scripts) of just the skills a run pins or names.+ * `trustedGenerated` lists generated skills the run's own Task names: those+ * load even through a workspace-public agent (it is the goal's own plan).+ */+ loadRuntimeSkills = async (+ identifiers: Iterable<string>,+ { trustedGenerated = [] }: { trustedGenerated?: Iterable<string> } = {},+ ): Promise<UserRuntimeSkill[]> => {+ const names = [...new Set(identifiers)].filter(isUserSkillIdentifier).map(toName);+ if (!names.length) return [];+ const trusted = [...new Set(trustedGenerated)].filter(isUserSkillIdentifier).map(toName);+ return (await this.model.findByNames(names, { trustedGenerated: trusted })).map(toRuntimeSkill);+ };+}diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex a511141952e..d3227ad662b 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -489,6 +489,8 @@"goalBatch.gatePanel.history.released": "Released wave {{wave}} ({{count}} units)","goalBatch.gatePanel.history.unit": "“{{title}}” failed its own check — the batch was held at once","goalBatch.gatePanel.history.unrecorded": "Judged before verdicts were recorded — no detail kept",+ "goalBatch.gatePanel.learned": "What this gate taught",+ "goalBatch.gatePanel.learnedHint": "Written into the plan every later unit loads, and added to the acceptance each of them must pass.","goalBatch.gatePanel.next.checking": "Every unit finished — judged on the coordinator’s next step","goalBatch.gatePanel.next.human": "Waiting on you: revise the plan, or fork a fresh one for the units that broke","goalBatch.gatePanel.next.locked": "Judged automatically once this round’s {{count}} units finish",@@ -498,13 +500,14 @@"goalBatch.gatePanel.question": "Revise the plan and re-probe, or fork a fresh one for the units that broke?","goalBatch.gatePanel.verdict": "Verdict","goalBatch.overviewCount": "Total: {{count}} batches · {{nodes}} nodes",- "goalBatch.planPanel.compare": "Compare with",- "goalBatch.planPanel.diff": "What changed from v{{base}} to v{{revision}}",- "goalBatch.planPanel.first": "The first version — nothing earlier to compare with",+ "goalBatch.planPanel.compare": "Compare versions",+ "goalBatch.planPanel.compareTitle": "Compare plan versions",+ "goalBatch.planPanel.files": "Files",+ "goalBatch.planPanel.foldFiles": "Hide files","goalBatch.planPanel.forked": "A forked plan: it starts again from the batch’s original outline instead of revising the previous version",- "goalBatch.planPanel.full": "v{{revision}} in full",+ "goalBatch.planPanel.latest": "v{{revision}} · latest","goalBatch.planPanel.same": "Same as v{{base}}",- "goalBatch.planPanel.version": "Version",+ "goalBatch.planPanel.unfoldFiles": "Show files","goalBatch.probes.cell.backlog": "Not started","goalBatch.probes.cell.done": "Done","goalBatch.probes.cell.human": "Needs you",@@ -526,6 +529,8 @@"goalBatch.round.foot": "{{count}} units","goalBatch.round.reviseEdge": "Sent back · revise","goalBatch.round.title": "Round {{revision}}",+ "goalBatch.skill.forked": "Plan skill v{{revision}} · new class",+ "goalBatch.skill.title": "Plan skill v{{revision}}","goalBatch.status.done": "All done","goalBatch.status.human": "{{count}} need you","goalBatch.status.pending": "Not started",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex ac08af19df2..cace01d31cf 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -489,6 +489,8 @@"goalBatch.gatePanel.history.released": "放行第 {{wave}} 批({{count}} 项)","goalBatch.gatePanel.history.unit": "「{{title}}」未通过自身验收,批次当即被拦下","goalBatch.gatePanel.history.unrecorded": "这一轮的判定早于判定记录功能,没有明细",+ "goalBatch.gatePanel.learned": "这道闸门学到的",+ "goalBatch.gatePanel.learnedHint": "已写进之后每个单元都会加载的方案,并加进它们各自的验收要求。","goalBatch.gatePanel.next.checking": "单元已全部跑完,协调器下一次推进时判定","goalBatch.gatePanel.next.human": "等你决定:修订方案重探,或为出问题的几项另起一份方案","goalBatch.gatePanel.next.locked": "本轮 {{count}} 个单元跑完后自动判定",@@ -498,13 +500,14 @@"goalBatch.gatePanel.question": "修订方案重探,还是为出问题的几项另起一份方案?","goalBatch.gatePanel.verdict": "结论","goalBatch.overviewCount": "共 {{count}} 个批次 · {{nodes}} 个节点",- "goalBatch.planPanel.compare": "对比",- "goalBatch.planPanel.diff": "v{{base}} → v{{revision}} 的变化",- "goalBatch.planPanel.first": "这是第一版方案,没有可对比的上一版",+ "goalBatch.planPanel.compare": "对比版本",+ "goalBatch.planPanel.compareTitle": "对比方案版本",+ "goalBatch.planPanel.files": "文件",+ "goalBatch.planPanel.foldFiles": "收起文件","goalBatch.planPanel.forked": "另起的方案:不沿用上一版的修订,从批次最初的方案出发",- "goalBatch.planPanel.full": "v{{revision}} 全文",+ "goalBatch.planPanel.latest": "v{{revision}} · 最新","goalBatch.planPanel.same": "与 v{{base}} 相同",- "goalBatch.planPanel.version": "版本",+ "goalBatch.planPanel.unfoldFiles": "展开文件","goalBatch.probes.cell.backlog": "未开始","goalBatch.probes.cell.done": "已完成","goalBatch.probes.cell.human": "需要介入",@@ -526,6 +529,8 @@"goalBatch.round.foot": "{{count}} 项","goalBatch.round.reviseEdge": "打回 · 修订","goalBatch.round.title": "第 {{revision}} 轮",+ "goalBatch.skill.forked": "方案技能 v{{revision}} · 新类型",+ "goalBatch.skill.title": "方案技能 v{{revision}}","goalBatch.status.done": "全部完成","goalBatch.status.human": "{{count}} 项需要介入","goalBatch.status.pending": "待开始",diff --git a/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.tsindex 96987ce2490..bb11b7aa84c 100644--- a/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.ts+++ b/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.ts@@ -487,4 +487,36 @@ describe('SkillsExecutionRuntime', () => {expect(result.content).toBe('kb body');});});++ describe('resolveSkill', () => {+ const userSkill = {+ content: 'PLAN BODY',+ description: 'How each unit is done',+ identifier: 'user-skills:goal-plan-x',+ name: 'user-skills:goal-plan-x',+ resources: {+ 'scripts/check.sh': { content: 'echo ok', fileHash: 'h', size: 7 },+ },+ source: 'builtin' as const,+ title: 'Plan',+ };++ it('reads a skill that was not preloaded, once, only when it is asked for', async () => {+ const resolveSkill = vi.fn().mockResolvedValue(userSkill);+ const runtime = new SkillsExecutionRuntime({ resolveSkill, service: createMockService() });+ expect(resolveSkill).not.toHaveBeenCalled();++ const activated = await runtime.activateSkill({ name: 'user-skills:goal-plan-x' });+ expect(activated.success).toBe(true);+ expect(activated.content).toContain('PLAN BODY');+ expect(activated.state).toMatchObject({ source: 'user' });++ const script = await runtime.readReference({+ id: 'user-skills:goal-plan-x',+ path: 'scripts/check.sh',+ } as never);+ expect(script.content).toContain('echo ok');+ expect(resolveSkill).toHaveBeenCalledTimes(1);+ });+ });});diff --git a/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts b/packages/builtin-tool-skills/src/ExecutionRuntime/index.tsindex 1f712e8d254..69327434ea4 100644--- a/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts@@ -1,4 +1,4 @@-import { AGENT_SKILLS_IDENTIFIER_PREFIX } from '@lobechat/const';+import { AGENT_SKILLS_IDENTIFIER_PREFIX, USER_SKILLS_IDENTIFIER_PREFIX } from '@lobechat/const';import {formatCommandResult,formatSandboxRecreation,@@ -105,6 +105,12 @@ export interface SkillsExecutionRuntimeOptions {deviceFileAccess?: DeviceFileAccess;/** Filesystem skills discovered on the execution device. */projectSkills?: ProjectSkillRuntimeItem[];+ /**+ * Resolves a skill by name when it is not among `builtinSkills`: a library+ * too large to load up front (the user's own skills) is read on demand, only+ * for the name a call asks for.+ */+ resolveSkill?: (name: string) => Promise<BuiltinSkill | undefined>;service: SkillRuntimeService;}@@ -167,6 +173,7 @@ export class SkillsExecutionRuntime {private builtinSkills: BuiltinSkill[];private projectSkills: ProjectSkillRuntimeItem[];private deviceFileAccess?: DeviceFileAccess;+ private resolveSkill?: (name: string) => Promise<BuiltinSkill | undefined>;private service: SkillRuntimeService;constructor(options: SkillsExecutionRuntimeOptions) {@@ -175,8 +182,18 @@ export class SkillsExecutionRuntime {this.builtinSkills = options.builtinSkills || [];this.projectSkills = options.projectSkills || [];this.deviceFileAccess = options.deviceFileAccess;+ this.resolveSkill = options.resolveSkill;}+ /** A preloaded builtin-shaped skill, else one the resolver reads on demand. */+ private findBuiltinSkill = async (name: string): Promise<BuiltinSkill | undefined> => {+ const preloaded = findByNameCI(this.builtinSkills, name);+ if (preloaded || !this.resolveSkill) return preloaded;+ const resolved = await this.resolveSkill(name);+ if (resolved) this.builtinSkills = [...this.builtinSkills, resolved];+ return resolved;+ };+async execScript(args: ExecScriptParams): Promise<BuiltinServerRuntimeOutput> {const { command, description } = args;// Args win when the caller (client executor) already injected stepContext;@@ -365,7 +382,7 @@ export class SkillsExecutionRuntime {// Fall back to builtin skills (includes agent-document skill bundles// via the `agent-skills:` identifier prefix).- const builtinSkill = findByNameCI(this.builtinSkills, id);+ const builtinSkill = await this.findBuiltinSkill(id);if (builtinSkill?.resources) {const meta = builtinSkill.resources[path];if (meta?.content !== undefined) {@@ -470,7 +487,7 @@ export class SkillsExecutionRuntime {// Fall back to builtin skills (includes agent-document skill bundles via// the `agent-skills:` identifier prefix).- const builtinSkill = findByNameCI(this.builtinSkills, name);+ const builtinSkill = await this.findBuiltinSkill(name);if (builtinSkill) {let content = builtinSkill.content;const hasResources = !!(@@ -486,6 +503,8 @@ export class SkillsExecutionRuntime {// inspector can pick the right label ("Activate Agent Skill") and prefer// the friendly `title` over the raw `agent-skills:<filename>` name.const isAgentSkill = builtinSkill.identifier.startsWith(AGENT_SKILLS_IDENTIFIER_PREFIX);+ // The user's own skill library rides the same path under `user-skills:`.+ const isUserSkill = builtinSkill.identifier.startsWith(USER_SKILLS_IDENTIFIER_PREFIX);return {content,@@ -494,7 +513,7 @@ export class SkillsExecutionRuntime {hasResources,identifier: builtinSkill.identifier,name: builtinSkill.name,- source: isAgentSkill ? 'agent' : 'builtin',+ source: isAgentSkill ? 'agent' : isUserSkill ? 'user' : 'builtin',...(builtinSkill.title && { title: builtinSkill.title }),},success: true,diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.tsindex 79262045758..88c2a67185f 100644--- a/packages/const/src/apiKeyScope.ts+++ b/packages/const/src/apiKeyScope.ts@@ -301,6 +301,8 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRuleuser: rw('user:read', 'user:write'),userMemories: rw('user:read', 'user:write'),userMemory: rw('user:read', 'user:write'),+ // the user's own skill library — same scope as the agent skills it sits beside+ userSkill: rw('agent:read', 'agent:write'),verify: 'blocked',video: { any: 'model:invoke' },waitlist: 'blocked',diff --git a/packages/const/src/skill.ts b/packages/const/src/skill.tsindex bc377e4e4b0..e2b3419aa11 100644--- a/packages/const/src/skill.ts+++ b/packages/const/src/skill.ts@@ -18,6 +18,16 @@ export const SKILL_DRAG_MIME = 'application/x-lobe-skill';*/export const AGENT_SKILLS_IDENTIFIER_PREFIX = 'agent-skills:';+/**+ * Identifier prefix for skills in the user's own library (`documents` bundles+ * owned by the user and bound to no agent). Any run can activate one by this+ * identifier; a run that lists it in its plugins gets it injected.+ */+export const USER_SKILLS_IDENTIFIER_PREFIX = 'user-skills:';++export const buildUserSkillIdentifier = (name: string): string =>+ `${USER_SKILLS_IDENTIFIER_PREFIX}${name}`;+export const buildAgentSkillIdentifier = (filename: string): string =>`${AGENT_SKILLS_IDENTIFIER_PREFIX}${filename}`;diff --git a/packages/database/src/models/__tests__/userSkill.test.ts b/packages/database/src/models/__tests__/userSkill.test.tsnew file mode 100644index 00000000000..d2f9cf36703--- /dev/null+++ b/packages/database/src/models/__tests__/userSkill.test.ts@@ -0,0 +1,164 @@+// @vitest-environment node+import { and, eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { documents, users, workspaces } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { DocumentModel } from '../document';+import { UserSkillModel } from '../userSkill';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'user-skill-model-test-user';+const otherUserId = 'user-skill-model-test-other';+const model = new UserSkillModel(serverDB, userId);++beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+});++afterEach(async () => {+ await serverDB.delete(documents).where(eq(documents.userId, userId));+ await serverDB.delete(users);+});++const create = () =>+ model.create({+ content: '---\nname: migrate-slice\ndescription: Move one slice\n---\nv1 body',+ description: 'Move one slice',+ files: [{ content: 'echo ok', language: 'bash', path: 'scripts/check.sh' }],+ name: 'migrate-slice',+ origin: { goalId: 'goal_1' },+ title: 'Migrate a slice',+ });++describe('UserSkillModel', () => {+ it('creates a skill with its SKILL.md, its scripts and a v1 snapshot', async () => {+ const skill = await create();++ expect(skill).toMatchObject({+ description: 'Move one slice',+ files: [{ content: 'echo ok', language: 'bash', path: 'scripts/check.sh' }],+ name: 'migrate-slice',+ origin: { goalId: 'goal_1' },+ title: 'Migrate a slice',+ version: 1,+ });+ expect(skill.content).toContain('v1 body');+ expect(await model.listVersions(skill.id)).toMatchObject([{ version: 1 }]);+ expect(await model.nameTaken('migrate-slice')).toBe(true);+ });++ it('keeps every version whole as it revises, and serves the latest', async () => {+ const skill = await create();++ expect(await model.revise(skill.id, { content: 'v2 body', note: 'gate broke' })).toBe(2);+ expect(await model.revise(skill.id, { content: 'v3 body' })).toBe(3);++ const latest = await model.findById(skill.id);+ expect(latest).toMatchObject({ content: 'v3 body', version: 3 });+ expect((await model.listVersions(skill.id)).map((v) => [v.version, v.content, v.note])).toEqual(+ [+ [1, expect.stringContaining('v1 body'), undefined],+ [2, 'v2 body', 'gate broke'],+ [3, 'v3 body', undefined],+ ],+ );+ });++ it('loads skills by name for a run, and only the owner sees them', async () => {+ const skill = await create();++ expect((await model.findByNames(['migrate-slice', 'missing'])).map((s) => s.id)).toEqual([+ skill.id,+ ]);+ const other = new UserSkillModel(serverDB, otherUserId);+ expect(await other.findById(skill.id)).toBeUndefined();+ expect(await other.revise(skill.id, { content: 'hijack' })).toBeUndefined();+ });++ it('lists the library as a catalog without reading any body', async () => {+ const skill = await create();+ expect(await model.listCatalog()).toEqual([+ {+ description: 'Move one slice',+ generated: false,+ id: skill.id,+ name: 'migrate-slice',+ title: 'Migrate a slice',+ },+ ]);+ });++ it('flags a skill a goal batch wrote as generated', async () => {+ await model.create({+ content: 'v1',+ description: 'How each unit is done',+ name: 'goal-plan-x',+ origin: { batchNodeId: 'batch-1', goalId: 'goal-1', revision: 1 },+ title: 'Plan',+ });+ expect((await model.listCatalog()).map((item) => [item.name, item.generated])).toEqual([+ ['goal-plan-x', true],+ ]);+ // A run listing only hand-made skills does not read it at all.+ expect(await model.listCatalog({ includeGenerated: false })).toEqual([]);+ });++ it('keeps a workspace member’s skills away from the other members', async () => {+ const [workspace] = await serverDB+ .insert(workspaces)+ .values({ name: 'user-skill-ws', primaryOwnerId: userId, slug: 'user-skill-ws' })+ .returning();+ const creator = new UserSkillModel(serverDB, userId, workspace.id);+ const skill = await creator.create({+ content: 'Do it.',+ description: 'Move one slice',+ name: 'migrate-slice',+ title: 'Migrate a slice',+ });++ const member = new UserSkillModel(serverDB, otherUserId, workspace.id);+ expect(await member.listCatalog()).toEqual([]);+ expect(await member.findByNames(['migrate-slice'])).toEqual([]);+ expect(await member.findById(skill.id)).toBeUndefined();+ expect(await member.revise(skill.id, { content: 'hijack' })).toBeUndefined();+ // The creator still has it…+ expect((await creator.listCatalog()).map((item) => item.id)).toEqual([skill.id]);+ // …but not through a workspace-public agent, which must not read (and+ // echo) its caller's private instructions.+ const throughPublicAgent = new UserSkillModel(serverDB, userId, workspace.id, 'public');+ expect(await throughPublicAgent.listCatalog()).toEqual([]);+ expect(await throughPublicAgent.findByNames(['migrate-slice'])).toEqual([]);+ // A goal batch's own plan loads there only when the run's Task names it —+ // it is the goal's plan — never because a name was merely supplied.+ await creator.create({+ content: 'Plan body',+ description: 'How each unit is done',+ files: [{ content: 'echo ok', path: 'scripts/check.sh' }],+ name: 'goal-plan-x',+ origin: { batchNodeId: 'batch-1', goalId: 'goal-1', revision: 1 },+ title: 'Plan',+ });+ expect(await throughPublicAgent.findByNames(['goal-plan-x'])).toEqual([]);+ const [plan] = await throughPublicAgent.findByNames(['goal-plan-x', 'migrate-slice'], {+ trustedGenerated: ['goal-plan-x'],+ });+ expect(plan).toMatchObject({ content: 'Plan body', name: 'goal-plan-x' });+ expect(plan.files.map((file) => file.path)).toEqual(['scripts/check.sh']);+ await serverDB.delete(workspaces);+ });++ it('stays out of the Page library', async () => {+ await create();+ const { items } = await new DocumentModel(serverDB, userId).query();+ expect(items).toEqual([]);+ const stored = await serverDB+ .select({ sourceType: documents.sourceType })+ .from(documents)+ .where(and(eq(documents.userId, userId)));+ expect(new Set(stored.map((row) => row.sourceType))).toEqual(new Set(['agent']));+ });+});diff --git a/packages/database/src/models/userSkill.ts b/packages/database/src/models/userSkill.tsnew file mode 100644index 00000000000..06c8fc9ee6e--- /dev/null+++ b/packages/database/src/models/userSkill.ts@@ -0,0 +1,468 @@+import { and, asc, eq, inArray, isNull, or, type SQL, sql } from 'drizzle-orm';++import {+ documents,+ SKILL_BUNDLE_FILE_TYPE,+ SKILL_INDEX_FILE_TYPE,+ SKILL_INDEX_FILENAME,+ SKILL_SCRIPT_FILE_TYPE,+ SKILL_VERSION_FILE_TYPE,+ USER_SKILL_SOURCE,+} from '../schemas';+import type { LobeChatDatabase, Transaction } from '../type';+import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';++/**+ * A user-level skill library on the `documents` table.+ *+ * A skill is a `skills/bundle` row owned by the user and bound to no agent, so+ * any agent or run can load it by name. Under it sit its `SKILL.md`+ * (`skills/index`), its scripts (`skills/script`, the code in `content`, the+ * language in `metadata.language`) and one `skills/version` row per version —+ * the full `SKILL.md` it read at that version. Versions are rows of their own,+ * not document history: history is trimmed, a version must stay readable.+ *+ * Rows carry `sourceType: 'agent'` so the Page library never lists them.+ */++export interface UserSkillFile {+ content: string;+ language?: string;+ /** Path inside the bundle, e.g. `scripts/check.sh`. */+ path: string;+}++/** Where a skill or a version came from, e.g. the goal batch that wrote it. */+export type UserSkillOrigin = Record<string, unknown>;++export interface UserSkillVersion {+ content: string;+ createdAt: Date;+ id: string;+ note?: string;+ origin?: UserSkillOrigin;+ version: number;+}++export interface UserSkillCatalogItem {+ description: string;+ /**+ * Written by the system for one job (a goal batch's plan), not by the person.+ * Such skills are loaded where they are named, not listed to every run.+ */+ generated: boolean;+ id: string;+ name: string;+ title: string;+}++export interface UserSkillItem {+ /** The current `SKILL.md`. */+ content: string;+ createdAt: Date;+ description: string;+ files: UserSkillFile[];+ id: string;+ name: string;+ origin?: UserSkillOrigin;+ title: string;+ updatedAt: Date;+ version: number;+}++interface UserSkillMeta {+ origin?: UserSkillOrigin;+ version: number;+}++const SOURCE_TYPE = 'agent' as const;++const lineCount = (text: string) => (text ? text.split('\n').length : 0);++export class UserSkillModel {+ private db: LobeChatDatabase;+ private userId: string;+ private workspaceId?: string;++ /**+ * Visibility of the agent a read runs for. A workspace-public agent must not+ * read its caller's private rows — and user skills are private — so such a+ * run sees none of them (see `buildWorkspaceWhere`).+ */+ private callerAgentVisibility?: 'private' | 'public' | null;++ constructor(+ db: LobeChatDatabase,+ userId: string,+ workspaceId?: string,+ callerAgentVisibility?: 'private' | 'public' | null,+ ) {+ this.db = db;+ this.userId = userId;+ this.workspaceId = workspaceId;+ this.callerAgentVisibility = callerAgentVisibility;+ }++ /**+ * The caller's own rows in the current workspace. A user skill belongs to its+ * creator: the workspace scope alone would also admit other members' public+ * rows, putting one member's instructions into another member's runs.+ */+ private scope = () =>+ and(+ buildWorkspaceWhere(+ {+ callerAgentVisibility: this.callerAgentVisibility,+ userId: this.userId,+ workspaceId: this.workspaceId,+ },+ documents,+ ),+ eq(documents.userId, this.userId),+ );++ /** The caller's own rows, whatever agent the read runs for. */+ private ownerScope = () =>+ and(+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, documents),+ eq(documents.userId, this.userId),+ );++ private bundleWhere = (scope: SQL | undefined = this.scope()) =>+ and(+ scope,+ eq(documents.fileType, SKILL_BUNDLE_FILE_TYPE),+ eq(documents.source, USER_SKILL_SOURCE),+ isNull(documents.parentId),+ );++ /** A bundle a goal batch generated records the batch in its origin. */+ private generated = () =>+ sql<boolean>`COALESCE(jsonb_exists(${documents.metadata} -> 'userSkill' -> 'origin', 'batchNodeId'), false)`;++ private row = (params: {+ content: string;+ description?: string | null;+ fileType: string;+ filename: string;+ metadata?: Record<string, unknown>;+ parentId?: string;+ title: string;+ }) =>+ buildWorkspacePayload(+ { userId: this.userId, workspaceId: this.workspaceId },+ {+ content: params.content,+ description: params.description ?? null,+ fileType: params.fileType,+ filename: params.filename,+ metadata: params.metadata,+ parentId: params.parentId,+ source: USER_SKILL_SOURCE,+ sourceType: SOURCE_TYPE,+ // Owner-only, like the reads above: never listed to other members.+ visibility: 'private' as const,+ title: params.title,+ totalCharCount: params.content.length,+ totalLineCount: lineCount(params.content),+ },+ );++ private insertVersion = async (+ tx: Transaction,+ bundleId: string,+ params: { content: string; note?: string; origin?: UserSkillOrigin; version: number },+ ) => {+ await tx.insert(documents).values(+ this.row({+ content: params.content,+ fileType: SKILL_VERSION_FILE_TYPE,+ filename: `v${params.version}`,+ metadata: { note: params.note, origin: params.origin, version: params.version },+ parentId: bundleId,+ title: `v${params.version}`,+ }),+ );+ };++ /** Whether the user already has a skill with this name. */+ nameTaken = async (name: string) => {+ const [row] = await this.db+ .select({ id: documents.id })+ .from(documents)+ .where(and(this.bundleWhere(), eq(documents.filename, name)))+ .limit(1);+ return !!row;+ };++ /**+ * Creates a skill at version 1: its bundle, its `SKILL.md`, its scripts, and+ * the v1 snapshot.+ */+ create = async (params: {+ content: string;+ description: string;+ files?: UserSkillFile[];+ name: string;+ note?: string;+ origin?: UserSkillOrigin;+ title: string;+ }): Promise<UserSkillItem> => {+ const id = await this.db.transaction(async (tx) => {+ const [bundle] = await tx+ .insert(documents)+ .values(+ this.row({+ content: '',+ description: params.description,+ fileType: SKILL_BUNDLE_FILE_TYPE,+ filename: params.name,+ metadata: {+ skill: { frontmatter: { description: params.description, name: params.name } },+ userSkill: { origin: params.origin, version: 1 } satisfies UserSkillMeta,+ },+ title: params.title,+ }),+ )+ .returning({ id: documents.id });+ await tx.insert(documents).values(+ this.row({+ content: params.content,+ fileType: SKILL_INDEX_FILE_TYPE,+ filename: SKILL_INDEX_FILENAME,+ parentId: bundle.id,+ title: SKILL_INDEX_FILENAME,+ }),+ );+ for (const file of params.files ?? []) {+ await tx.insert(documents).values(+ this.row({+ content: file.content,+ fileType: SKILL_SCRIPT_FILE_TYPE,+ filename: file.path,+ metadata: file.language ? { language: file.language } : undefined,+ parentId: bundle.id,+ title: file.path,+ }),+ );+ }+ await this.insertVersion(tx, bundle.id, {+ content: params.content,+ note: params.note,+ origin: params.origin,+ version: 1,+ });+ return bundle.id;+ });+ return (await this.findById(id))!;+ };++ /**+ * Writes a new version: replaces the current `SKILL.md` and freezes it as the+ * next version. Returns the new version number, or undefined when the skill+ * is not the caller's.+ */+ revise = async (+ id: string,+ params: { content: string; note?: string; origin?: UserSkillOrigin },+ ): Promise<number | undefined> =>+ this.db.transaction(async (tx) => {+ const [bundle] = await tx+ .select({ id: documents.id, metadata: documents.metadata })+ .from(documents)+ .where(and(this.bundleWhere(), eq(documents.id, id)))+ .for('update')+ .limit(1);+ if (!bundle) return undefined;+ const meta = (bundle.metadata?.userSkill ?? { version: 1 }) as UserSkillMeta;+ const version = meta.version + 1;++ await tx+ .update(documents)+ .set({+ content: params.content,+ totalCharCount: params.content.length,+ totalLineCount: lineCount(params.content),+ updatedAt: new Date(),+ })+ .where(+ and(+ this.scope(),+ eq(documents.parentId, id),+ eq(documents.fileType, SKILL_INDEX_FILE_TYPE),+ ),+ );+ await tx+ .update(documents)+ .set({+ metadata: { ...bundle.metadata, userSkill: { ...meta, version } },+ updatedAt: new Date(),+ })+ .where(and(this.bundleWhere(), eq(documents.id, id)));+ await this.insertVersion(tx, id, {+ content: params.content,+ note: params.note,+ origin: params.origin,+ version,+ });+ return version;+ });++ private load = async (bundles: (typeof documents.$inferSelect)[]): Promise<UserSkillItem[]> => {+ if (!bundles.length) return [];+ const children = await this.db+ .select()+ .from(documents)+ .where(+ and(+ // The bundles were authorized by the caller's read; their own rows+ // follow them.+ this.ownerScope(),+ inArray(+ documents.parentId,+ bundles.map((bundle) => bundle.id),+ ),+ inArray(documents.fileType, [SKILL_INDEX_FILE_TYPE, SKILL_SCRIPT_FILE_TYPE]),+ ),+ )+ .orderBy(asc(documents.filename));+ // One pass over the children, not one per bundle.+ const byBundle = new Map<string, (typeof children)[number][]>();+ for (const child of children) {+ if (!child.parentId) continue;+ const list = byBundle.get(child.parentId) ?? [];+ list.push(child);+ byBundle.set(child.parentId, list);+ }+ return bundles.map((bundle) => {+ const own = byBundle.get(bundle.id) ?? [];+ const meta = (bundle.metadata?.userSkill ?? { version: 1 }) as UserSkillMeta;+ return {+ content: own.find((child) => child.fileType === SKILL_INDEX_FILE_TYPE)?.content ?? '',+ createdAt: bundle.createdAt,+ description: bundle.description ?? '',+ files: own+ .filter((child) => child.fileType === SKILL_SCRIPT_FILE_TYPE)+ .map((child) => ({+ content: child.content ?? '',+ language: child.metadata?.language,+ path: child.filename ?? '',+ })),+ id: bundle.id,+ name: bundle.filename ?? '',+ origin: meta.origin,+ title: bundle.title ?? bundle.filename ?? '',+ updatedAt: bundle.updatedAt,+ version: meta.version,+ };+ });+ };++ findById = async (id: string): Promise<UserSkillItem | undefined> => {+ const bundles = await this.db+ .select()+ .from(documents)+ .where(and(this.bundleWhere(), eq(documents.id, id)))+ .limit(1);+ return (await this.load(bundles))[0];+ };++ /**+ * The library as a catalog: name, title and description from the bundle rows+ * alone, no `SKILL.md` or scripts. What every run lists; bodies are loaded+ * only for the skills a run actually uses (`findByNames`).+ */+ listCatalog = async ({ includeGenerated = true }: { includeGenerated?: boolean } = {}): Promise<+ UserSkillCatalogItem[]+ > => {+ // A bundle a goal batch generated records the batch in its origin. Tested+ // by key existence (never `IS NULL` on an extracted jsonb value), in the+ // query, so a run that lists only hand-made skills never reads the rest.+ const generated = this.generated();+ const rows = await this.db+ .select({+ description: documents.description,+ filename: documents.filename,+ generated,+ id: documents.id,+ title: documents.title,+ })+ .from(documents)+ .where(includeGenerated ? this.bundleWhere() : and(this.bundleWhere(), sql`NOT ${generated}`))+ .orderBy(asc(documents.filename));+ return rows.map((row) => ({+ description: row.description ?? '',+ generated: !!row.generated,+ id: row.id,+ name: row.filename ?? '',+ title: row.title ?? row.filename ?? '',+ }));+ };++ /** Every skill in the library, bodies included. */+ findAll = async (): Promise<UserSkillItem[]> => {+ const bundles = await this.db+ .select()+ .from(documents)+ .where(this.bundleWhere())+ .orderBy(asc(documents.filename));+ return this.load(bundles);+ };++ /** The skills with these names, for a run that loads them. */+ findByNames = async (+ names: string[],+ { trustedGenerated = [] }: { trustedGenerated?: string[] } = {},+ ): Promise<UserSkillItem[]> => {+ if (!names.length) return [];+ // A skill a goal batch generated is that goal's own plan — its units carry+ // it in their brief anyway — so the run whose Task names it gets it even+ // through a workspace-public agent. Only those exact names: a name the+ // model supplies never widens it, and the rest of the caller's private+ // library stays out of such a run.+ const trusted = trustedGenerated.filter((name) => names.includes(name));+ const bundles = await this.db+ .select()+ .from(documents)+ .where(+ and(+ trusted.length+ ? or(+ this.bundleWhere(),+ and(+ this.bundleWhere(this.ownerScope()),+ this.generated(),+ inArray(documents.filename, trusted),+ ),+ )+ : this.bundleWhere(),+ inArray(documents.filename, names),+ ),+ );+ return this.load(bundles);+ };++ /** Every version of a skill, oldest first. */+ listVersions = async (id: string): Promise<UserSkillVersion[]> => {+ const rows = await this.db+ .select()+ .from(documents)+ .where(+ and(+ this.scope(),+ eq(documents.parentId, id),+ eq(documents.fileType, SKILL_VERSION_FILE_TYPE),+ ),+ );+ return rows+ .map((row) => ({+ content: row.content ?? '',+ createdAt: row.createdAt,+ id: row.id,+ note: row.metadata?.note,+ origin: row.metadata?.origin,+ version: Number(row.metadata?.version ?? 0),+ }))+ .sort((a, b) => a.version - b.version);+ };+}diff --git a/packages/database/src/schemas/file.ts b/packages/database/src/schemas/file.tsindex b93172d60f0..bf5c7481bd9 100644--- a/packages/database/src/schemas/file.ts+++ b/packages/database/src/schemas/file.ts@@ -42,6 +42,18 @@ export const SKILL_BUNDLE_FILE_TYPE = 'skills/bundle';/** File type used by the SKILL.md index document inside a managed skill bundle. */export const SKILL_INDEX_FILE_TYPE = 'skills/index';+/** File type of a script file inside a skill bundle; its language sits in `metadata.language`. */+export const SKILL_SCRIPT_FILE_TYPE = 'skills/script';++/** File type of one frozen version of a user skill's `SKILL.md`, kept under its bundle. */+export const SKILL_VERSION_FILE_TYPE = 'skills/version';++/**+ * Source attribution of a user-level skill: a bundle owned by the user, not+ * bound to any agent, so any agent or run can load it by name.+ */+export const USER_SKILL_SOURCE = 'user-skills';+/** Source attribution stored on documents created by skill-management tooling. */export const SKILL_MANAGEMENT_SOURCE = 'agent-signal:skill-management';diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 22c35a2c1a5..82eded9d723 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -41,14 +41,15 @@ export default {'goalBatch.cell.stale': 'Superseded','goalBatch.cell.tooltip': 'Wave {{wave}} · item {{index}} · {{title}} · {{state}}','goalBatch.enter': 'Open',- 'goalBatch.planPanel.compare': 'Compare with',- 'goalBatch.planPanel.diff': 'What changed from v{{base}} to v{{revision}}',- 'goalBatch.planPanel.first': 'The first version — nothing earlier to compare with',+ 'goalBatch.planPanel.compare': 'Compare versions',+ 'goalBatch.planPanel.compareTitle': 'Compare plan versions',+ 'goalBatch.planPanel.files': 'Files',+ 'goalBatch.planPanel.foldFiles': 'Hide files','goalBatch.planPanel.forked':'A forked plan: it starts again from the batch’s original outline instead of revising the previous version',- 'goalBatch.planPanel.full': 'v{{revision}} in full',+ 'goalBatch.planPanel.latest': 'v{{revision}} · latest','goalBatch.planPanel.same': 'Same as v{{base}}',- 'goalBatch.planPanel.version': 'Version',+ 'goalBatch.planPanel.unfoldFiles': 'Show files','goalBatch.probes.cell.backlog': 'Not started','goalBatch.probes.cell.done': 'Done','goalBatch.probes.cell.human': 'Needs you',@@ -62,6 +63,9 @@ export default {'goalBatch.gateCheck.units_settled': 'Every unit this round finished','goalBatch.gateCheck.units_succeeded':'Every unit this round ran through on its own — none failed or was sent back',+ 'goalBatch.gatePanel.learned': 'What this gate taught',+ 'goalBatch.gatePanel.learnedHint':+ 'Written into the plan every later unit loads, and added to the acceptance each of them must pass.','goalBatch.gatePanel.checks': 'Checks','goalBatch.gatePanel.checksAt': 'Verdict {{index}} · {{time}}','goalBatch.gatePanel.checksPlanned': 'Not judged yet — these will be checked',@@ -117,6 +121,8 @@ export default {'goalBatch.status.pending': 'Not started','goalBatch.status.running': 'In progress','goalBatch.status.stale': '{{count}} superseded',+ 'goalBatch.skill.forked': 'Plan skill v{{revision}} · new class',+ 'goalBatch.skill.title': 'Plan skill v{{revision}}','goalBatch.template.forked': 'Plan v{{revision}} · new class','goalBatch.template.title': 'Plan v{{revision}}','goalBatch.templatePlain': 'Batch plan',diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.tsindex fef151dc387..56a1ef2a79b 100644--- a/packages/types/src/goal.ts+++ b/packages/types/src/goal.ts@@ -552,6 +552,34 @@ export type GoalRolloutPhase = 'probe' | 'assay' | 'mass' | 'pattern_break' | 'd* coordinator's own gate moves, never by a policy edit — the same rule that* keeps `managerState` server-owned.*/+/**+ * What one break taught the batch: a rule in the batch's expertise domain,+ * which every later unit's acceptance adds as a clause it must meet.+ */+export interface GoalRolloutLearning {+ /**+ * Legacy: a standalone criterion compiled from the rule by an earlier+ * version. Nothing mounts it — later units' acceptance carries `rule` as a+ * clause of its requirement instead.+ */+ criterionId?: string;+ lessonCode?: string;+ lessonId: string;+ /** The round whose gate broke and taught it. */+ revision: number;+ /** The whole correction, as written — `title` is its one-line label. */+ rule?: string;+ title: string;+}++/** The batch's execution plan, kept as a skill in the user's own skill library. */+export interface GoalRolloutPlanSkill {+ /** The skill bundle's document id. */+ id: string;+ /** The skill's name: units load it as `user-skills:<name>`. */+ name: string;+}+export interface GoalRolloutState {/** The gate (Assay) decision node, once decomposition created it. */assayNodeId?: string;@@ -562,6 +590,10 @@ export interface GoalRolloutState {* round that was judged never loses its latest verdict to later rounds.*/gateLog?: GoalRolloutGateEvaluation[];+ /** The expertise domain the batch's breaks teach, once one has. */+ learningDomainId?: string;+ /** Every rule a break taught, oldest first. */+ learnings?: GoalRolloutLearning[];/*** Node ids of the mass tasks the current round released, oldest wave first.* A restarted canary starts a new round and clears it.@@ -569,6 +601,8 @@ export interface GoalRolloutState {massNodeIds?: string[];/** Phase the rollout is in; the coordinator reads this to pick its move. */phase: GoalRolloutPhase;+ /** The execution plan as a user skill; each Template revision is one of its versions. */+ planSkill?: GoalRolloutPlanSkill;/** Node ids of the probe tasks that must run before the gate passes. */probeNodeIds: string[];/** How many roster entries have been materialized (probes + released waves). */diff --git a/src/features/AgentGoals/GoalDecision/index.tsx b/src/features/AgentGoals/GoalDecision/index.tsxindex 93bcac0ad6e..6f317bd7ab8 100644--- a/src/features/AgentGoals/GoalDecision/index.tsx+++ b/src/features/AgentGoals/GoalDecision/index.tsx@@ -325,10 +325,10 @@ const GoalDecisionCase = ({const handleSubmit = useCallback(async (answers: ClarificationAnswer[]) => {const answer = toGateAnswer(decision, answers);- if (!answer) return;+ if (!answer) return false;if (gateAnswerProblem(answer) === 'correctionRequired') {toast.error(t('goalProcess.gate.batchCorrectionRequired'));- return;+ return false;}await onDecide(answer.optionId, answer.resolution?.trim() || undefined);},diff --git a/src/features/AgentGoals/ProcessControl/BatchGate/GateDetail.tsx b/src/features/AgentGoals/ProcessControl/BatchGate/GateDetail.tsxindex cd35cf5349b..6fbc8701b80 100644--- a/src/features/AgentGoals/ProcessControl/BatchGate/GateDetail.tsx+++ b/src/features/AgentGoals/ProcessControl/BatchGate/GateDetail.tsx@@ -2,7 +2,7 @@ import { Flexbox, Icon } from '@lobehub/ui';import { Text } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar } from 'antd-style';import dayjs from 'dayjs';-import { CircleCheck, CircleDashed, CircleX } from 'lucide-react';+import { CircleCheck, CircleDashed, CircleX, GraduationCap } from 'lucide-react';import { memo, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';@@ -37,6 +37,15 @@ const styles = createStaticStyles(({ css }) => ({border-block-start: 1px dashed ${cssVar.colorBorderSecondary};}`,+ /* A rule this gate taught, as a card of its own — it outlives the round. */+ learnedCard: css`+ padding-block: 10px;+ padding-inline: 12px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadiusLG};++ background: ${cssVar.colorBgContainer};+ `,label: css`font-size: 12px;font-weight: 600;@@ -193,6 +202,8 @@ const GateDetail = memo<GateDetailProps>(({ decide, graph, model, onOpenNode, ro);};+ const learned = model.learnings.filter((learning) => learning.revision === round.revision);+// The gate is waiting on a person: answer it here, beside what it found.const pending = round.assayId ? graph.byId[round.assayId]?.decision : undefined;@@ -223,6 +234,45 @@ const GateDetail = memo<GateDetailProps>(({ decide, graph, model, onOpenNode, ro</Section>)}+ {/* What this gate's break taught the batch: a rule the executor reads,+ and a clause every later unit's acceptance must meet. */}+ {learned.length > 0 && (+ <Section title={t('goalBatch.gatePanel.learned')}>+ <Flexbox data-gate-learned gap={8}>+ {learned.map((learning) => (+ <Flexbox+ horizontal+ align={'flex-start'}+ className={styles.learnedCard}+ gap={10}+ key={learning.lessonId}+ >+ <span+ className={styles.unitGlyph}+ style={{ background: cssVar.colorFillTertiary, color: cssVar.colorTextSecondary }}+ >+ <Icon icon={GraduationCap} size={14} />+ </span>+ <Text+ fontSize={13}+ style={{ flex: 1, minWidth: 0, paddingBlockStart: 3, whiteSpace: 'pre-wrap' }}+ >+ {learning.rule ?? learning.title}+ </Text>+ {learning.lessonCode && (+ <Text className={styles.mono} fontSize={12} type={'secondary'}>+ {learning.lessonCode}+ </Text>+ )}+ </Flexbox>+ ))}+ <Text fontSize={12} type={'secondary'}>+ {t('goalBatch.gatePanel.learnedHint')}+ </Text>+ </Flexbox>+ </Section>+ )}+<Sectiontitle={t('goalBatch.gatePanel.checks')}extra={diff --git a/src/features/AgentGoals/ProcessControl/BatchPlan/PlanCompareModal.tsx b/src/features/AgentGoals/ProcessControl/BatchPlan/PlanCompareModal.tsxnew file mode 100644index 00000000000..2a76e57da7b--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/BatchPlan/PlanCompareModal.tsx@@ -0,0 +1,117 @@+'use client';++import { CodeDiff, Flexbox } from '@lobehub/ui';+import { createModal, type ModalInstance, Select, Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { t } from 'i18next';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { DIFF_OPTIONS, withTrailingNewline } from '@/features/Dashboard/WidgetDetail/diffContent';+import { parseSkillMarkdownFrontmatter } from '@/utils/skillMarkdown';++import type { PlanVersion } from './planVersion';++const styles = createStaticStyles(({ css }) => ({+ bar: css`+ padding-block: 10px;+ padding-inline: 16px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};+ background: ${cssVar.colorBgLayout};+ `,+ body: css`+ overflow: auto;+ flex: 1;+ min-height: 0;+ padding: 16px;+ `,+ root: css`+ overflow: hidden;+ display: flex;+ flex-direction: column;++ width: 100%;+ height: 100%;++ background: ${cssVar.colorBgContainer};+ `,+}));++interface PlanCompareProps {+ /** Compared with by default; the version before `target` when omitted. */+ base?: number;+ target: number;+ versions: PlanVersion[];+}++const bodyOf = (version?: PlanVersion) =>+ version ? parseSkillMarkdownFrontmatter(version.content).body : '';++/** Two versions of a batch's plan, side by side as a diff, each one pickable. */+const PlanCompare = memo<PlanCompareProps>(({ base, target, versions }) => {+ const { t } = useTranslation('chat');+ const [to, setTo] = useState(target);+ const [from, setFrom] = useState(+ base ?? versions.findLast((version) => version.revision < target)?.revision ?? target,+ );+ const options = versions.map((version) => ({+ label: `v${version.revision}`,+ value: version.revision,+ }));+ const before = bodyOf(versions.find((version) => version.revision === from));+ const after = bodyOf(versions.find((version) => version.revision === to));++ return (+ <div data-plan-compare className={styles.root}>+ <Flexbox horizontal align={'center'} className={styles.bar} gap={8}>+ <Select+ options={options}+ size={'small'}+ style={{ width: 88 }}+ value={from}+ onChange={(value) => setFrom(Number(value))}+ />+ <Text type={'secondary'}>→</Text>+ <Select+ options={options}+ size={'small'}+ style={{ width: 88 }}+ value={to}+ onChange={(value) => setTo(Number(value))}+ />+ </Flexbox>+ <div className={styles.body}>+ {before.trim() === after.trim() ? (+ <Text type={'secondary'}>{t('goalBatch.planPanel.same', { base: from })}</Text>+ ) : (+ <CodeDiff+ diffOptions={DIFF_OPTIONS}+ language={'markdown'}+ newContent={withTrailingNewline(after)}+ oldContent={withTrailingNewline(before)}+ showHeader={false}+ viewMode={'unified'}+ />+ )}+ </div>+ </div>+ );+});++PlanCompare.displayName = 'GoalPlanCompare';++export const openPlanCompareModal = (props: PlanCompareProps): ModalInstance =>+ createModal({+ content: <PlanCompare {...props} />,+ footer: null,+ styles: {+ content: {+ display: 'flex',+ height: 'min(72vh, 800px)',+ overflow: 'hidden',+ padding: 0,+ },+ },+ title: t('goalBatch.planPanel.compareTitle', { ns: 'chat' }),+ width: 'min(92vw, 960px)',+ });diff --git a/src/features/AgentGoals/ProcessControl/BatchPlan/PlanDetail.tsx b/src/features/AgentGoals/ProcessControl/BatchPlan/PlanDetail.tsxindex 1e18f814e11..c6f64b55ce8 100644--- a/src/features/AgentGoals/ProcessControl/BatchPlan/PlanDetail.tsx+++ b/src/features/AgentGoals/ProcessControl/BatchPlan/PlanDetail.tsx@@ -1,64 +1,56 @@-import { Flexbox, Markdown } from '@lobehub/ui';-import { Segmented, Text } from '@lobehub/ui/base-ui';+import { useEditor } from '@lobehub/editor/react';+import { Flexbox } from '@lobehub/ui';+import { ActionIcon, Text } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar, cx } from 'antd-style';-import { memo, type ReactNode, useState } from 'react';+import { PanelRightCloseIcon, PanelRightOpenIcon } from 'lucide-react';+import { memo, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';+import Loading from '@/components/Loading/CircleLoading';+import ContentViewer from '@/features/AgentSkillDetail/ContentViewer';+import { EditorCanvas } from '@/features/EditorCanvas';+import FileTree from '@/features/FileTree';+import SkillFrontmatterCard from '@/features/Portal/Document/SkillFrontmatterCard';+import { parseSkillMarkdownFrontmatter } from '@/utils/skillMarkdown';+import type { GoalGraphView } from '../goalGraphViewModel';import type { BatchModel, BatchRound } from '../Graph/batchModel';-import { planDiff } from './planDiff';+import { usePlanVersions, usePlanVersionSelection } from './planVersion';+import { skillFileTree } from './skillVersions';/**- * Every version of a batch's plan, for the panel that opens on one of them:- * pick a version, pick what to compare it with (the previous one by default),- * read the line diff, then the version in full.+ * A batch's plan, opened from its node, read the way the product reads a+ * skill document: its frontmatter card (folded — the plan is what one comes+ * to read), then the selected file of the skill on the left — `SKILL.md` on+ * the same canvas documents render on, read-only since a version is a record+ * of a round — and the skill's files on the right.+ * Which version shows, and comparing two, live in the panel's header+ * (`PlanHeaderActions`), out of the document.*/-const styles = createStaticStyles(({ css }) => ({- diff: css`- overflow: hidden;-- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadiusLG};+const SKILL_INDEX = 'SKILL.md';- font-family: ${cssVar.fontFamilyCode};- font-size: 12px;- line-height: 1.7;- `,- line: css`- padding-inline: 10px;- white-space: pre-wrap;- `,- added: css`- color: ${cssVar.colorSuccessText};- background: ${cssVar.colorSuccessBg};- `,- removed: css`- color: ${cssVar.colorErrorText};- text-decoration: line-through;- background: ${cssVar.colorErrorBg};+const styles = createStaticStyles(({ css }) => ({+ files: css`+ overflow-y: auto;+ display: flex;+ flex: none;+ flex-direction: column;++ width: 180px;+ padding: 8px;+ border-inline-start: 1px solid ${cssVar.colorBorderSecondary};`,- same: css`- color: ${cssVar.colorTextTertiary};+ filesFolded: css`+ width: auto;+ padding-inline: 4px;`,- label: css`- font-size: 12px;- font-weight: 600;- color: ${cssVar.colorTextSecondary};+ filesHead: css`+ padding-block: 2px 6px;+ padding-inline: 8px 0;`,}));-const Section = memo<{ children: ReactNode; title: string }>(({ children, title }) => (- <Flexbox gap={6}>- <span className={styles.label}>{title}</span>- {children}- </Flexbox>-));--Section.displayName = 'GoalPlanDetailSection';--const MARK = { added: '+ ', removed: '− ', same: ' ' } as const;-interface PlanDetailProps {graph: GoalGraphView;model: BatchModel;@@ -67,97 +59,91 @@ interface PlanDetailProps {const PlanDetail = memo<PlanDetailProps>(({ graph, model, round }) => {const { t } = useTranslation('chat');- const versions = model.rounds.filter((item) => item.templateId);- const [selected, setSelected] = useState(round.revision);- const [base, setBase] = useState<number | undefined>(undefined);+ const editor = useEditor();+ const [selectedFile, setSelectedFile] = useState(SKILL_INDEX);+ const [filesOpen, setFilesOpen] = useState(true);+ const { selected } = usePlanVersionSelection();+ const { files, isLoading, versions } = usePlanVersions(graph, model);+ const resourceTree = useMemo(() => skillFileTree(files), [files]);+ const contentMap = useMemo(+ () => Object.fromEntries(files.map((file) => [file.path, file.content])),+ [files],+ );- const current = versions.find((item) => item.revision === selected) ?? round;- const earlier = versions.filter((item) => item.revision < current.revision);- // Compare with the previous version unless the reader picked another.- const against = earlier.find((item) => item.revision === base) ?? earlier.at(-1);- const textOf = (item?: BatchRound) =>- (item?.templateId && graph.byId[item.templateId]?.node.description) || '';+ if (isLoading) return <Loading />;- const lines = against ? planDiff(textOf(against), textOf(current)) : [];- const changed = lines.some((line) => line.kind !== 'same');+ const revision = selected ?? round.revision;+ const current = versions.find((version) => version.revision === revision);+ const forked = model.rounds.find((item) => item.revision === revision)?.forked;+ const { body, frontmatter } = parseSkillMarkdownFrontmatter(current?.content);return (- <Flexbox data-plan-detail gap={16}>- {versions.length > 1 && (- <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>- <span className={styles.label}>{t('goalBatch.planPanel.version')}</span>- <Segmented- size={'small'}- value={String(current.revision)}- options={versions.map((item) => ({- label: `v${item.revision}`,- value: String(item.revision),- }))}- onChange={(value) => {- setSelected(Number(value));- setBase(undefined);- }}- />- {earlier.length > 1 && (- <>- <span className={styles.label}>{t('goalBatch.planPanel.compare')}</span>- <Segmented- size={'small'}- value={against ? String(against.revision) : undefined}- options={earlier.map((item) => ({- label: `v${item.revision}`,- value: String(item.revision),- }))}- onChange={(value) => setBase(Number(value))}- />- </>+ <Flexbox data-plan-detail flex={1} style={{ minHeight: 0 }}>+ {(forked || frontmatter) && (+ <Flexbox paddingInline={16} style={{ flex: 'none' }}>+ {forked && (+ <Text fontSize={12} style={{ paddingBlockStart: 12 }} type={'secondary'}>+ {t('goalBatch.planPanel.forked')}+ </Text>)}+ {frontmatter && <SkillFrontmatterCard defaultCollapsed frontmatter={frontmatter} />}</Flexbox>)}-- {current.forked && (- <Text fontSize={12} type={'secondary'}>- {t('goalBatch.planPanel.forked')}- </Text>- )}-- {against ? (- <Section- title={t('goalBatch.planPanel.diff', {- base: against.revision,- revision: current.revision,- })}- >- {changed ? (- <div data-plan-diff className={styles.diff}>- {lines.map((line, index) => (- <div- className={cx(styles.line, styles[line.kind])}- data-diff={line.kind}- key={index}- >- {MARK[line.kind]}- {line.text}- </div>- ))}+ <Flexbox horizontal flex={1} style={{ minHeight: 0 }}>+ <div style={{ flex: 1, minWidth: 0, overflowY: 'auto', paddingBlockEnd: 24 }}>+ {selectedFile === SKILL_INDEX ? (+ <div style={{ paddingInline: 16 }}>+ <EditorCanvas+ editable={false}+ editor={editor}+ editorData={{ content: body }}+ entityId={`${model.planSkill?.id ?? model.batchId}:${revision}`}+ floatingToolbar={false}+ /></div>) : (- <Text fontSize={12} type={'secondary'}>- {t('goalBatch.planPanel.same', { base: against.revision })}- </Text>+ <ContentViewer contentMap={contentMap} key={selectedFile} selectedFile={selectedFile} />)}- </Section>- ) : (- <Text fontSize={12} type={'secondary'}>- {t('goalBatch.planPanel.first')}- </Text>- )}-- <Section title={t('goalBatch.planPanel.full', { revision: current.revision })}>- <Markdown fontSize={13} style={{ flexShrink: 0 }} variant={'chat'}>- {textOf(current)}- </Markdown>- </Section>+ </div>+ {/* The skill's files: folds to a rail so the document can take the width. */}+ <div+ className={cx(styles.files, !filesOpen && styles.filesFolded)}+ data-plan-files={filesOpen ? 'open' : 'folded'}+ >+ {filesOpen ? (+ <>+ <Flexbox+ horizontal+ align={'center'}+ className={styles.filesHead}+ justify={'space-between'}+ >+ <Text fontSize={12} type={'secondary'} weight={500}>+ {t('goalBatch.planPanel.files')}+ </Text>+ <ActionIcon+ icon={PanelRightCloseIcon}+ size={'small'}+ title={t('goalBatch.planPanel.foldFiles')}+ onClick={() => setFilesOpen(false)}+ />+ </Flexbox>+ <FileTree+ resourceTree={resourceTree}+ selectedFile={selectedFile}+ onSelectFile={setSelectedFile}+ />+ </>+ ) : (+ <ActionIcon+ icon={PanelRightOpenIcon}+ size={'small'}+ title={t('goalBatch.planPanel.unfoldFiles')}+ onClick={() => setFilesOpen(true)}+ />+ )}+ </div>+ </Flexbox></Flexbox>);});diff --git a/src/features/AgentGoals/ProcessControl/BatchPlan/PlanHeaderActions.tsx b/src/features/AgentGoals/ProcessControl/BatchPlan/PlanHeaderActions.tsxnew file mode 100644index 00000000000..2aa8305e2e8--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/BatchPlan/PlanHeaderActions.tsx@@ -0,0 +1,70 @@+'use client';++import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@lobechat/const';+import { type DropdownItem, DropdownMenu, Flexbox, Icon } from '@lobehub/ui';+import { ActionIcon, Button } from '@lobehub/ui/base-ui';+import { Check, ChevronDown, GitCompareArrows } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import type { GoalGraphView } from '../goalGraphViewModel';+import type { BatchModel, BatchRound } from '../Graph/batchModel';+import { openPlanCompareModal } from './PlanCompareModal';+import { usePlanVersions, usePlanVersionSelection } from './planVersion';++interface PlanHeaderActionsProps {+ graph: GoalGraphView;+ model: BatchModel;+ round: BatchRound;+}++/**+ * A plan's versions, kept out of the document: which one is shown, tucked+ * into the panel's corner, and a compare that opens the diff in a modal.+ */+const PlanHeaderActions = memo<PlanHeaderActionsProps>(({ graph, model, round }) => {+ const { t } = useTranslation('chat');+ const { selected, setSelected } = usePlanVersionSelection();+ const { versions } = usePlanVersions(graph, model);+ if (versions.length < 2) return null;++ const current = selected ?? round.revision;+ const latest = versions.at(-1)!.revision;+ const items: DropdownItem[] = [...versions].reverse().map((version) => ({+ extra: version.revision === current ? <Icon icon={Check} /> : undefined,+ key: String(version.revision),+ label:+ version.revision === latest+ ? t('goalBatch.planPanel.latest', { revision: version.revision })+ : `v${version.revision}`,+ onClick: () => setSelected(version.revision),+ }));++ return (+ <Flexbox horizontal align={'center'} gap={2}>+ <DropdownMenu items={items} placement={'bottomRight'}>+ <Button+ data-plan-version+ icon={ChevronDown}+ iconPosition={'end'}+ size={'small'}+ type={'text'}+ >+ {`v${current}`}+ </Button>+ </DropdownMenu>+ <ActionIcon+ data-plan-compare-open+ disabled={!versions.some((version) => version.revision < current)}+ icon={GitCompareArrows}+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}+ title={t('goalBatch.planPanel.compare')}+ onClick={() => openPlanCompareModal({ target: current, versions })}+ />+ </Flexbox>+ );+});++PlanHeaderActions.displayName = 'GoalPlanHeaderActions';++export default PlanHeaderActions;diff --git a/src/features/AgentGoals/ProcessControl/BatchPlan/planDiff.test.ts b/src/features/AgentGoals/ProcessControl/BatchPlan/planDiff.test.tsdeleted file mode 100644index 2da76b69de4..00000000000--- a/src/features/AgentGoals/ProcessControl/BatchPlan/planDiff.test.ts+++ /dev/null@@ -1,22 +0,0 @@-import { describe, expect, it } from 'vitest';--import { planDiff } from './planDiff';--describe('planDiff', () => {- it('reads a revision as the previous plan unchanged plus its own section', () => {- expect(planDiff('Step one\nStep two', 'Step one\nStep two\n\n### v2\nSeed first')).toEqual([- { kind: 'same', text: 'Step one' },- { kind: 'same', text: 'Step two' },- { kind: 'added', text: '' },- { kind: 'added', text: '### v2' },- { kind: 'added', text: 'Seed first' },- ]);- });-- it('marks a line the new version dropped as removed', () => {- expect(planDiff('Keep\nDrop', 'Keep')).toEqual([- { kind: 'same', text: 'Keep' },- { kind: 'removed', text: 'Drop' },- ]);- });-});diff --git a/src/features/AgentGoals/ProcessControl/BatchPlan/planDiff.ts b/src/features/AgentGoals/ProcessControl/BatchPlan/planDiff.tsdeleted file mode 100644index 0523c06a2ae..00000000000--- a/src/features/AgentGoals/ProcessControl/BatchPlan/planDiff.ts+++ /dev/null@@ -1,28 +0,0 @@-import { diffLines } from 'diff';--export interface PlanDiffLine {- kind: 'added' | 'removed' | 'same';- text: string;-}--/**- * Line-level difference between two versions of a batch plan. A revision- * carries the previous plan forward and appends its own section, so the usual- * result is the earlier text unchanged and the new section added.- */-export const planDiff = (before = '', after = ''): PlanDiffLine[] =>- // Both sides end with a newline, or a last line followed by new text would- // read as changed rather than kept.- diffLines(`${before.trim()}\n`, `${after.trim()}\n`).flatMap((part) =>- part.value- .replace(/\n$/, '')- .split('\n')- .map((text) => ({- kind: part.added- ? ('added' as const)- : part.removed- ? ('removed' as const)- : ('same' as const),- text,- })),- );diff --git a/src/features/AgentGoals/ProcessControl/BatchPlan/planVersion.tsx b/src/features/AgentGoals/ProcessControl/BatchPlan/planVersion.tsxnew file mode 100644index 00000000000..e22d53ae900--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/BatchPlan/planVersion.tsx@@ -0,0 +1,59 @@+'use client';++import { createContext, memo, type PropsWithChildren, use, useMemo, useState } from 'react';++import { useClientDataSWR } from '@/libs/swr';+import { userSkillService } from '@/services/userSkill';++import type { GoalGraphView } from '../goalGraphViewModel';+import type { BatchModel, BatchRound } from '../Graph/batchModel';+import { skillVersionContent } from './skillVersions';++/**+ * The plan version a reader picked in the panel's header, shared with its body.+ * Undefined until they pick one: the panel shows the round it opened on.+ */+const PlanVersionContext = createContext<{+ selected?: number;+ setSelected: (revision: number) => void;+}>({ setSelected: () => {} });++export const PlanVersionProvider = memo<PropsWithChildren>(({ children }) => {+ const [selected, setSelected] = useState<number>();+ const value = useMemo(() => ({ selected, setSelected }), [selected]);+ return <PlanVersionContext value={value}>{children}</PlanVersionContext>;+});++PlanVersionProvider.displayName = 'GoalPlanVersionProvider';++export const usePlanVersionSelection = () => use(PlanVersionContext);++export interface PlanVersion {+ /** `SKILL.md` as kept, frontmatter included. */+ content: string;+ revision: number;+}++/**+ * Every version of a batch's plan, oldest first. The plan is a skill in the+ * user's library — round N is its version N; a batch from before the plan+ * became a skill falls back to its plan nodes' text.+ */+export const usePlanVersions = (graph: GoalGraphView, model: BatchModel) => {+ const planSkill = model.planSkill;+ // Keyed by the round count, so a revision the panel is open on loads its version.+ const { data: skill, isLoading } = useClientDataSWR(+ planSkill ? ['goal-plan-skill', planSkill.id, model.rounds.length] : null,+ () => userSkillService.get(planSkill!.id),+ );+ const versions: PlanVersion[] = model.rounds+ .filter((item) => item.templateId)+ .map((item: BatchRound) => ({+ content:+ skillVersionContent(skill?.versions, item.revision) ??+ ((item.templateId && graph.byId[item.templateId]?.node.description) || ''),+ revision: item.revision,+ }));+ // A skill's scripts are its latest set; versions keep `SKILL.md` alone.+ return { files: skill?.files ?? [], isLoading: !!planSkill && isLoading, versions };+};diff --git a/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.test.ts b/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.test.tsnew file mode 100644index 00000000000..60944ec487d--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.test.ts@@ -0,0 +1,42 @@+import { describe, expect, it } from 'vitest';++import { skillFileTree, skillVersionContent } from './skillVersions';++describe('skillVersionContent', () => {+ it('reads a kept version whole, frontmatter included', () => {+ const versions = [{ content: '---\nname: plan\n---\nv2 body', version: 2 }];+ expect(skillVersionContent(versions, 2)).toBe('---\nname: plan\n---\nv2 body');+ expect(skillVersionContent(versions, 3)).toBeUndefined();+ });++ it('has nothing to offer when the payload carries no versions', () => {+ expect(skillVersionContent(undefined, 1)).toBeUndefined();+ });+});++describe('skillFileTree', () => {+ it('nests a skill’s files into folders, folders first', () => {+ expect(+ skillFileTree([+ { content: 'b', path: 'scripts/rollback.sql' },+ { content: 'notes', path: 'README.md' },+ { content: 'a', path: 'scripts/check.sh' },+ ]),+ ).toEqual([+ {+ children: [+ { content: 'a', name: 'check.sh', path: 'scripts/check.sh', type: 'file' },+ { content: 'b', name: 'rollback.sql', path: 'scripts/rollback.sql', type: 'file' },+ ],+ name: 'scripts',+ path: 'scripts',+ type: 'directory',+ },+ { content: 'notes', name: 'README.md', path: 'README.md', type: 'file' },+ ]);+ });++ it('is empty for a skill with no files', () => {+ expect(skillFileTree(undefined)).toEqual([]);+ });+});diff --git a/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.ts b/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.tsnew file mode 100644index 00000000000..b9dbeaaab9d--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.ts@@ -0,0 +1,46 @@+import type { SkillResourceTreeNode } from '@lobechat/types';++/**+ * One version's `SKILL.md` as a plan skill kept it — frontmatter included, as+ * the document view shows it. A payload without `versions` (an older server)+ * has none to offer, rather than throwing.+ */+export const skillVersionContent = (+ versions: readonly { content: string; version: number }[] | null | undefined,+ revision: number,+): string | undefined => (versions ?? []).find((version) => version.version === revision)?.content;++/**+ * A skill's files as the file tree takes them: `scripts/check.sh` becomes a+ * `scripts` folder holding `check.sh`. Folders first, then files, by name.+ * `SKILL.md` itself is the tree's root entry, not one of these.+ */+export const skillFileTree = (+ files: readonly { content: string; path: string }[] | null | undefined,+): SkillResourceTreeNode[] => {+ const root: SkillResourceTreeNode[] = [];+ for (const file of files ?? []) {+ const parts = file.path.split('/').filter(Boolean);+ let level = root;+ parts.forEach((name, index) => {+ const path = parts.slice(0, index + 1).join('/');+ if (index === parts.length - 1) {+ level.push({ content: file.content, name, path, type: 'file' });+ return;+ }+ let folder = level.find((node) => node.type === 'directory' && node.name === name);+ if (!folder) {+ folder = { children: [], name, path, type: 'directory' };+ level.push(folder);+ }+ level = folder.children!;+ });+ }+ const sort = (nodes: SkillResourceTreeNode[]): SkillResourceTreeNode[] =>+ nodes+ .map((node) => (node.children ? { ...node, children: sort(node.children) } : node))+ .sort((a, b) =>+ a.type === b.type ? a.name.localeCompare(b.name) : a.type === 'directory' ? -1 : 1,+ );+ return sort(root);+};diff --git a/src/features/AgentGoals/ProcessControl/Graph/batchModel.test.ts b/src/features/AgentGoals/ProcessControl/Graph/batchModel.test.tsindex a12e2f811fc..d8b26af1ea6 100644--- a/src/features/AgentGoals/ProcessControl/Graph/batchModel.test.ts+++ b/src/features/AgentGoals/ProcessControl/Graph/batchModel.test.ts@@ -11,12 +11,21 @@ import { describe, expect, it } from 'vitest';import { buildGoalGraphView } from '../goalGraphViewModel';import { batchGroupId, layoutBatch } from './batchLayout';import {+ batchPlanTitleKey,buildBatchModel,findBatchGate,findBatchPlan,reopenedRows,verdictChecks,} from './batchModel';+import {+ BATCH_SCOPE_COLUMNS,+ batchScopeFrameId,+ batchStageId,+ batchStages,+ layoutBatchScope,+ parseBatchStageId,+} from './batchScopeLayout';const T0 = new Date('2026-10-01T00:00:00Z');const at = (minutes: number) => new Date(T0.getTime() + minutes * 60_000);@@ -601,3 +610,105 @@ describe('buildBatchModel roster', () => {expect(model.waves[0][0]).toMatchObject({ nodeId: 'm3b', state: 'done', title: 'U3' });});});++describe('batchPlanTitleKey', () => {+ const round = { forked: false, revision: 2 } as any;++ it('names the plan as a skill when the batch keeps it as one', () => {+ const model = { planSkill: { id: 'docs_1', name: 'goal-plan-x' } };+ expect(batchPlanTitleKey(model, round)).toBe('goalBatch.skill.title');+ expect(batchPlanTitleKey(model, { ...round, forked: true })).toBe('goalBatch.skill.forked');+ });++ it('keeps the plain plan name for a batch without a plan skill', () => {+ expect(batchPlanTitleKey({}, round)).toBe('goalBatch.template.title');+ });+});++describe('layoutBatchScope', () => {+ it('lays an entered batch out as round frames with its units in a grid', () => {+ const units = ['m3', 'm4', 'm5', 'm6', 'm7', 'm8'];+ const graph = buildGoalGraphView(+ batchSnapshot({+ extraNodes: units.map((id, index) =>+ node(id, 'task', 10, { status: 'resolved', title: `U${index + 3}` }),+ ),+ state: { massNodeIds: units, phase: 'mass', waveIndex: 1 },+ }),+ NOW,+ );+ const model = buildBatchModel(graph, 'batch');+ const members = new Set(['t1', 'a1', 'p1', 'p2', ...units]);+ const { boxes, edges, frames } = layoutBatchScope(graph, model, members);++ // The cold start, then round 1 — one frame each, stacked top to bottom.+ expect(frames.map((frame) => frame.revision)).toEqual([0, 1]);+ const [cold, round1] = frames;+ expect(round1.box.y).toBeGreaterThan(cold.box.y + cold.box.height);+ expect(boxes.p1.y).toBe(boxes.p2.y);+ // Plan over gate on the left, linked; the units in a grid beside them.+ expect(boxes.t1.x).toBe(boxes.a1.x);+ expect(boxes.a1.y).toBeGreaterThan(boxes.t1.y);+ expect(edges).toEqual([expect.objectContaining({ source: 't1', target: 'a1' })]);+ const firstRow = units.slice(0, BATCH_SCOPE_COLUMNS);+ expect(new Set(firstRow.map((id) => boxes[id].y)).size).toBe(1);+ expect(boxes.m4.x).toBeGreaterThan(boxes.m3.x);+ expect(boxes.m3.x).toBeGreaterThan(boxes.t1.x + boxes.t1.width);+ // Six units in four columns wrap to a second row, back at the first column.+ expect(boxes.m7.y).toBeGreaterThan(boxes.m3.y);+ expect(boxes.m7.x).toBe(boxes.m3.x);+ // Every unit sits inside its round's frame.+ for (const id of units) {+ expect(boxes[id].y + boxes[id].height).toBeLessThanOrEqual(round1.box.y + round1.box.height);+ expect(boxes[id].x + boxes[id].width).toBeLessThanOrEqual(round1.box.width);+ }+ expect(boxes[batchScopeFrameId('batch', 1)]).toEqual(round1.box);+ });++ it('keeps a member the rounds do not account for on the map, in the latest round', () => {+ const graph = buildGoalGraphView(+ batchSnapshot({ extraNodes: [node('stray', 'task', 20)], state: {} }),+ NOW,+ );+ const model = buildBatchModel(graph, 'batch');+ const { boxes, frames } = layoutBatchScope(graph, model, new Set(['t1', 'a1', 'stray']));+ const latest = frames.at(-1)!;+ expect(boxes.stray.y).toBeGreaterThanOrEqual(latest.box.y);+ expect(boxes.stray.y + boxes.stray.height).toBeLessThanOrEqual(+ latest.box.y + latest.box.height,+ );+ });+});++describe('batchStages', () => {+ it('splits a batch into the stages a person enters one at a time', () => {+ const units = ['m3', 'm4', 'm5'];+ const graph = buildGoalGraphView(+ batchSnapshot({+ extraNodes: units.map((id, index) =>+ node(id, 'task', 10, { status: 'resolved', title: `U${index + 3}` }),+ ),+ state: { massNodeIds: units, phase: 'mass', waveIndex: 1 },+ }),+ NOW,+ );+ const model = buildBatchModel(graph, 'batch');+ const stages = batchStages(graph, model, new Set(['t1', 'a1', 'p1', 'p2', ...units]));++ expect(stages).toEqual([+ { headers: [], revision: 0, units: ['p1', 'p2'] },+ { headers: ['t1', 'a1'], revision: 1, units },+ ]);+ // Entered alone, a stage lays out as one frame.+ const { frames } = layoutBatchScope(graph, model, new Set(['t1', 'a1', ...units]));+ expect(frames.map((frame) => frame.revision)).toEqual([1]);+ });++ it('names a stage as a scope and reads it back', () => {+ expect(parseBatchStageId(batchStageId('batch-1', 2))).toEqual({+ batchId: 'batch-1',+ revision: 2,+ });+ expect(parseBatchStageId('batch-1')).toBeUndefined();+ });+});diff --git a/src/features/AgentGoals/ProcessControl/Graph/batchModel.ts b/src/features/AgentGoals/ProcessControl/Graph/batchModel.tsindex b3ea08269b1..6a285713dde 100644--- a/src/features/AgentGoals/ProcessControl/Graph/batchModel.ts+++ b/src/features/AgentGoals/ProcessControl/Graph/batchModel.ts@@ -7,7 +7,9 @@ import type {GoalRolloutGateCheck,GoalRolloutGateCheckKey,GoalRolloutGateEvaluation,+ GoalRolloutLearning,GoalRolloutPhase,+ GoalRolloutPlanSkill,} from '@lobechat/types';import { experimentMembers } from '@lobechat/utils/goalGraph';@@ -101,7 +103,11 @@ export interface BatchModel {decisionIds: string[];/** What the gate checks, for a round no verdict has reached yet. */gateChecks: BatchGateCheck[];+ /** What the batch's breaks taught it, oldest first. */+ learnings: GoalRolloutLearning[];phase?: GoalRolloutPhase;+ /** The execution plan as a skill in the user's library; round N is its version N. */+ planSkill?: GoalRolloutPlanSkill;rounds: BatchRound[];/*** The round (1-based revision) each wave belongs to. A released wave belongs@@ -335,7 +341,9 @@ export const buildBatchModel = (graph: GoalGraphView, batchId: string): BatchModbatchId,decisionIds,gateChecks,+ learnings: state?.learnings ?? [],phase: state?.phase,+ planSkill: state?.planSkill,rounds,waveRounds,waves,@@ -445,6 +453,16 @@ export const reopenedRows = (* The batch and round a plan version belongs to, when `nodeId` is one — so the* panel that opens on it can show every version and what changed between them.*/+/** How a round's plan is named: a skill when the batch keeps its plan as one. */+export const batchPlanTitleKey = (model: Pick<BatchModel, 'planSkill'>, round: BatchRound) =>+ model.planSkill+ ? round.forked+ ? ('goalBatch.skill.forked' as const)+ : ('goalBatch.skill.title' as const)+ : round.forked+ ? ('goalBatch.template.forked' as const)+ : ('goalBatch.template.title' as const);+export const findBatchPlan = (graph: GoalGraphView,nodeId: string,diff --git a/src/features/AgentGoals/ProcessControl/Graph/batchScopeLayout.ts b/src/features/AgentGoals/ProcessControl/Graph/batchScopeLayout.tsnew file mode 100644index 00000000000..7a1fbc839cb--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/Graph/batchScopeLayout.ts@@ -0,0 +1,171 @@+import type { GoalGraphView } from '../goalGraphViewModel';+import { BATCH_FRAME_HEAD } from './batchLayout';+import type { BatchModel } from './batchModel';+import { type LayoutBox, NODE_HEIGHT, NODE_WIDTH } from './layout';+import type { MeasuredSizes } from './measuredSizes';++/**+ * A batch entered stage by stage. The batch's "进入" opens one stage — the+ * cold start, or one round — and a stage is dozens of units that do not lead+ * to one another, so a tree would lay them out as one endless row. Here the+ * stage is a frame with its plan and gate on the left and its units in a grid+ * beside them:+ *+ * ┆第 2 轮: 方案 v2 → 闸门 │ ▢ ▢ ▢ ▢ / ▢ ▢ ▢ ▢ …┆+ */++export const BATCH_SCOPE_COLUMNS = 4;+const PAD = 16;+const GAP = 16;+const SECTION_GAP = 32;+const HEADER_WIDTH = 250;+const HEADER_GAP = 32;++export interface BatchScopeFrame {+ box: LayoutBox;+ id: string;+ /** 0 for the cold start, else the round's revision. */+ revision: number;+}++export interface BatchScopeLayout {+ boxes: Record<string, LayoutBox>;+ /** Plan → gate inside each round, the only links the grid draws. */+ edges: { id: string; source: string; target: string }[];+ frames: BatchScopeFrame[];+}++export const batchScopeFrameId = (batchId: string, revision: number) =>+ `${batchId}::scope-${revision}`;++/** One stage of a batch: the cold start (revision 0) or a round, with what ran in it. */+export interface BatchStage {+ /** The round's plan and gate, top to bottom; none for the cold start. */+ headers: string[];+ revision: number;+ units: string[];+}++/** A stage a person can enter on its own, as a navigation scope. */+export const batchStageId = (batchId: string, revision: number) => `${batchId}::stage-${revision}`;++export const parseBatchStageId = (id: string) => {+ const match = /^(.+)::stage-(\d+)$/.exec(id);+ return match ? { batchId: match[1], revision: Number(match[2]) } : undefined;+};++/**+ * The batch's stages with the members each holds. `nodeIds`: the members on+ * the map. A member the rounds do not account for (a side decision without a+ * subject, a unit of an unknown wave) joins the latest round, so nothing in the+ * batch drops off the map.+ */+export const batchStages = (+ graph: GoalGraphView,+ model: BatchModel,+ nodeIds: ReadonlySet<string>,+): BatchStage[] => {+ const placed = new Set<string>();+ const take = (ids: (string | undefined)[]) =>+ ids.filter((id): id is string => {+ if (!id || !nodeIds.has(id) || placed.has(id)) return false;+ placed.add(id);+ return true;+ });++ const [first] = model.rounds;+ const sections: BatchStage[] = [];+ if (first.probes.length)+ sections.push({+ headers: [],+ revision: 0,+ units: take(first.probes.map((probe) => probe.nodeId)),+ });+ for (const round of model.rounds) {+ const headers = take([round.templateId, round.assayId]);+ const units = take([+ ...(round.revision > 1 ? round.probes.map((probe) => probe.nodeId) : []),+ ...model.waves.flatMap((cells, wave) =>+ model.waveRounds[wave] === round.revision ? cells.map((cell) => cell.nodeId) : [],+ ),+ ]);+ sections.push({ headers, revision: round.revision, units });+ }+ // Side decisions sit with the units of the round their subject ran in.+ const sectionOf = new Map<string, BatchStage>();+ for (const section of sections) for (const id of section.units) sectionOf.set(id, section);+ const latest = sections.at(-1)!;+ for (const id of model.decisionIds) {+ const subject = graph.byId[id]?.gateSubjectId;+ const [taken] = take([id]);+ if (taken) (subject ? (sectionOf.get(subject) ?? latest) : latest).units.push(taken);+ }+ latest.units.push(...take([...nodeIds]));+ return sections;+};++/** Lays out the stages of `nodeIds` — one stage when a person entered one. */+export const layoutBatchScope = (+ graph: GoalGraphView,+ model: BatchModel,+ nodeIds: ReadonlySet<string>,+ sizes: MeasuredSizes = {},+): BatchScopeLayout => {+ const sections = batchStages(graph, model, nodeIds);+ const placed = sections.flatMap((section) => [...section.headers, ...section.units]);++ const kindOf = (id: string) => graph.byId[id]?.node.kind ?? 'task';+ const widthOf = (id: string) => sizes[id]?.width ?? NODE_WIDTH[kindOf(id)];+ const heightOf = (id: string) => sizes[id]?.height ?? NODE_HEIGHT[kindOf(id)];++ const cell = Math.max(NODE_WIDTH.task, ...placed.map(widthOf));+ // As many columns as the fullest stage needs, up to the grid's width.+ const columns = Math.min(+ BATCH_SCOPE_COLUMNS,+ Math.max(1, ...sections.map((section) => section.units.length)),+ );+ const gridWidth = columns * cell + (columns - 1) * GAP;+ const hasHeaders = sections.some((section) => section.headers.length);+ const gridX = PAD + (hasHeaders ? HEADER_WIDTH + HEADER_GAP : 0);+ const frameWidth = gridX + gridWidth + PAD;++ const boxes: Record<string, LayoutBox> = {};+ const frames: BatchScopeFrame[] = [];+ const edges: BatchScopeLayout['edges'] = [];+ let top = 0;+ for (const section of sections) {+ if (!section.headers.length && !section.units.length) continue;+ const bodyTop = top + BATCH_FRAME_HEAD;++ let headerBottom = bodyTop;+ section.headers.forEach((id, index) => {+ boxes[id] = { height: heightOf(id), width: HEADER_WIDTH, x: PAD, y: headerBottom };+ headerBottom += heightOf(id) + GAP;+ const above = section.headers[index - 1];+ if (above) edges.push({ id: `${model.batchId}::scope-e-${id}`, source: above, target: id });+ });++ let rowTop = bodyTop;+ for (let start = 0; start < section.units.length; start += columns) {+ const row = section.units.slice(start, start + columns);+ row.forEach((id, column) => {+ boxes[id] = {+ height: heightOf(id),+ width: widthOf(id),+ x: gridX + column * (cell + GAP),+ y: rowTop,+ };+ });+ rowTop += Math.max(...row.map(heightOf)) + GAP;+ }++ const bottom = Math.max(headerBottom, rowTop) - GAP + PAD;+ const id = batchScopeFrameId(model.batchId, section.revision);+ const box = { height: bottom - top, width: frameWidth, x: 0, y: top };+ frames.push({ box, id, revision: section.revision });+ boxes[id] = box;+ top = bottom + SECTION_GAP;+ }++ return { boxes, edges, frames };+};diff --git a/src/features/AgentGoals/ProcessControl/Graph/index.tsx b/src/features/AgentGoals/ProcessControl/Graph/index.tsxindex 823bffd99b0..bdecc85e5f8 100644--- a/src/features/AgentGoals/ProcessControl/Graph/index.tsx+++ b/src/features/AgentGoals/ProcessControl/Graph/index.tsx@@ -46,7 +46,7 @@ import {isRunningNode,scopeGraphView,} from '../goalGraphViewModel';-import { GATE_COLOR, KindDot } from '../shared';+import { GATE_COLOR, KindDot, SKILL_COLOR, SKILL_ICON } from '../shared';import {BatchExperimentProbeGroup,BatchRoundFrame,@@ -59,10 +59,12 @@ import { type BatchLayout, layoutBatch } from './batchLayout';import {type BatchGateState,type BatchModel,+ batchPlanTitleKey,type BatchRound,buildBatchModel,verdictChecks,} from './batchModel';+import { batchStageId, batchStages, layoutBatchScope } from './batchScopeLayout';import { edgeDirection } from './edgeRouting';import ExperimentGroup, { type ExperimentGroupData } from './ExperimentGroup';import { batchContainerStatus } from './experimentStatus';@@ -448,12 +450,22 @@ const useBatchCopy = () => {: t('goalBatch.gate.title'),};},- template: (round: BatchRound, view: GoalNodeView): GraphNodeData['presentation'] => ({+ template: (+ round: BatchRound,+ view: GoalNodeView,+ model: BatchModel,+ ): GraphNodeData['presentation'] => ({chip: null,- subtitle: view.node.description?.split('\n')[0] ?? '',- title: round.forked- ? t('goalBatch.template.forked', { revision: round.revision })- : t('goalBatch.template.title', { revision: round.revision }),+ // A plan kept as a skill reads as the skill every unit loads — its icon,+ // its colour, its identifier — not as a conclusion.+ ...(model.planSkill+ ? {+ icon: SKILL_ICON,+ palette: SKILL_COLOR,+ subtitle: `user-skills:${model.planSkill.name}`,+ }+ : { subtitle: view.node.description?.split('\n')[0] ?? '' }),+ title: t(batchPlanTitleKey(model, round), { revision: round.revision }),}),}),[t, checkCopy],@@ -483,6 +495,8 @@ const Canvas = memo<onInspect: (id: string) => void;onEnter: (id: string) => void;navigation?: ReactNode;+ /** The batch entered on its own: its units as a grid, round by round. */+ scopeBatch?: BatchModel;}>(({@@ -500,6 +514,7 @@ const Canvas = memo<onInspect,onEnter,navigation,+ scopeBatch,view,}) => {const { fitView, getInternalNode, getViewport, setCenter } = useReactFlow();@@ -541,15 +556,15 @@ const Canvas = memo<}, [graph, collapsed]);const batchRoles = useMemo(() => {const result = new Map<string, BatchRole>();- for (const { layout, model } of batches.values()) {- if (!layout) continue;+ const open = [...batches.values()].flatMap(({ layout, model }) => (layout ? [model] : []));+ for (const model of scopeBatch ? [...open, scopeBatch] : open) {for (const round of model.rounds) {if (round.templateId) result.set(round.templateId, { kind: 'template', model, round });if (round.assayId) result.set(round.assayId, { kind: 'assay', model, round });}}return result;- }, [batches]);+ }, [batches, scopeBatch]);const containerLayouts = useMemo(() =>new Map(@@ -591,13 +606,23 @@ const Canvas = memo<const handleNodesChange = useCallback((changes: NodeChange[]) => {setMeasuredSizes((previous) => mergeMeasuredSizes(previous, changes));}, []);- const positions = hasContainers- ? map.boxes- : layoutGraph(- baseNodes.filter((node) => visibleIds.has(node.id)),- [...graph.edges, ...bridges.map((bridge) => ({ ...bridge, kind: 'leads_to' as const }))],- measuredSizes,- );+ const scopeLayout = useMemo(+ () =>+ scopeBatch ? layoutBatchScope(graph, scopeBatch, visibleIds, measuredSizes) : undefined,+ [graph, scopeBatch, visibleIds, measuredSizes],+ );+ const positions = scopeLayout+ ? scopeLayout.boxes+ : hasContainers+ ? map.boxes+ : layoutGraph(+ baseNodes.filter((node) => visibleIds.has(node.id)),+ [+ ...graph.edges,+ ...bridges.map((bridge) => ({ ...bridge, kind: 'leads_to' as const })),+ ],+ measuredSizes,+ );const ghosts = useMemo(() => {if (!planning) return [];@@ -687,7 +712,8 @@ const Canvas = memo<const box = positions[item.node.id];const batchRole = batchRoles.get(item.node.id);const inBatch =- !!map.parents.get(item.node.id) && batches.has(map.parents.get(item.node.id)!);+ !!scopeBatch ||+ (!!map.parents.get(item.node.id) && batches.has(map.parents.get(item.node.id)!));const waiting = item.node.kind === 'decision' && item.node.status === 'waiting';// Inside a batch a decision is a plain card: the hand glyph and a blue// chip say a person is needed, without the orange gate frame.@@ -704,18 +730,21 @@ const Canvas = memo<// Once the report marked a mainline, everything off it is context too.// Inside a batch the gate's own chip says it is locked; a settled// side decision steps back instead.- dim: inBatch- ? !batchRole && item.node.status === 'resolved'- : isNodeDimmed({- blocked: item.node.status === 'proposed' && item.blockers.length > 0,- emphasis,- highlighted,- }),+ // An entered batch is the units themselves: only a superseded one steps back.+ dim: scopeBatch+ ? item.isStale+ : inBatch+ ? !batchRole && item.node.status === 'resolved'+ : isNodeDimmed({+ blocked: item.node.status === 'proposed' && item.blockers.length > 0,+ emphasis,+ highlighted,+ }),highlighted,isGate,presentation:batchRole?.kind === 'template'- ? batchCopy.template(batchRole.round, item)+ ? batchCopy.template(batchRole.round, item, batchRole.model): batchRole?.kind === 'assay'? batchCopy.gate(batchRole.round, batchRole.model): inBatch && item.node.kind === 'decision'@@ -797,6 +826,7 @@ const Canvas = memo<batchCopy,openBatchIds,placeInMap,+ scopeBatch,],);@@ -804,8 +834,8 @@ const Canvas = memo<// round's waves and the frame each round's nodes sit in. They are not graph// nodes; their cards and squares open the real node underneath.const batchFlowNodes: FlowNode[] = useMemo(- () =>- [...batches].flatMap(([batchId, { layout, model }]) => {+ () => [+ ...[...batches].flatMap(([batchId, { layout, model }]) => {if (!layout || !visibleIds.has(batchId)) return [];const [first] = model.rounds;// The roster waves a round owns, keeping each one's roster position.@@ -834,14 +864,14 @@ const Canvas = memo<const data =group.kind === 'experimentProbe'? {- onEnter: () => onEnter(batchId),+ onEnter: () => onEnter(batchStageId(batchId, 0)),onSelect,probes: first.probes,started: first.probes.some((probe) => probe.state !== 'backlog'),views: graph.byId,}: ({- onEnter: () => onEnter(batchId),+ onEnter: () => onEnter(batchStageId(batchId, group.revision)),onSelect,probes: round.probes,revision: group.revision,@@ -862,6 +892,7 @@ const Canvas = memo<} satisfies FlowNode;});}),+ ],[batches, visibleIds, graph.byId, onEnter, onSelect, placeInMap],);@@ -880,7 +911,9 @@ const Canvas = memo<const markerOf = (tone: EdgeTone) =>tone === 'mainline' ? mainlineMarker : tone === 'detour' ? detourMarker : marker;const lanes = new Map<string, number>();- const direct = (hasContainers ? map.edges : graph.edges)+ // Inside an entered batch the units do not lead to one another: the grid+ // draws only each round's plan → gate.+ const direct = (scopeLayout ? [] : hasContainers ? map.edges : graph.edges).filter((edge) => visibleIds.has(edge.sourceNodeId) && visibleIds.has(edge.targetNodeId)).map((edge) => {// An open batch has no card of its own: a link to it lands on its first piece.@@ -960,8 +993,20 @@ const Canvas = memo<}) satisfies FlowEdge,),);- return [...direct, ...bridged, ...chained];+ const scoped = (scopeLayout?.edges ?? []).map(+ (edge) =>+ ({+ data: { lane: 0 },+ id: edge.id,+ markerEnd: marker,+ source: edge.source,+ target: edge.target,+ type: 'exploration',+ }) satisfies FlowEdge,+ );+ return [...direct, ...(scopeLayout ? [] : bridged), ...chained, ...scoped];}, [+ scopeLayout,batches,graph,visibleIds,@@ -1111,15 +1156,45 @@ Canvas.displayName = 'GoalGraphCanvas';const Graph = memo<GraphProps>(({ extra, fullscreen = false, onFullscreenChange, ...props }) => {const { t } = useTranslation('chat');- const navigation = useExplorationNavigation(props.graph.goal.id, {- nodes: props.graph.nodes.map((item) => item.node),- edges: props.graph.edges,- });+ const shape = useMemo(+ () => ({ edges: props.graph.edges, nodes: props.graph.nodes.map((item) => item.node) }),+ [props.graph],+ );+ // A batch is entered one stage at a time — its cold start, or one round —+ // so each stage is a scope of its own, read off the whole graph.+ const batchStageScopes = useMemo(() => {+ const result = new Map<string, { members: Set<string>; model: BatchModel; revision: number }>();+ for (const item of props.graph.nodes) {+ if (item.node.kind !== 'batch') continue;+ const model = buildBatchModel(props.graph, item.node.id);+ const members = experimentMembers(shape, item.node.id);+ for (const stage of batchStages(props.graph, model, members))+ result.set(batchStageId(item.node.id, stage.revision), {+ members: new Set([...stage.headers, ...stage.units]),+ model,+ revision: stage.revision,+ });+ }+ return result;+ }, [props.graph, shape]);+ const navigation = useExplorationNavigation(+ props.graph.goal.id,+ shape,+ (id) => batchStageScopes.get(id)?.members,+ );const { collapsed, scopeId } = navigation;const scopeIds = new Set(navigation.nodes.map((node) => node.id));const scopedGraph: GoalGraphView = scopeId? scopeGraphView(props.graph, scopeIds, navigation.edges): props.graph;+ const scopeStage = scopeId ? batchStageScopes.get(scopeId) : undefined;+ const scopeBatch = scopeStage?.model;+ const stageLabel = (revision: number) =>+ revision ? t('goalBatch.round.title', { revision }) : t('goalBatch.probes.title');+ const scopeLabel = (id: string) => {+ const stage = batchStageScopes.get(id);+ return stage ? stageLabel(stage.revision) : props.graph.byId[id]?.node.title;+ };const openNode = useChatStore((s) => s.openGoalNode);const [preferredView, setView] = useState<GraphViewMode>('stage');const stageIsWholeMap = isStageWholeMap(props.graph);@@ -1187,11 +1262,11 @@ const Graph = memo<GraphProps>(({ extra, fullscreen = false, onFullscreenChange,<ChevronRight size={14} />{index === navigation.path.length - 1 ? (<Text aria-current={'page'} fontSize={12}>- {props.graph.byId[id]?.node.title}+ {scopeLabel(id)}</Text>) : (<Button size={'small'} onClick={() => navigation.backTo(index + 1)}>- {props.graph.byId[id]?.node.title}+ {scopeLabel(id)}</Button>)}</Flexbox>@@ -1301,6 +1376,7 @@ const Graph = memo<GraphProps>(({ extra, fullscreen = false, onFullscreenChange,key={scopeId ?? 'root'}planning={scopeId ? false : props.planning}refitKey={showPortal}+ scopeBatch={scopeBatch}view={scopeId ? 'all' : view}navigation={<Flexbox gap={8}>@@ -1365,6 +1441,7 @@ const Graph = memo<GraphProps>(({ extra, fullscreen = false, onFullscreenChange,key={scopeId ?? 'root'}navigation={breadcrumbs}planning={scopeId ? false : props.planning}+ scopeBatch={scopeBatch}view={scopeId ? 'all' : view}onEnter={navigation.enter}onInspect={(id) => openNode(props.graph.goal.id, id)}diff --git a/src/features/AgentGoals/ProcessControl/Graph/useExplorationNavigation.ts b/src/features/AgentGoals/ProcessControl/Graph/useExplorationNavigation.tsindex ab3ee5fa2f5..1709392bdcb 100644--- a/src/features/AgentGoals/ProcessControl/Graph/useExplorationNavigation.ts+++ b/src/features/AgentGoals/ProcessControl/Graph/useExplorationNavigation.ts@@ -15,13 +15,27 @@ type Graph = Pick<GoalGraphSnapshot, 'nodes' | 'edges'>;*/const foldable = (node: Graph['nodes'][number]) => node.kind !== 'batch';-export const useExplorationNavigation = (goalId: string, graph: Graph) => {+/**+ * A scope that is not a node: a batch's stage (`batchStageId`). Returns its+ * members, or undefined when `id` is no such scope.+ */+export type ScopeMembers = (id: string) => ReadonlySet<string> | undefined;++export const useExplorationNavigation = (+ goalId: string,+ graph: Graph,+ virtualScope?: ScopeMembers,+) => {const [state, setState] = useState({ goalId, path: [] as string[], toggled: new Set<string>() });if (state.goalId !== goalId) setState({ goalId, path: [], toggled: new Set() });- const path = state.path.filter((id) => graph.nodes.some((n) => n.id === id));+ const path = state.path.filter(+ (id) => graph.nodes.some((n) => n.id === id) || !!virtualScope?.(id),+ );const scopeId = path.at(-1);- const scopeIds = scopeId ? experimentMembers(graph, scopeId) : undefined;+ const scopeIds = scopeId+ ? (virtualScope?.(scopeId) ?? experimentMembers(graph, scopeId))+ : undefined;const nodes = graph.nodes.filter((node) => !scopeIds || scopeIds.has(node.id));const ids = new Set(nodes.map((node) => node.id));const edges = graph.edges.filter(@@ -47,7 +61,7 @@ export const useExplorationNavigation = (goalId: string, graph: Graph) => {path,scopeId,enter: (id: string) => {- if (!containers.some((node) => node.id === id)) return;+ if (!containers.some((node) => node.id === id) && !virtualScope?.(id)) return;setState((previous) => ({ ...previous, path: [...path, id] }));},backTo: (depth: number) =>diff --git a/src/features/AgentGoals/ProcessControl/shared.tsx b/src/features/AgentGoals/ProcessControl/shared.tsxindex 45b14229868..6b39a3a2f45 100644--- a/src/features/AgentGoals/ProcessControl/shared.tsx+++ b/src/features/AgentGoals/ProcessControl/shared.tsx@@ -1,5 +1,6 @@import { Icon } from '@lobehub/ui';import { Text } from '@lobehub/ui/base-ui';+import { SkillsIcon } from '@lobehub/ui/icons';import { createStaticStyles, cssVar } from 'antd-style';import {Boxes,@@ -42,6 +43,15 @@ export const KIND_COLOR: Record<GoalGraphNodeKind, { line: string; soft: string*/export const GATE_COLOR = { line: cssVar.cyan10, soft: cssVar.cyan3 };+/**+ * A batch's execution plan kept as a skill in the user's library. It is the+ * graph's `finding` node underneath, but it reads as a skill — the thing every+ * unit loads — not as a conclusion. It wears the color skills wear everywhere+ * else (the chat input's skill tags), so it reads as the same thing.+ */+export const SKILL_COLOR = { line: cssVar.colorSuccess, soft: cssVar.colorSuccessBg };+export const SKILL_ICON = SkillsIcon as unknown as LucideIcon;+export const KIND_ICON: Record<GoalGraphNodeKind, LucideIcon> = {batch: Boxes,decision: GitBranch,diff --git a/src/features/ClarificationQuestions/index.tsx b/src/features/ClarificationQuestions/index.tsxindex 8b2a95983c4..b880aab7916 100644--- a/src/features/ClarificationQuestions/index.tsx+++ b/src/features/ClarificationQuestions/index.tsx@@ -27,6 +27,7 @@ import {readClarificationDraft,writeClarificationDraft,} from './draftStorage';+import { ClarificationAnswerDeclined, submitClarification } from './submit';import { useAskUserLabels } from './useAskUserLabels';export type { ClarificationAnswer, ClarificationQuestion } from './answers';@@ -47,7 +48,11 @@ export interface ClarificationQuestionsProps {* no skip at all.*/onSkip?: () => Promise<void> | void;- onSubmit: (answers: ClarificationAnswer[]) => Promise<void> | void;+ /**+ * Sends the answers. Return `false` to decline them unsent (after telling the+ * user why): the form stays editable and keeps the draft.+ */+ onSubmit: (answers: ClarificationAnswer[]) => Promise<boolean | void> | boolean | void;questions: ClarificationQuestion[];/** Defaults to `true`; pass `false` when every question is optional. */requireAllAnswered?: boolean;@@ -114,11 +119,15 @@ const ClarificationQuestions = memo<ClarificationQuestionsProps>(if (!onSkip) return;await onSkip();} else if (action.type === 'submit')- await onSubmit(toClarificationAnswers(questions, action.payload ?? {}));+ await submitClarification(+ onSubmit,+ toClarificationAnswers(questions, action.payload ?? {}),+ );// Sent: nothing left to restore. A failed send keeps the draft.if (storageKey) clearClarificationDraft(storageKey);} catch (error) {- setFailed(true);+ // A declined answer was never sent: the host already said why.+ if (!(error instanceof ClarificationAnswerDeclined)) setFailed(true);// Rethrow so the form leaves its submitting state and can be retried.throw error;}diff --git a/src/features/ClarificationQuestions/submit.test.ts b/src/features/ClarificationQuestions/submit.test.tsnew file mode 100644index 00000000000..488631e8256--- /dev/null+++ b/src/features/ClarificationQuestions/submit.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it } from 'vitest';++import { ClarificationAnswerDeclined, submitClarification } from './submit';++describe('submitClarification', () => {+ it('resolves when the host sends the answers', async () => {+ await expect(submitClarification(async () => {}, [])).resolves.toBeUndefined();+ await expect(submitClarification(() => true, [])).resolves.toBeUndefined();+ });++ // A gate that needs a written correction refuses an empty one with a toast;+ // the form must leave its submitting state instead of spinning forever.+ it('throws a decline when the host refuses the answers', async () => {+ await expect(submitClarification(async () => false, [])).rejects.toBeInstanceOf(+ ClarificationAnswerDeclined,+ );+ });++ it('passes a failed send through unchanged', async () => {+ const error = new Error('network');+ await expect(+ submitClarification(async () => {+ throw error;+ }, []),+ ).rejects.toBe(error);+ });+});diff --git a/src/features/ClarificationQuestions/submit.ts b/src/features/ClarificationQuestions/submit.tsnew file mode 100644index 00000000000..2e0d430d58b--- /dev/null+++ b/src/features/ClarificationQuestions/submit.ts@@ -0,0 +1,23 @@+/**+ * The host refused an answer before sending it, and already told the user why+ * (a toast). Not a failed send: the form leaves its submitting state and keeps+ * the draft, without a "could not send" alert.+ */+export class ClarificationAnswerDeclined extends Error {+ constructor() {+ super('The host declined this answer before sending it');+ this.name = 'ClarificationAnswerDeclined';+ }+}++/**+ * Hands the answers to the host. A host that returns `false` declined them:+ * that throws, since the form only leaves its submitting state on a throw — a+ * normal return means "sent, wait for the card to settle".+ */+export const submitClarification = async <T>(+ onSubmit: (answers: T) => Promise<boolean | void> | boolean | void,+ answers: T,+) => {+ if ((await onSubmit(answers)) === false) throw new ClarificationAnswerDeclined();+};diff --git a/src/features/Portal/Document/Body.tsx b/src/features/Portal/Document/Body.tsxindex a78bc43a602..005f68a36af 100644--- a/src/features/Portal/Document/Body.tsx+++ b/src/features/Portal/Document/Body.tsx@@ -23,7 +23,6 @@ import { getDocumentRenderMode } from '@/utils/documentRenderMode';import {getSkillMarkdownMetadataError,parseSkillMarkdownFrontmatterFields,- parseSkillMarkdownMetadata,} from '@/utils/skillMarkdown';import {@@ -33,6 +32,7 @@ import {} from './documentViewContext';import EditorCanvas from './EditorCanvas';import FooterActions from './FooterActions';+import SkillFrontmatterCard from './SkillFrontmatterCard';import TodoList from './TodoList';import { useHighlightSave } from './useHighlightSave';@@ -47,35 +47,6 @@ const styles = createStaticStyles(({ css }) => ({overflow: auto;flex: 1;`,- frontmatter: css`- margin-block: 16px 12px;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: 8px;- background: ${cssVar.colorBgContainer};- `,- metadataKey: css`- flex-shrink: 0;- width: 112px;- font-family: ${cssVar.fontFamilyCode};- color: ${cssVar.colorTextSecondary};- `,- metadataRow: css`- padding-block: 10px;- padding-inline: 12px;-- &:not(:last-child) {- border-block-end: 1px solid ${cssVar.colorBorderSecondary};- }- `,- metadataValue: css`- min-width: 0;- white-space: pre-wrap;- `,- sectionHeader: css`- padding-block: 10px;- padding-inline: 12px;- border-block-end: 1px solid ${cssVar.colorBorderSecondary};- `,textArea: css`font-family: ${cssVar.fontFamilyCode};`,@@ -88,7 +59,6 @@ interface SkillFrontmatterBlockProps {const SkillFrontmatterBlock = memo<SkillFrontmatterBlockProps>(({ documentId, frontmatter }) => {const { t } = useTranslation('editor');- const metadata = useMemo(() => parseSkillMarkdownMetadata(frontmatter), [frontmatter]);const currentName = useMemo(() => parseSkillMarkdownFrontmatterFields(frontmatter).name,[frontmatter],@@ -154,10 +124,10 @@ const SkillFrontmatterBlock = memo<SkillFrontmatterBlockProps>(({ documentId, fr}, [currentName, documentId, draft, performSave, t, updateSkillFrontmatter]);return (- <Flexbox className={styles.frontmatter}>- <Flexbox horizontal align="center" className={styles.sectionHeader} justify="space-between">- <Text type="secondary">{t('skillFrontmatter.title')}</Text>- {editing ? (+ <SkillFrontmatterCard+ frontmatter={frontmatter}+ extra={+ editing ? (<Flexbox horizontal gap={8}><Button icon={XIcon} size="small" onClick={handleCancel}>{t('cancel')}@@ -179,9 +149,10 @@ const SkillFrontmatterBlock = memo<SkillFrontmatterBlockProps>(({ documentId, frtitle={t('skillFrontmatter.edit')}onClick={handleEdit}/>- )}- </Flexbox>- {editing ? (+ )+ }+ >+ {editing && (<Flexbox gap={8} padding={12}>{/* Raw YAML is only exposed in edit mode so users can keep advanced frontmatter syntax. */}<TextArea@@ -196,19 +167,8 @@ const SkillFrontmatterBlock = memo<SkillFrontmatterBlockProps>(({ documentId, fr/>{error && <Text type="danger">{error}</Text>}</Flexbox>- ) : metadata.length > 0 ? (- metadata.map((item) => (- <Flexbox horizontal align="flex-start" className={styles.metadataRow} key={item.key}>- <Text className={styles.metadataKey}>{item.key}</Text>- <Text className={styles.metadataValue}>{item.value}</Text>- </Flexbox>- ))- ) : (- <Flexbox className={styles.metadataRow}>- <Text type="secondary">{t('skillFrontmatter.empty')}</Text>- </Flexbox>)}- </Flexbox>+ </SkillFrontmatterCard>);});diff --git a/src/features/Portal/Document/SkillFrontmatterCard.tsx b/src/features/Portal/Document/SkillFrontmatterCard.tsxnew file mode 100644index 00000000000..fa64bb2d604--- /dev/null+++ b/src/features/Portal/Document/SkillFrontmatterCard.tsx@@ -0,0 +1,129 @@+'use client';++import { Flexbox, Icon } from '@lobehub/ui';+import { Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { ChevronRight } from 'lucide-react';+import { memo, type ReactNode, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { parseSkillMarkdownMetadata } from '@/utils/skillMarkdown';++const styles = createStaticStyles(({ css }) => ({+ frontmatter: css`+ margin-block: 16px 12px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: 8px;+ background: ${cssVar.colorBgContainer};+ `,+ metadataKey: css`+ flex-shrink: 0;+ width: 112px;+ font-family: ${cssVar.fontFamilyCode};+ color: ${cssVar.colorTextSecondary};+ `,+ metadataRow: css`+ padding-block: 10px;+ padding-inline: 12px;++ &:not(:last-child) {+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};+ }+ `,+ metadataValue: css`+ min-width: 0;+ white-space: pre-wrap;+ `,+ sectionHeaderCollapsed: css`+ border-block-end: none;+ `,+ sectionHeaderToggle: css`+ cursor: pointer;+ user-select: none;+ `,+ sectionHeader: css`+ padding-block: 10px;+ padding-inline: 12px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};+ `,+}));++interface SkillFrontmatterCardProps {+ /** Replaces the key/value rows, e.g. the raw YAML while editing. */+ children?: ReactNode;+ /** Starts folded to its header; the header toggles it. */+ defaultCollapsed?: boolean;+ /** The header's right side, e.g. an edit action. */+ extra?: ReactNode;+ frontmatter: string;+}++/**+ * A skill's frontmatter as a document shows it: a card of key/value rows above+ * the body. Read-only on its own; a host adds editing through `extra`.+ */+const SkillFrontmatterCard = memo<SkillFrontmatterCardProps>(+ ({ children, defaultCollapsed, extra, frontmatter }) => {+ const { t } = useTranslation('editor');+ const metadata = useMemo(() => parseSkillMarkdownMetadata(frontmatter), [frontmatter]);+ const collapsible = defaultCollapsed !== undefined;+ const [collapsed, setCollapsed] = useState(!!defaultCollapsed);++ return (+ <Flexbox className={styles.frontmatter} data-collapsed={collapsed || undefined}>+ <Flexbox+ horizontal+ align="center"+ aria-expanded={collapsible ? !collapsed : undefined}+ justify="space-between"+ role={collapsible ? 'button' : undefined}+ className={cx(+ styles.sectionHeader,+ collapsible && styles.sectionHeaderToggle,+ collapsed && styles.sectionHeaderCollapsed,+ )}+ onClick={collapsible ? () => setCollapsed((value) => !value) : undefined}+ >+ <Flexbox horizontal align="center" gap={6}>+ {collapsible && (+ <Icon+ icon={ChevronRight}+ size={14}+ style={{+ transform: collapsed ? undefined : 'rotate(90deg)',+ transition: 'transform 0.15s',+ }}+ />+ )}+ <Text type="secondary">{t('skillFrontmatter.title')}</Text>+ </Flexbox>+ {extra}+ </Flexbox>+ {collapsed+ ? null+ : (children ??+ (metadata.length > 0 ? (+ metadata.map((item) => (+ <Flexbox+ horizontal+ align="flex-start"+ className={styles.metadataRow}+ key={item.key}+ >+ <Text className={styles.metadataKey}>{item.key}</Text>+ <Text className={styles.metadataValue}>{item.value}</Text>+ </Flexbox>+ ))+ ) : (+ <Flexbox className={styles.metadataRow}>+ <Text type="secondary">{t('skillFrontmatter.empty')}</Text>+ </Flexbox>+ )))}+ </Flexbox>+ );+ },+);++SkillFrontmatterCard.displayName = 'SkillFrontmatterCard';++export default SkillFrontmatterCard;diff --git a/src/features/Portal/GoalNode/Body.tsx b/src/features/Portal/GoalNode/Body.tsxindex 1b4ff2a9b33..8baae24fb6c 100644--- a/src/features/Portal/GoalNode/Body.tsx+++ b/src/features/Portal/GoalNode/Body.tsx@@ -168,8 +168,10 @@ const Body = memo(() => {// A batch's release gate is judged by the coordinator, not asked of a person:// its panel shows the verdicts and their checks instead of a bare decision.const batchGate = node.kind === 'decision' ? findBatchGate(graph, node.id) : undefined;- // A batch's plan opens on its versions and what changed between them.+ // A batch's plan is a skill: it opens as one, full height, with its versions.const batchPlan = node.kind === 'finding' ? findBatchPlan(graph, node.id) : undefined;+ if (batchPlan)+ return <PlanDetail graph={graph} model={batchPlan.model} round={batchPlan.round} />;// Coordinator gates localize; arbitrary gates keep their stored copy.const gateKind = node.kind === 'decision' ? viewGateKind(nodeView) : undefined;@@ -183,7 +185,7 @@ const Body = memo(() => {<Flexbox flex={1} gap={16} padding={16} style={{ minHeight: 0, overflowY: 'auto' }}>{/* A gate's raw node status stays `proposed` while it releases waves;its verdict below says what state it is really in. */}- {!batchGate && !batchPlan && (+ {!batchGate && (<Flexbox horizontal align={'center'} gap={8}><Tag size={'small'}>{t(`goalProcess.kind.${node.kind}` as const)}</Tag><Tag size={'small'}>{t(`goalProcess.nodeStatus.${node.status}` as const)}</Tag>@@ -203,11 +205,8 @@ const Body = memo(() => {/>)}- {batchPlan && <PlanDetail graph={graph} model={batchPlan.model} round={batchPlan.round} />}-{node.description &&!batchGate &&- !batchPlan &&(isFinding ? (// A finding's description is the run's handoff — real Markdown, so// render it as such instead of pre-wrapped source text. `flex-shrink: 0`diff --git a/src/features/Portal/GoalNode/Header.tsx b/src/features/Portal/GoalNode/Header.tsxnew file mode 100644index 00000000000..72b3141a368--- /dev/null+++ b/src/features/Portal/GoalNode/Header.tsx@@ -0,0 +1,39 @@+'use client';++import { memo, useMemo } from 'react';++import PlanHeaderActions from '@/features/AgentGoals/ProcessControl/BatchPlan/PlanHeaderActions';+import { buildGoalGraphView } from '@/features/AgentGoals/ProcessControl/goalGraphViewModel';+import { findBatchPlan } from '@/features/AgentGoals/ProcessControl/Graph/batchModel';+import { useChatStore } from '@/store/chat';+import { chatPortalSelectors } from '@/store/chat/selectors';+import { goalSelectors, useGoalStore } from '@/store/goal';++import PortalHeader from '../components/Header';+import Title from './Title';++/** The shared portal header; a batch's plan adds its version controls on the right. */+const Header = memo<{ onClose?: () => void }>(({ onClose }) => {+ const view = useChatStore(chatPortalSelectors.goalNodeView);+ const snapshot = useGoalStore(goalSelectors.goalGraph(view?.goalId ?? ''));+ const plan = useMemo(() => {+ if (!snapshot || !view) return undefined;+ const graph = buildGoalGraphView(snapshot);+ const found = findBatchPlan(graph, view.nodeId);+ return found && { graph, ...found };+ }, [snapshot, view]);++ return (+ <PortalHeader+ title={<Title />}+ rightExtra={+ plan && <PlanHeaderActions graph={plan.graph} model={plan.model} round={plan.round} />+ }+ onClose={onClose}+ />+ );+});++Header.displayName = 'GoalNodePortalHeader';++export default Header;diff --git a/src/features/Portal/GoalNode/Title.tsx b/src/features/Portal/GoalNode/Title.tsxindex 1ed50b63d4d..930456d82fd 100644--- a/src/features/Portal/GoalNode/Title.tsx+++ b/src/features/Portal/GoalNode/Title.tsx@@ -5,13 +5,20 @@ import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { graphNodeKind } from '@/features/AgentGoals/Experiments/model';+import { usePlanVersionSelection } from '@/features/AgentGoals/ProcessControl/BatchPlan/planVersion';import { coordinatorNodeTitleKey } from '@/features/AgentGoals/ProcessControl/coordinatorCopy';import { buildGoalGraphView } from '@/features/AgentGoals/ProcessControl/goalGraphViewModel';import {+ batchPlanTitleKey,findBatchGate,findBatchPlan,} from '@/features/AgentGoals/ProcessControl/Graph/batchModel';-import { GATE_COLOR, KindIcon } from '@/features/AgentGoals/ProcessControl/shared';+import {+ GATE_COLOR,+ KindIcon,+ SKILL_COLOR,+ SKILL_ICON,+} from '@/features/AgentGoals/ProcessControl/shared';import { useChatStore } from '@/store/chat';import { chatPortalSelectors } from '@/store/chat/selectors';import { goalSelectors, useGoalStore } from '@/store/goal';@@ -21,6 +28,8 @@ const Title = memo(() => {const { t } = useTranslation('chat');const view = useChatStore(chatPortalSelectors.goalNodeView);const snapshot = useGoalStore(goalSelectors.goalGraph(view?.goalId ?? ''));+ // A plan's title names the version the header picked.+ const { selected } = usePlanVersionSelection();const node = useMemo(() => {if (!snapshot || !view) return undefined;const graph = buildGoalGraphView(snapshot);@@ -28,19 +37,25 @@ const Title = memo(() => {if (!nodeView) return undefined;// Coordinator-authored titles are English; a batch gate also names its round.const revision = findBatchGate(graph, nodeView.node.id)?.round.revision;- const plan = findBatchPlan(graph, nodeView.node.id)?.round;+ const plan = findBatchPlan(graph, nodeView.node.id);const titleKey = coordinatorNodeTitleKey(nodeView);+ const planRound = plan+ ? (plan.model.rounds.find((item) => item.revision === selected) ?? plan.round)+ : undefined;const title = plan- ? t(plan.forked ? 'goalBatch.template.forked' : 'goalBatch.template.title', {- revision: plan.revision,- })+ ? t(batchPlanTitleKey(plan.model, planRound!), { revision: planRound!.revision }): revision && revision > 1? t('goalBatch.gate.titleRound', { revision }): titleKey? t(titleKey as any): nodeView.node.title;- return { gate: !!revision, kind: graphNodeKind(graph, nodeView), title };- }, [snapshot, view, t]);+ return {+ gate: !!revision,+ kind: graphNodeKind(graph, nodeView),+ skill: !!plan?.model.planSkill,+ title,+ };+ }, [snapshot, view, t, selected]);return (// Hug the content so the shared `…` sits right after the title.@@ -48,6 +63,8 @@ const Title = memo(() => {{node &&(node.gate ? (<Icon color={GATE_COLOR.line} icon={DoorOpen} size={14} />+ ) : node.skill ? (+ <Icon color={SKILL_COLOR.line} icon={SKILL_ICON} size={14} />) : (<KindIcon kind={node.kind} />))}diff --git a/src/features/Portal/GoalNode/Wrapper.tsx b/src/features/Portal/GoalNode/Wrapper.tsxnew file mode 100644index 00000000000..4bf712174bc--- /dev/null+++ b/src/features/Portal/GoalNode/Wrapper.tsx@@ -0,0 +1,25 @@+'use client';++import { EditorProvider } from '@lobehub/editor/react';+import { memo, type PropsWithChildren } from 'react';++import { PlanVersionProvider } from '@/features/AgentGoals/ProcessControl/BatchPlan/planVersion';+import { useChatStore } from '@/store/chat';+import { chatPortalSelectors } from '@/store/chat/selectors';++/**+ * Shares what a node's header picks with its body — a plan's version — and+ * starts over for every node opened.+ */+const Wrapper = memo<PropsWithChildren>(({ children }) => {+ const view = useChatStore(chatPortalSelectors.goalNodeView);+ return (+ <EditorProvider>+ <PlanVersionProvider key={view?.nodeId}>{children}</PlanVersionProvider>+ </EditorProvider>+ );+});++Wrapper.displayName = 'GoalNodePortalWrapper';++export default Wrapper;diff --git a/src/features/Portal/GoalNode/index.ts b/src/features/Portal/GoalNode/index.tsindex 327bf2be143..bb5390d9480 100644--- a/src/features/Portal/GoalNode/index.ts+++ b/src/features/Portal/GoalNode/index.ts@@ -1,6 +1,14 @@import { type PortalImpl } from '../type';import Body from './Body';+import Header from './Header';import Title from './Title';import { useGoalNodeMoreMenu } from './useMoreMenu';+import Wrapper from './Wrapper';-export const GoalNode: PortalImpl = { Body, Title, useMoreMenu: useGoalNodeMoreMenu };+export const GoalNode: PortalImpl = {+ Body,+ Header,+ Title,+ useMoreMenu: useGoalNodeMoreMenu,+ Wrapper,+};diff --git a/src/services/userSkill.ts b/src/services/userSkill.tsnew file mode 100644index 00000000000..85af33f6e82--- /dev/null+++ b/src/services/userSkill.ts@@ -0,0 +1,12 @@+import { lambdaClient } from '@/libs/trpc/client';++export type UserSkillDetail = NonNullable<+ Awaited<ReturnType<typeof lambdaClient.userSkill.get.query>>+>;+export type UserSkillVersion = UserSkillDetail['versions'][number];++class UserSkillService {+ get = async (id: string) => lambdaClient.userSkill.get.query({ id });+}++export const userSkillService = new UserSkillService();