🤯 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): distill the batch plan from settled probes and draw each batch's retro (#21187)
Arvin Xu09ce85bdbb3a
diff --git a/.agents/skills/cli/references/goal.md b/.agents/skills/cli/references/goal.mdindex 38575538241..03468675f4b 100644--- a/.agents/skills/cli/references/goal.md+++ b/.agents/skills/cli/references/goal.md@@ -115,7 +115,10 @@ probes run first, the rest are released wave by wave once the probes ran throughwithout a person, and a rejection revises the recipe and re-probes. Whether theunits are one mould is the planning agent's call; the server refuses only amalformed declaration, a Goal with `--rollout off`, or a batch already in flight.-No planning turn starts while a batch is in flight.+No planning turn starts while a batch is in flight, except one: when the probes+settle, the main Agent gets a `rollout_distill` turn to rewrite the plan from+what they ran into — answer it with `revise_plan` and the full plan — and the+gate judges the probes after that.`wait` is how a turn waits for time or external evidence — never sleep or poll.Producers deliver the event with `lh goal wake`.diff --git a/apps/cli/src/commands/goal/index.ts b/apps/cli/src/commands/goal/index.tsindex fab908400fa..b10fd4433dc 100644--- a/apps/cli/src/commands/goal/index.ts+++ b/apps/cli/src/commands/goal/index.ts@@ -234,8 +234,8 @@ const admissionHint: Record<string, string> = {'this turn was handed a batch release; answer with release, or escalate without ask for the owner',release_unsolicited: 'release only answers a batch release handed to this turn',revise_turn_only:- 'this turn was handed a plan the owner sent back; answer with revise_plan (the full revised recipe)',- revise_unsolicited: 'revise_plan only answers a plan the owner sent back to this turn',+ 'this turn was handed the batch plan to rewrite; answer with revise_plan (the full revised recipe)',+ revise_unsolicited: 'revise_plan only answers a batch plan handed to this turn to rewrite',review_changed: 'task review feedback changed after this turn started',stale_input: 'the graph moved after this turn started, so the plan would apply to stale input',started_from_draft:@@ -494,7 +494,7 @@ export function registerGoalCommand(program: Command) {).requiredOption('--file <path>',- 'JSON plan: action tasks/wait/verify/retry/escalate/release/revise_plan, reason and action fields; a tasks plan may add "rollout" to run its units as a batch; release answers a batch release handed to this turn; revise_plan answers a plan the owner sent back, with "recipe" the full revised plan and optional "rerun" the experiment unit ids to run again on it (omitted: all)',+ 'JSON plan: action tasks/wait/verify/retry/escalate/release/revise_plan, reason and action fields; a tasks plan may add "rollout" to run its units as a batch; release answers a batch release handed to this turn; revise_plan answers a plan the owner sent back, with "recipe" the full revised plan and optional "rerun" the experiment unit ids to run again on it (omitted: all), and answers settled probes to distill with "recipe" alone',).requiredOption('--token <token>', 'Current server-issued planning turn token').option('--operation <id>', 'Defaults to LOBEHUB_OPERATION_ID')diff --git a/apps/server/src/services/goal/GoalService/rollout.ts b/apps/server/src/services/goal/GoalService/rollout.tsindex d62414bb27c..57c2f688011 100644--- a/apps/server/src/services/goal/GoalService/rollout.ts+++ b/apps/server/src/services/goal/GoalService/rollout.ts@@ -17,6 +17,7 @@ import { GoalGraphModel } from '@/database/models/goalGraph';import { BatchPlanSkillService } from '../batchPlanSkill';import { TERMINAL_NODE_STATUSES } from '../decideNextMove';+import { probesDistilled } from '../probeDistill';import { carriedUnitBrief, createRecipeUnitTask } from '../rolloutBatch';import { evaluateRolloutGate, type RolloutGateResult, withGateVerdict } from '../rolloutGate';import type { GoalServiceContext } from './types';@@ -42,7 +43,9 @@ export const collectRolloutGate = (state.phase === 'done' ||state.phase === 'pattern_break' ||state.phase === 'release_review' ||- state.phase === 'plan_revision'+ state.phase === 'plan_revision' ||+ // The probes are judged once they have taught the plan, straight from the distill step.+ (state.phase === 'plan_distill' && !probesDistilled(state)))return undefined;const materializedIds = new Set([...state.probeNodeIds, ...(state.massNodeIds ?? [])]);diff --git a/apps/server/src/services/goal/GoalService/tick.ts b/apps/server/src/services/goal/GoalService/tick.tsindex 8cdd5598f06..70f0b8e57db 100644--- a/apps/server/src/services/goal/GoalService/tick.ts+++ b/apps/server/src/services/goal/GoalService/tick.ts@@ -11,6 +11,7 @@ import {import { exploreGraph } from '../exploreGraph';import { classifyGoalFailure, isMachineFailureClass } from '../failureClass';import { GoalManagerService } from '../manager';+import { GoalProbeDistill, needsProbeDistill } from '../probeDistill';import { resolveMaxConcurrentTasks } from '../recoveryPolicy';import { withoutGoalReport } from '../report';import { GoalReportService } from '../reportService';@@ -78,7 +79,7 @@ export const tickOnce = async (const at = Date.now();// The coordinator never sees the wrap-up report node: it runs after the// Goal-level acceptance and does not take part in the Goal's status.- const graph = withoutGoalReport(await ctx.requireGraph(goalId));+ let graph = withoutGoalReport(await ctx.requireGraph(goalId));// A draft is still being arranged; only `start` hands it to the coordinator.if (graph.goal.status === 'draft')return {@@ -103,6 +104,14 @@ export const tickOnce = async (// frontier: every probe has settled and nothing else is ready to run.if (graph.goal.config?.rolloutState?.phase === 'plan_revision')return ctx.releaseReview.routeRolloutRevision(graph);+ // Settled probes teach the plan before the gate judges them: the main Agent+ // rewrites the plan skill from what they ran into. Once it has, this same+ // advance goes on to the gate, on the goal as it now stands.+ if (needsProbeDistill(graph)) {+ const waiting = await new GoalProbeDistill(ctx.db, ctx.userId, ctx.workspaceId).route(graph);+ if (waiting) return waiting;+ graph = withoutGoalReport(await ctx.requireGraph(goalId));+ }const frontier = selectFrontier(graph);diff --git a/apps/server/src/services/goal/manager.README.md b/apps/server/src/services/goal/manager.README.mdindex eebf43c380d..40ad88f16d5 100644--- a/apps/server/src/services/goal/manager.README.md+++ b/apps/server/src/services/goal/manager.README.md@@ -78,7 +78,14 @@ commands. It submits a JSON file through `lh goal plan <goal-id> --token <turn>The judgement is the main Agent's: only a malformed declaration, a Goal withrollout `off`, a takeover turn or a batch already in flight is refused. Whilea batch is in flight no uninvited turn starts, so the gate — not a planning- turn — answers the moment its members settle.+ turn — answers the moment its members settle. The probe wave is the+ exception: once a round's probes settle, the coordinator first hands them to+ the main Agent as a `rollout_distill` takeover (`probeDistill.ts`). It reads+ what the probes ran into and answers `revise_plan` with the full plan, which+ becomes the plan skill's next version, and the same advance judges the gate+ straight from that step, so the owner reviews the probes against the plan+ they taught. Without a+ turn to spend, the gate judges them on the plan as written.- `verify`: reason; requests the ordinary independent final acceptance Task.This does not mark the Goal achieved.- `retry`: reason (checkpoint-aware recovery instruction), taskId and exactdiff --git a/apps/server/src/services/goal/manager.test.ts b/apps/server/src/services/goal/manager.test.tsindex ed4bf967e16..b3841e53881 100644--- a/apps/server/src/services/goal/manager.test.ts+++ b/apps/server/src/services/goal/manager.test.ts@@ -39,6 +39,7 @@ import { GoalService } from './index';import { decideFailedTurn, GoalManagerService, MAX_FAILED_MANAGER_TURNS } from './manager';import * as scheduler from './scheduler';import { GoalStartService } from './start';+import { answerDistill, pendingRelease as heldRelease } from './testUtils';import { GoalWaitService } from './wait';vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: () => db }));@@ -1972,13 +1973,10 @@ describe('a batch the main Agent declares', () => {await service().tick(started.id);const probes = (await service().graph(started.id)).nodes.filter((n) => n.kind === 'task');await settle(probes.map((n) => n.id));- await service().tick(started.id);+ await answerDistill(service(), db, userId, started.id, batchPlan.rollout.recipe);return started;};- const pendingRelease = async (id: string) =>- (await service().graph(id)).decisions.find(- (d) => d.status === 'pending' && d.options?.some((option) => option.id === 'release'),- );+ const pendingRelease = (id: string) => heldRelease(service(), id);const approve = async (id: string) => {const pending = await pendingRelease(id);expect(pending).toBeDefined();@@ -1996,12 +1994,12 @@ describe('a batch the main Agent declares', () => {return { op: op!, state };};- it('holds the first wave for the owner, without starting a planning turn', async () => {- const { id, state } = await probesPassed();+ it('holds the first wave for the owner once the probes taught the plan', async () => {+ const { id } = await probesPassed();expect((await service().graph(id)).nodes.some((n) => n.title === 'Project skills')).toBe(false);expect(await pendingRelease(id)).toBeDefined();- expect((await model().findById(id))!.config!.managerState!.token).toBe(state.token);+ expect((await model().findById(id))!.config!.managerState!.problemKind).toBe('rollout_distill');await approve(id);@@ -2122,7 +2120,8 @@ describe('a batch the main Agent declares', () => {expect(after.rollout!.spec!.recipeOutline).toBe(recipe);// Their results, not the old ones, go back to the owner for the release.await settle(reruns);- await service().tick(id);+ // The re-run units are new probes: they teach the plan again before the review.+ await answerDistill(service(), db, userId, id, recipe);expect((await pendingRelease(id))!.nodeId).not.toBe(pending!.nodeId);});diff --git a/apps/server/src/services/goal/manager/admission.ts b/apps/server/src/services/goal/manager/admission.tsindex 1a3b4c76efb..2d162373163 100644--- a/apps/server/src/services/goal/manager/admission.ts+++ b/apps/server/src/services/goal/manager/admission.ts@@ -55,11 +55,12 @@ export const PLAN_REJECTION = {},revise_turn_only: {message:- 'This turn was handed a plan the owner sent back; answer it with revise_plan carrying the full revised recipe',+ 'This turn was handed the batch plan to rewrite; answer it with revise_plan carrying the full revised recipe',trpc: 'BAD_REQUEST',},revise_unsolicited: {- message: 'revise_plan only answers a plan the owner sent back to this turn',+ message:+ 'revise_plan only answers a batch plan handed to this turn: one the owner sent back, or one to rewrite from settled probes',trpc: 'BAD_REQUEST',},release_unsolicited: {@@ -191,9 +192,11 @@ export const evaluateAdmission = async ((plan.action !== 'escalate' || plan.ask !== undefined))return rejectPlan('release_turn_only', op?.status);- // A plan the owner sent back has one answer: the Agent rewrites it. The- // plan is the Agent's, so nobody else applies the correction in its place.- const reviseTurn = state.problemKind === 'rollout_revise';+ // A plan the owner sent back, or one the settled probes are to teach, has+ // one answer: the Agent rewrites it. The plan is the Agent's, so nobody else+ // applies the correction or the lessons in its place.+ const reviseTurn =+ state.problemKind === 'rollout_revise' || state.problemKind === 'rollout_distill';if (plan?.action === 'revise_plan' && !reviseTurn)return rejectPlan('revise_unsolicited', op?.status);if (plan && reviseTurn && plan.action !== 'revise_plan')diff --git a/apps/server/src/services/goal/manager/submit.ts b/apps/server/src/services/goal/manager/submit.tsindex 839f0f2c8c9..279120e6b15 100644--- a/apps/server/src/services/goal/manager/submit.ts+++ b/apps/server/src/services/goal/manager/submit.ts@@ -268,6 +268,19 @@ export const submitPlan = async (waveIndex: rollout.waveIndex,},});+ } else if (plan.action === 'revise_plan' && state.problemKind === 'rollout_distill') {+ // The plan distilled from the settled probes lands with the plan; the next+ // advance writes it as the plan skill's next version, then judges the gate.+ const rollout = goal.config?.rolloutState;+ if (rollout?.phase !== 'plan_distill')+ throw new TRPCError({+ code: 'CONFLICT',+ message: 'The batch is no longer waiting on a plan distilled from its probes',+ });+ await model.updateRolloutState(goalId, {+ ...rollout,+ pendingDistill: { reason: plan.reason, recipe: plan.recipe },+ });} else if (plan.action === 'revise_plan') {// The rewrite lands with the plan; the next advance re-runs the units it names.const rollout = goal.config?.rolloutState;diff --git a/apps/server/src/services/goal/probeDistill.test.ts b/apps/server/src/services/goal/probeDistill.test.tsnew file mode 100644index 00000000000..1979a4768ad--- /dev/null+++ b/apps/server/src/services/goal/probeDistill.test.ts@@ -0,0 +1,247 @@+// @vitest-environment node+import type { GoalConfig } from '@lobechat/types';+import { eq } from 'drizzle-orm';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { AgentOperationModel } from '@/database/models/agentOperation';+import { GoalModel } from '@/database/models/goal';+import { VerifyRunModel } from '@/database/models/verifyRun';+import { agents, goalNodes, goals } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';+import { AiAgentService } from '@/server/services/aiAgent';+import { UserSkillService } from '@/server/services/userSkill';++import { GoalService } from './index';+import { GoalManagerService } from './manager';+import { GoalProbeDistill } from './probeDistill';+import * as scheduler from './scheduler';+import {+ answerDistill,+ distillTurn,+ pendingRelease,+ registerGoalServiceTestCleanup,+} from './testUtils';++const db: LobeChatDatabase = await getTestDB();+const userId = 'goal-probe-distill-test-user';+const agentId = 'goal-probe-distill-agent';++const service = () => new GoalService(db, userId);+const manager = () => new GoalManagerService(db, userId);+const model = () => new GoalModel(db, userId);+const ops = () => new AgentOperationModel(db, userId);++registerGoalServiceTestCleanup(db, userId);++let seq = 0;+beforeEach(async () => {+ await db.insert(agents).values({ id: agentId, userId });+ vi.spyOn(scheduler, 'scheduleGoalAdvance').mockResolvedValue();+ vi.spyOn(AiAgentService.prototype, 'execAgent').mockImplementation(async (params) => {+ const operationId = `op-distill-${++seq}`;+ const topicId = params.appContext!.topicId!;+ await ops().recordStart({+ agentId: params.agentId,+ appContext: { sourceMessageId: params.clientIds?.userMessageId },+ operationId,+ topicId,+ });+ return { operationId, topicId } as Awaited<ReturnType<AiAgentService['execAgent']>>;+ });+});++const recipe = 'Persist the resource, show stale data first, revalidate, add a regression test';+const batchPlan = {+ action: 'tasks' as const,+ reason: 'Four resources share one caching recipe',+ rollout: { recipe, units: ['Project skills', 'Home inbox'] },+ tasks: [+ { description: 'Persist device:listDevices; online state unknown', title: 'Device list' },+ { description: 'Persist toolResultPayload in IndexedDB, capped', title: 'Tool payload' },+ ],+};+const distilled = `${recipe}\n\n## Pitfalls the probes hit\n- Scope the persisted key by workspace before hydrating`;++/** A goal whose main Agent declared the batch and whose probes just settled. */+const probesSettled = async (+ status: 'rejected' | 'resolved' = 'resolved',+ config: Partial<GoalConfig> = {},+) => {+ const graph = await service().create({+ config: { manager: { maxTurns: 4 } },+ createdByAgentId: agentId,+ title: 'Cache resources',+ });+ const id = graph.goal.id;+ // Supervision would take a failed probe first; this file covers the batch path.+ await db+ .update(goals)+ .set({ config: { manager: { maxTurns: 4 }, ...config } })+ .where(eq(goals.id, id));+ await service().tick(id);+ const first = (await model().findById(id))!.config!.managerState!;+ const op = await ops().findByTopicSourceMessage(first.topicId, `msg_goal_manager_${first.token}`);+ await manager().submit(id, first.token, op!.id, batchPlan);+ await ops().recordCompletion(op!.id, { status: 'done' });+ await service().tick(id);+ const probeIds = (await model().findById(id))!.config!.rolloutState!.probeNodeIds;+ for (const [index, nodeId] of probeIds.entries())+ await db+ .update(goalNodes)+ .set({ status: index === 0 ? status : 'resolved' })+ .where(eq(goalNodes.id, nodeId));+ return { id, probeIds };+};++describe('distilling the plan from settled probes', () => {+ it('hands the settled probes to the main Agent before the gate judges them', async () => {+ const { id, probeIds } = await probesSettled();++ await service().tick(id);++ const config = (await model().findById(id))!.config!;+ expect(config.rolloutState!.phase).toBe('plan_distill');+ // The gate waits on the plan: no release is held for the owner yet.+ expect(await pendingRelease(service(), id)).toBeUndefined();+ const { state } = await distillTurn(db, userId, id);+ for (const probeId of probeIds) expect(state.problem).toContain(probeId);+ });++ it('lands the distilled plan as the plan skill next version, then holds the release on it', async () => {+ const { id, probeIds } = await probesSettled();+ await service().tick(id);+ const { op, state: turn } = await distillTurn(db, userId, id);+ await manager().submit(id, turn.token, op.id, {+ action: 'revise_plan',+ reason: 'Folded the workspace scoping pitfall into step 1',+ recipe: distilled,+ });+ await ops().recordCompletion(op.id, { status: 'done' });+ const phases: string[] = [];+ for (let i = 0; i < 3; i++) {+ await service().tick(id);+ phases.push((await model().findById(id))!.config!.rolloutState!.phase);+ }++ // The distill step hands straight to the gate: never back through `probe`.+ expect(phases).not.toContain('probe');+ expect(phases.at(-1)).toBe('release_review');++ const config = (await model().findById(id))!.config!;+ const state = config.rolloutState!;+ expect(state).toMatchObject({ phase: 'release_review', planVersions: { '1': 2 } });+ expect(state.pendingDistill).toBeUndefined();+ // Every later wave is briefed from the distilled plan, and the skill holds it.+ expect(config.rollout!.spec!.recipeOutline).toBe(distilled);+ const skill = await new UserSkillService(db, userId).getSkill(state.planSkill!.id);+ expect(skill?.versions.map((version) => version.version)).toEqual([1, 2]);+ expect(skill?.content).toContain('Scope the persisted key by workspace');+ const template = (await service().graph(id)).nodes.find((n) => n.id === state.templateNodeId);+ expect(template?.description).toBe(distilled);+ // The probes are not run again; the owner reviews them with the plan they taught.+ expect(state.probeNodeIds).toEqual(probeIds);+ const pending = await pendingRelease(service(), id);+ expect(pending!.question).toContain('Experiments of v2 finished');+ const [round] = await new VerifyRunModel(db, userId).listByAcceptance(+ state.releaseGateAcceptanceId!,+ );+ expect(round.metadata!.releaseGate!.plan.content).toContain('Pitfalls the probes hit');+ });++ it('distills a round with a broken probe too, before the gate breaks on it', async () => {+ const { id } = await probesSettled('rejected');++ await service().tick(id);+ expect((await model().findById(id))!.config!.rolloutState!.phase).toBe('plan_distill');+ await answerDistill(service(), db, userId, id, distilled);++ const config = (await model().findById(id))!.config!;+ expect(config.rolloutState!.phase).toBe('pattern_break');+ // The person revising the broken round starts from the distilled plan.+ expect(config.rollout!.spec!.recipeOutline).toBe(distilled);+ });++ it('takes only a rewrite on a distill turn, and hands it over again when none came', async () => {+ const { id } = await probesSettled();+ await service().tick(id);+ const first = await distillTurn(db, userId, id);++ await expect(+ manager().submit(id, first.state.token, first.op.id, {+ action: 'release',+ reason: 'The probes look fine',+ }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });++ await ops().recordCompletion(first.op.id, { status: 'done' });+ await service().tick(id);+ await service().tick(id);+ const second = await distillTurn(db, userId, id);+ expect(second.state.token).not.toBe(first.state.token);+ expect((await model().findById(id))!.config!.rolloutState!.phase).toBe('plan_distill');+ });++ it('judges the gate on the plan as written when the main Agent has no turn left', async () => {+ const { id } = await probesSettled('resolved', { manager: { maxTurns: 1 } });++ // One advance: the skipped distill step goes straight on to the gate.+ expect((await service().tick(id)).outcome).toBe('waiting_human');++ const config = (await model().findById(id))!.config!;+ expect(config.rolloutState!.phase).toBe('release_review');+ expect(config.rollout!.spec!.recipeOutline).toBe(recipe);+ expect(config.managerState!.problemKind).toBeUndefined();+ });++ it('keeps the distillation pending while the goal is paused', async () => {+ const { id } = await probesSettled();+ await service().tick(id);+ const first = await distillTurn(db, userId, id);+ await ops().recordCompletion(first.op.id, { status: 'done' });+ await model().updateStatus(id, 'paused');++ // A queued advance runs while paused: the Agent is unavailable, not out of turns.+ await service().tick(id);++ let state = (await model().findById(id))!.config!.rolloutState!;+ expect(state.phase).toBe('plan_distill');+ expect(state.distilledProbes).toBeUndefined();+ expect(await pendingRelease(service(), id)).toBeUndefined();++ // Resumed, the probes go to the main Agent again rather than to the gate.+ await model().updateStatus(id, 'running');+ await service().tick(id);+ await service().tick(id);+ const second = await distillTurn(db, userId, id);+ expect(second.state.token).not.toBe(first.state.token);+ state = (await model().findById(id))!.config!.rolloutState!;+ expect(state.phase).toBe('plan_distill');+ });++ it('writes one plan skill version when two advances land the same rewrite', async () => {+ const { id } = await probesSettled();+ await service().tick(id);+ const { op, state } = await distillTurn(db, userId, id);+ await manager().submit(id, state.token, op.id, {+ action: 'revise_plan',+ reason: 'Folded the workspace scoping pitfall into step 1',+ recipe: distilled,+ });+ await ops().recordCompletion(op.id, { status: 'done' });+ // Settle the turn, so the next advance is the one that lands the rewrite.+ await service().tick(id);+ const before = await service().graph(id);+ expect(before.goal.config!.rolloutState!.pendingDistill).toBeDefined();++ // Two advances read the same pending rewrite; the second lands after the first.+ const distill = new GoalProbeDistill(db, userId, undefined);+ await distill.route(before);+ await distill.route(before);++ const after = (await model().findById(id))!.config!.rolloutState!;+ const skill = await new UserSkillService(db, userId).getSkill(after.planSkill!.id);+ expect(skill?.versions.map((version) => version.version)).toEqual([1, 2]);+ expect(after.planVersions).toEqual({ '1': 2 });+ });+});diff --git a/apps/server/src/services/goal/probeDistill.ts b/apps/server/src/services/goal/probeDistill.tsnew file mode 100644index 00000000000..5a5b1d4d5d7--- /dev/null+++ b/apps/server/src/services/goal/probeDistill.ts@@ -0,0 +1,225 @@+import { GOAL_COORDINATOR_ACTOR_ID } from '@lobechat/const/goal';+import type { GoalGraphSnapshot, GoalRolloutState, GoalTickResult } from '@lobechat/types';+import debug from 'debug';++import { GoalModel } from '@/database/models/goal';+import { GoalGraphModel } from '@/database/models/goalGraph';+import type { LobeChatDatabase } from '@/database/type';++import { BatchPlanSkillService } from './batchPlanSkill';+import { GoalManagerService } from './manager';+import { activeStatuses } from './manager/turnState';++const log = debug('lobe-server:goal-rollout');++/** Node states that mean a probe will never produce again. */+const SETTLED_NODE_STATUSES = new Set(['resolved', 'rejected', 'retired']);++/**+ * Names one set of probes. A round's probes are distilled once; probes a+ * send-back re-runs, or a break re-opens, are new nodes and so a new set.+ */+export const probeSetKey = (state: Pick<GoalRolloutState, 'probeNodeIds'>) =>+ state.probeNodeIds.toSorted().join(',');++/**+ * Whether the round's probes have taught the plan — distilled, or skipped for+ * want of a main Agent turn — so the gate judges them now. The rollout stays+ * in `plan_distill` until the gate moves it on: there is no step in between.+ */+export const probesDistilled = (state: GoalRolloutState) =>+ state.phase === 'plan_distill' && state.distilledProbes === probeSetKey(state);++/**+ * Whether a round's settled probes are owed (or are in) the distill step+ * before the gate judges them. Only the probe wave is distilled — it is where+ * the plan meets real units first — and only on a goal whose main Agent can+ * rewrite it.+ */+export const needsProbeDistill = (graph: GoalGraphSnapshot): boolean => {+ const state = graph.goal.config?.rolloutState;+ if (!graph.goal.config?.rollout || !state) return false;+ if (state.phase === 'plan_distill') return true;+ if (state.phase !== 'probe' || state.waveIndex !== 0 || !state.probeNodeIds.length) return false;+ if (!graph.goal.config.manager || !graph.goal.agentId) return false;+ if (state.distilledProbes === probeSetKey(state)) return false;+ // A person's open question comes first: the gate would not be judged either.+ if (graph.decisions.some((decision) => decision.status === 'pending')) return false;+ const probes = graph.nodes.filter((node) => state.probeNodeIds.includes(node.id));+ return probes.length > 0 && probes.every((node) => SETTLED_NODE_STATUSES.has(node.status));+};++/** The plan version a round runs on (see `GoalRolloutState.planVersions`). */+const planVersionOf = (state: GoalRolloutState) =>+ state.planVersions?.[String(state.templateRevision)] ?? state.templateRevision;++/**+ * The step between a round's settled probes and its gate: the main Agent reads+ * what the probes ran into and rewrites the plan skill from it, so the owner+ * reviews the probes against the plan they taught and every later wave runs on+ * it. The probes are not run again. A goal whose main Agent cannot take the+ * turn (no turns or budget left) keeps its plan as written and goes on to the+ * gate rather than stopping on it.+ */+export class GoalProbeDistill {+ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId: string | undefined,+ ) {}++ /**+ * Drive the distill step. Returns the tick result while it waits on the main+ * Agent; `undefined` once the plan is ready, and the caller judges the gate in+ * the same advance — straight from `plan_distill`, never back through `probe`.+ */+ route = async (snapshot: GoalGraphSnapshot): Promise<GoalTickResult | undefined> => {+ let graph = snapshot;+ const goalId = graph.goal.id;+ const state = graph.goal.config!.rolloutState!;+ if (probesDistilled(state)) return undefined;+ if (state.phase === 'plan_distill' && state.pendingDistill) {+ await this.apply(graph);+ return undefined;+ }++ if (state.phase !== 'plan_distill') {+ const entered = await this.db.transaction(async (tx) => {+ const goalModel = new GoalModel(tx, this.userId, this.workspaceId);+ const current = (await goalModel.lockById(goalId))?.config?.rolloutState;+ if (+ current?.phase !== 'probe' ||+ current.waveIndex !== 0 ||+ probeSetKey(current) !== probeSetKey(state)+ )+ return false;+ await goalModel.updateRolloutState(goalId, { ...current, phase: 'plan_distill' });+ return true;+ });+ const fresh = entered+ ? await new GoalGraphModel(this.db, this.userId, this.workspaceId).getGraph(goalId)+ : undefined;+ if (!fresh)+ return {+ goalId,+ message: 'Another advance already moved the probes on',+ outcome: 'no_progress',+ };+ // The turn is claimed against the goal as it now stands, phase included.+ graph = fresh;+ }++ const probes = graph.nodes.filter((node) => state.probeNodeIds.includes(node.id));+ // Names the probe set, so a later round's distillation is never read as+ // already answered by this one.+ const problem = {+ kind: 'rollout_distill' as const,+ reason: `The ${probes.length} probe${probes.length === 1 ? '' : 's'} of plan v${planVersionOf(state)} settled (${probes+ .map((node) => `${node.title} [${node.id}]: ${node.status}`)+ .join('; ')}). Rewrite the plan from what they ran into before the gate judges them.`,+ };+ // Paused, or waiting on a person: the main Agent is unavailable for now,+ // not out of turns, so the distillation stays pending for when it runs again.+ if (+ !activeStatuses.has(graph.goal.status) ||+ graph.decisions.some((decision) => decision.status === 'pending')+ )+ return {+ goalId,+ message: 'The plan waits to be distilled from the probes until the goal runs again',+ outcome: 'waiting_human',+ };+ const takeover = await new GoalManagerService(this.db, this.userId, this.workspaceId).takeOver(+ graph,+ problem,+ );+ if (takeover) return takeover;+ await this.skip(goalId);+ return undefined;+ };++ /** No main Agent can rewrite the plan: the gate judges the probes on it as written. */+ private skip = async (goalId: string) =>+ this.db.transaction(async (tx) => {+ const goalModel = new GoalModel(tx, this.userId, this.workspaceId);+ const current = (await goalModel.lockById(goalId))?.config?.rolloutState;+ if (current?.phase !== 'plan_distill' || current.pendingDistill) return;+ log('probe distill: no main Agent turn; judging the gate on the plan as written');+ await goalModel.updateRolloutState(goalId, {+ ...current,+ distilledProbes: probeSetKey(current),+ });+ });++ /**+ * Land the plan the main Agent distilled: the plan skill's next version, the+ * policy's outline every later wave is briefed from, and the Template. The+ * round stays in `plan_distill`, marked distilled, for the gate to judge.+ *+ * The rewrite is claimed under the goal row's lock before the skill is+ * revised, so overlapping advances that read the same pending rewrite write+ * one version, not one each.+ */+ private apply = async (graph: GoalGraphSnapshot) => {+ const goalId = graph.goal.id;+ const policy = graph.goal.config?.rollout;+ await this.db.transaction(async (tx) => {+ const goalModel = new GoalModel(tx, this.userId, this.workspaceId);+ const current = (await goalModel.lockById(goalId))?.config?.rolloutState;+ // Another advance landed it first; the gate is next either way.+ if (current?.phase !== 'plan_distill' || !current.pendingDistill) return;+ const { reason, recipe: raw } = current.pendingDistill;+ const recipe = raw.trim();+ const round = String(current.templateRevision);+ const skill = recipe ? current.planSkill : undefined;+ // A savepoint: a failed revision costs the skill version, not the claim.+ const version = skill+ ? await tx+ .transaction((savepoint) =>+ new BatchPlanSkillService(+ savepoint as unknown as LobeChatDatabase,+ this.userId,+ this.workspaceId,+ ).revise(skill, {+ goalId,+ guidance: reason,+ plan: recipe,+ revision: current.templateRevision,+ }),+ )+ .catch((error) => {+ log('probe distill: plan skill revision failed: %O', error);+ return undefined;+ })+ : undefined;+ // A revision that did not land leaves the skill on the plan before the+ // probes: later units drop it and copy the distilled plan instead.+ const planSkill = skill && version === undefined ? undefined : current.planSkill;+ if (recipe) {+ if (policy)+ await goalModel.updateRolloutPolicy(goalId, {+ ...policy,+ spec: {+ ...policy.spec,+ recipeOutline: recipe,+ repeatable: policy.spec?.repeatable ?? true,+ },+ });+ if (current.templateNodeId)+ await new GoalGraphModel(tx, this.userId, this.workspaceId, {+ id: GOAL_COORDINATOR_ACTOR_ID,+ type: 'system',+ }).updateNodeDescription(goalId, current.templateNodeId, recipe);+ }+ await goalModel.updateRolloutState(goalId, {+ ...current,+ distilledProbes: probeSetKey(current),+ pendingDistill: undefined,+ planSkill,+ planVersions: version+ ? { ...current.planVersions, [round]: version }+ : current.planVersions,+ });+ });+ };+}diff --git a/apps/server/src/services/goal/testUtils.ts b/apps/server/src/services/goal/testUtils.tsindex ba64b2238d7..56e0dc93acc 100644--- a/apps/server/src/services/goal/testUtils.ts+++ b/apps/server/src/services/goal/testUtils.ts@@ -1,6 +1,8 @@/** Shared helpers for the goal service tests: the database lifecycle, and driving a batch through its release review. */import { afterEach, beforeEach, expect, vi } from 'vitest';+import { AgentOperationModel } from '@/database/models/agentOperation';+import { GoalModel } from '@/database/models/goal';import {acceptances,agentOperations,@@ -21,6 +23,7 @@ import {import type { LobeChatDatabase } from '@/database/type';import type { GoalService } from './index';+import { GoalManagerService } from './manager';/** Seed the test user before each test and clear everything a goal test writes after it. */export const registerGoalServiceTestCleanup = (serverDB: LobeChatDatabase, userId: string) => {@@ -65,3 +68,41 @@ export const approveRelease = async (service: GoalService, goalId: string) => {await service.answerReleaseGate(pending!.nodeId, 'release');return service.tick(goalId);};++/**+ * The turn a round's settled probes were handed to, so the main Agent rewrites+ * the plan from them before the gate judges them.+ */+export const distillTurn = async (db: LobeChatDatabase, userId: string, goalId: string) => {+ const state = (await new GoalModel(db, userId).findById(goalId))!.config!.managerState!;+ expect(state.problemKind).toBe('rollout_distill');+ const op = await new AgentOperationModel(db, userId).findByTopicSourceMessage(+ state.topicId,+ `msg_goal_manager_${state.token}`,+ );+ return { op: op!, state };+};++/**+ * Hand a round's settled probes to the main Agent, answer that turn with+ * `recipe`, end it, and advance until the gate is judged.+ */+export const answerDistill = async (+ service: GoalService,+ db: LobeChatDatabase,+ userId: string,+ goalId: string,+ recipe: string,+) => {+ await service.tick(goalId);+ const { op, state } = await distillTurn(db, userId, goalId);+ await new GoalManagerService(db, userId).submit(goalId, state.token, op.id, {+ action: 'revise_plan',+ reason: 'Folded what the probes ran into into the plan',+ recipe,+ });+ await new AgentOperationModel(db, userId).recordCompletion(op.id, { status: 'done' });+ await service.tick(goalId);+ await service.tick(goalId);+ return service.tick(goalId);+};diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 02fa899c18d..b13f6f0b3f8 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -468,6 +468,8 @@"goalBatch.cell.tooltip": "Wave {{wave}} · item {{index}} · {{title}} · {{state}}","goalBatch.enter": "Open","goalBatch.gate.checkCount": "{{count}} checks",+ "goalBatch.gate.hintSection.execution": "Execution",+ "goalBatch.gate.hintSection.retro": "Retro & criteria","goalBatch.gate.hintTitle": "Checked before the rest are released:","goalBatch.gate.status.checking": "Judging","goalBatch.gate.status.human": "Needs your decision",@@ -478,8 +480,10 @@"goalBatch.gate.titleRound": "Release gate · v{{revision}}","goalBatch.gateCheck.axes_covered": "The trials covered every declared variant","goalBatch.gateCheck.count": "{{count}} / {{total}}",+ "goalBatch.gateCheck.interventions_accounted": "Every person’s intervention was accounted for","goalBatch.gateCheck.no_open_decision": "No decision in the batch is waiting on a person","goalBatch.gateCheck.plan_written": "The batch plan is written",+ "goalBatch.gateCheck.reverified": "The delivered units passed the retro’s criteria","goalBatch.gateCheck.uncovered": "Not covered: {{values}}","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",@@ -495,6 +499,7 @@"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.distilling": "The main Agent is updating the plan from what the probes ran into — judged once it is done","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","goalBatch.gatePanel.next.passed": "Released wave {{wave}} ({{count}} units) — judged again once it finishes",@@ -535,6 +540,28 @@"goalBatch.redispatch.labelRound": "v{{revision}}","goalBatch.redispatch.reopenedRow": "Reopened","goalBatch.redispatch.title": "Waves · v{{revision}}",+ "goalBatch.retro.added": "{{count}} new",+ "goalBatch.retro.changes": "{{count}} steps changed",+ "goalBatch.retro.criteria": "{{block}} blocking · {{warn}} advisory",+ "goalBatch.retro.hint": "What the execution ran into, kept in two layers: experience goes into the plan skill every unit loads, criteria go into the verifier every unit is judged on. The gate opens only after the retro.",+ "goalBatch.retro.interventionsShort": "{{accounted}}/{{total}} accounted",+ "goalBatch.retro.loosened": "{{count}} loosened, needs you",+ "goalBatch.retro.mark.blocked": "Unaccounted",+ "goalBatch.retro.mark.done": "Exp v{{skill}} · Crit v{{verifier}}",+ "goalBatch.retro.mark.pending": "Retro owed",+ "goalBatch.retro.mark.pendingHint": "This wave finished; its retro has not run yet",+ "goalBatch.retro.mark.running": "In retro",+ "goalBatch.retro.skill": "Experience · plan skill v{{version}}",+ "goalBatch.retro.status.blocked": "Interventions not accounted for",+ "goalBatch.retro.status.done": "Retro done",+ "goalBatch.retro.status.running": "In retro",+ "goalBatch.retro.summary.interventions": "{{accounted}}/{{total}} interventions accounted for",+ "goalBatch.retro.summary.reverify": "Re-verified {{passed}}/{{total}}",+ "goalBatch.retro.summary.skill": "Plan skill v{{version}}: {{count}} steps changed",+ "goalBatch.retro.summary.verifier": "Verifier v{{version}}: {{added}} added, {{loosened}} loosened",+ "goalBatch.retro.title": "Retro · cold start",+ "goalBatch.retro.titleWave": "Retro · wave {{wave}} sent back",+ "goalBatch.retro.verifier": "Criteria · verifier v{{version}}","goalBatch.round.foot": "{{count}} units","goalBatch.round.reviseEdge": "Sent back · revise","goalBatch.round.title": "Round {{revision}}",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex c866e8945e4..5a4c75c006f 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -468,6 +468,8 @@"goalBatch.cell.tooltip": "第 {{wave}} 批 · 第 {{index}} 项 · {{title}} · {{state}}","goalBatch.enter": "进入","goalBatch.gate.checkCount": "{{count}} 项检查",+ "goalBatch.gate.hintSection.execution": "执行",+ "goalBatch.gate.hintSection.retro": "复盘与判据","goalBatch.gate.hintTitle": "放行其余单元前逐项检查:","goalBatch.gate.status.checking": "判定中","goalBatch.gate.status.human": "需要你决定",@@ -478,8 +480,10 @@"goalBatch.gate.titleRound": "放行闸门 · v{{revision}}","goalBatch.gateCheck.axes_covered": "实验覆盖了每个变体取值","goalBatch.gateCheck.count": "{{count}} / {{total}}",+ "goalBatch.gateCheck.interventions_accounted": "人工介入全部有交代","goalBatch.gateCheck.no_open_decision": "批次内没有等人决定的事项","goalBatch.gateCheck.plan_written": "执行方案已成稿",+ "goalBatch.gateCheck.reverified": "本批已按新判据重验通过","goalBatch.gateCheck.uncovered": "未覆盖:{{values}}","goalBatch.gateCheck.units_settled": "本轮单元全部跑完","goalBatch.gateCheck.units_succeeded": "本轮单元全部自动跑通,没有失败或被打回的",@@ -495,6 +499,7 @@"goalBatch.gatePanel.learned": "这道闸门学到的","goalBatch.gatePanel.learnedHint": "已写进之后每个单元都会加载的方案,并加进它们各自的验收要求。","goalBatch.gatePanel.next.checking": "单元已全部跑完,协调器下一次推进时判定",+ "goalBatch.gatePanel.next.distilling": "主 Agent 正在根据探针遇到的问题更新方案,更新完再判定","goalBatch.gatePanel.next.human": "等你决定:修订方案重探,或为出问题的几项另起一份方案","goalBatch.gatePanel.next.locked": "本轮 {{count}} 个单元跑完后自动判定","goalBatch.gatePanel.next.passed": "已放行第 {{wave}} 批({{count}} 项),这一批跑完后再判一次",@@ -535,6 +540,28 @@"goalBatch.redispatch.labelRound": "v{{revision}}","goalBatch.redispatch.reopenedRow": "重开","goalBatch.redispatch.title": "分批执行 · v{{revision}}",+ "goalBatch.retro.added": "新增 {{count}}",+ "goalBatch.retro.changes": "改了 {{count}} 处",+ "goalBatch.retro.criteria": "阻断 {{block}} · 提醒 {{warn}}",+ "goalBatch.retro.hint": "把执行中遇到的问题分两层沉淀:经验写进每个单元都会加载的方案技能,判据写进每个单元的验收标准。复盘完成后才进入放行闸门。",+ "goalBatch.retro.interventionsShort": "介入 {{accounted}}/{{total}} 已交代",+ "goalBatch.retro.loosened": "放宽 {{count}},待你确认",+ "goalBatch.retro.mark.blocked": "缺交代",+ "goalBatch.retro.mark.done": "经验 v{{skill}} · 判据 v{{verifier}}",+ "goalBatch.retro.mark.pending": "待复盘",+ "goalBatch.retro.mark.pendingHint": "这一批已跑完,还没复盘",+ "goalBatch.retro.mark.running": "复盘中",+ "goalBatch.retro.skill": "经验 · 方案技能 v{{version}}",+ "goalBatch.retro.status.blocked": "有人工介入还没交代",+ "goalBatch.retro.status.done": "已复盘",+ "goalBatch.retro.status.running": "复盘中",+ "goalBatch.retro.summary.interventions": "人工介入 {{accounted}}/{{total}} 已交代",+ "goalBatch.retro.summary.reverify": "按新判据重验 {{passed}}/{{total}} 通过",+ "goalBatch.retro.summary.skill": "方案技能 v{{version}}:改了 {{count}} 处",+ "goalBatch.retro.summary.verifier": "验收判据 v{{version}}:新增 {{added}} 条,放宽 {{loosened}} 条",+ "goalBatch.retro.title": "复盘 · 冷启动",+ "goalBatch.retro.titleWave": "复盘 · 第 {{wave}} 批打回",+ "goalBatch.retro.verifier": "判据 · 验收判据 v{{version}}","goalBatch.round.foot": "{{count}} 项","goalBatch.round.reviseEdge": "打回 · 修订","goalBatch.round.title": "第 {{revision}} 轮",diff --git a/packages/database/src/repositories/topic/__tests__/duplicate.test.ts b/packages/database/src/repositories/topic/__tests__/duplicate.test.tsindex 9a6b98ac743..e3598c44c6a 100644--- a/packages/database/src/repositories/topic/__tests__/duplicate.test.ts+++ b/packages/database/src/repositories/topic/__tests__/duplicate.test.ts@@ -184,6 +184,45 @@ describe('TopicRepository - duplicate', () => {expect(newMsg4.id).not.toBe('msg4');});+ /**+ * Regression: messages were copied in `createdAt` order alone, so a reply+ * timestamped no later than its parent — rows written by one insert share a+ * timestamp, and imported or clock-skewed rows can run backwards — could be+ * inserted before its parent and break the parent foreign key.+ */+ it('copies a parent before its reply even when the reply is timestamped earlier', async () => {+ const topicId = 'topic-with-skewed-times';+ const later = new Date('2026-01-01T00:00:10.000Z');+ const earlier = new Date('2026-01-01T00:00:00.000Z');++ await serverDB.transaction(async (tx) => {+ await tx.insert(topics).values({ id: topicId, sessionId, userId, title: 'Original Topic' });+ await tx.insert(messages).values({+ content: 'Parent',+ createdAt: later,+ id: 'skew-parent',+ role: 'user',+ topicId,+ userId,+ });+ await tx.insert(messages).values({+ content: 'Reply',+ createdAt: earlier,+ id: 'skew-reply',+ parentId: 'skew-parent',+ role: 'assistant',+ topicId,+ userId,+ });+ });++ const { messages: duplicated } = await topicRepo.duplicate(topicId, 'Duplicated Topic');++ const byContent = new Map(duplicated.map((message) => [message.content, message]));+ expect(byContent.get('Parent')!.parentId).toBeNull();+ expect(byContent.get('Reply')!.parentId).toBe(byContent.get('Parent')!.id);+ });+it('should correctly map tool_call_id when duplicating messages with tools', async () => {const topicId = 'topic-with-tools';const originalToolId = 'toolu_original_123';diff --git a/packages/database/src/repositories/topic/duplicate.ts b/packages/database/src/repositories/topic/duplicate.tsindex c149bf402d6..27d179e2714 100644--- a/packages/database/src/repositories/topic/duplicate.ts+++ b/packages/database/src/repositories/topic/duplicate.ts@@ -17,6 +17,40 @@ import { messageOwnership, topicOwnership, type TopicRepositoryScope } from './s* that message (first message → that message) — the "fork from here" path.* Without it the whole topic is copied, matching the duplicate action.*/++/**+ * Order messages so every parent precedes its replies, keeping `createdAt`+ * order otherwise. Copies are inserted one by one against the parent foreign+ * key, and time alone does not guarantee it: rows written by one insert share a+ * timestamp, and imported or clock-skewed rows can run backwards.+ */+type Linked = { id: string; parentId?: string | null };++const parentsFirst = <T>(rows: T[]): T[] => {+ const link = (row: T) => row as Linked;+ const byId = new Map(rows.map((row) => [link(row).id, row]));+ const placed = new Set<string>();+ const ordered: T[] = [];+ for (const row of rows) {+ // Walk up to the first ancestor already placed (or the root), then place+ // the chain from the top down. A cycle stops the walk where it repeats.+ const chain: T[] = [];+ const seen = new Set<string>();+ let cursor: T | undefined = row;+ while (cursor && !placed.has(link(cursor).id) && !seen.has(link(cursor).id)) {+ const { id, parentId } = link(cursor);+ seen.add(id);+ chain.push(cursor);+ cursor = parentId ? byId.get(parentId) : undefined;+ }+ for (const item of chain.reverse()) {+ placed.add(link(item).id);+ ordered.push(item);+ }+ }+ return ordered;+};+export const duplicateTopic = async (scope: TopicRepositoryScope,topicId: string,@@ -69,7 +103,7 @@ export const duplicateTopic = async (// A fork copies only the selected prefix of the conversation (first// message → `upToMessageId`), so sibling branches left behind by// regenerate stay in the source topic; a duplicate copies the whole topic.- let originalMessages = topicMessages;+ let originalMessages = parentsFirst(topicMessages);if (options?.upToMessageId) {const byId = new Map(topicMessages.map((message) => [message.id, message]));const selected = byId.get(options.upToMessageId);diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 45b01be024c..9e94c635c70 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -63,6 +63,32 @@ export default {'goalBatch.gateCheck.no_open_decision': 'No decision in the batch is waiting on a person','goalBatch.gateCheck.plan_written': 'The batch plan is written','goalBatch.gateCheck.uncovered': 'Not covered: {{values}}',+ 'goalBatch.gateCheck.interventions_accounted': 'Every person’s intervention was accounted for',+ 'goalBatch.gateCheck.reverified': 'The delivered units passed the retro’s criteria',+ 'goalBatch.retro.added': '{{count}} new',+ 'goalBatch.retro.changes': '{{count}} steps changed',+ 'goalBatch.retro.criteria': '{{block}} blocking · {{warn}} advisory',+ 'goalBatch.retro.hint':+ 'What the execution ran into, kept in two layers: experience goes into the plan skill every unit loads, criteria go into the verifier every unit is judged on. The gate opens only after the retro.',+ 'goalBatch.retro.interventionsShort': '{{accounted}}/{{total}} accounted',+ 'goalBatch.retro.loosened': '{{count}} loosened, needs you',+ 'goalBatch.retro.mark.blocked': 'Unaccounted',+ 'goalBatch.retro.mark.done': 'Exp v{{skill}} · Crit v{{verifier}}',+ 'goalBatch.retro.mark.pending': 'Retro owed',+ 'goalBatch.retro.mark.pendingHint': 'This wave finished; its retro has not run yet',+ 'goalBatch.retro.mark.running': 'In retro',+ 'goalBatch.retro.skill': 'Experience · plan skill v{{version}}',+ 'goalBatch.retro.status.blocked': 'Interventions not accounted for',+ 'goalBatch.retro.status.done': 'Retro done',+ 'goalBatch.retro.status.running': 'In retro',+ 'goalBatch.retro.summary.interventions': '{{accounted}}/{{total}} interventions accounted for',+ 'goalBatch.retro.summary.reverify': 'Re-verified {{passed}}/{{total}}',+ 'goalBatch.retro.summary.skill': 'Plan skill v{{version}}: {{count}} steps changed',+ 'goalBatch.retro.summary.verifier':+ 'Verifier v{{version}}: {{added}} added, {{loosened}} loosened',+ 'goalBatch.retro.title': 'Retro · cold start',+ 'goalBatch.retro.titleWave': 'Retro · wave {{wave}} sent back',+ 'goalBatch.retro.verifier': 'Criteria · verifier v{{version}}','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',@@ -94,10 +120,14 @@ export default {'goalBatch.gatePanel.next.passed':'Released wave {{wave}} ({{count}} units) — judged again once it finishes','goalBatch.gatePanel.next.passedDone': 'The whole roster is released',+ 'goalBatch.gatePanel.next.distilling':+ 'The main Agent is updating the plan from what the probes ran into — judged once it is done','goalBatch.gatePanel.next.revising': 'The main Agent is rewriting the plan from your correction','goalBatch.gatePanel.next.rejected': 'Reopened as v{{revision}} on your decision','goalBatch.gatePanel.verdict': 'Verdict','goalBatch.gate.checkCount': '{{count}} checks',+ 'goalBatch.gate.hintSection.execution': 'Execution',+ 'goalBatch.gate.hintSection.retro': 'Retro & criteria','goalBatch.gate.hintTitle': 'Checked before the rest are released:','goalBatch.gate.status.checking': 'Judging','goalBatch.gate.status.human': 'Needs your decision',diff --git a/packages/prompts/src/chains/goalManager.test.ts b/packages/prompts/src/chains/goalManager.test.tsindex f1ed4500949..037d2a2d897 100644--- a/packages/prompts/src/chains/goalManager.test.ts+++ b/packages/prompts/src/chains/goalManager.test.ts@@ -28,7 +28,7 @@ describe('buildGoalManagerPrompt', () => {'keeps supervision language tied to the goal rather than the English control prompt: %s',(requirement) => {const prompt = buildGoalManagerPrompt({ ...base, requirement });- expect(GOAL_MANAGER_PROMPT_VERSION).toBe('v12');+ expect(GOAL_MANAGER_PROMPT_VERSION).toBe('v13');expect(cdataOf(prompt, 'requirement')).toBe(requirement);expect(prompt).toContain('Use the language of the Goal requirement');expect(prompt).toContain(@@ -56,6 +56,19 @@ describe('buildGoalManagerPrompt', () => {expect(prompt).not.toContain('Takeover: without you this Goal stops on a person');});+ it('asks a distill turn to rewrite the plan from the settled probes', () => {+ const prompt = buildGoalManagerPrompt({+ ...base,+ problem: 'The 2 probes of plan v1 settled. Rewrite the plan before the gate judges them.',+ problemKind: 'rollout_distill',+ });+ expect(prompt).toContain('Plan distillation:');+ expect(prompt).toContain('{"action":"revise_plan"');+ // Nothing re-runs on a distilled plan, so the turn is not offered `rerun`.+ expect(prompt).not.toContain('"rerun"');+ expect(prompt).not.toContain('Takeover: without you this Goal stops on a person');+ });+/*** Regression: a main Agent planning one recipe over many units only knew the* flat tasks schema, so it seeded every unit at once and the batch rollout@@ -152,7 +165,7 @@ describe('buildGoalManagerPrompt', () => {});expect(prompt.split('\n')[0]).toBe(- '<goalTurn goal="goal_1" maxTurns="12" trigger="settled" turn="3" version="v12">',+ '<goalTurn goal="goal_1" maxTurns="12" trigger="settled" turn="3" version="v13">',);expect(prompt.endsWith('</goalTurn>')).toBe(true);// CommonMark ends an HTML block at a blank line; the client needs one block.diff --git a/packages/prompts/src/chains/goalManager.ts b/packages/prompts/src/chains/goalManager.tsindex f0522a6c291..fef4fb9ffc9 100644--- a/packages/prompts/src/chains/goalManager.ts+++ b/packages/prompts/src/chains/goalManager.ts@@ -21,8 +21,11 @@ import { GOAL_TURN_TAG } from '@lobechat/const';* takeover, answered only with `revise_plan` (the rewritten recipe).* v12 reads measured acceptance from the clause values `lh goal show` reports* and asks the owner to record an unrecorded one instead of re-verifying.+ * v13 hands a round's settled probes to the agent as a `rollout_distill`+ * takeover before the gate judges them: it rewrites the plan from what the+ * probes ran into, answered only with `revise_plan`.*/-export const GOAL_MANAGER_PROMPT_VERSION = 'v12';+export const GOAL_MANAGER_PROMPT_VERSION = 'v13';export interface GoalManagerFeedbackNote {/** `user`, or `agent <id>` for an agent-written comment. */@@ -59,8 +62,9 @@ interface GoalManagerPromptInput {/*** `rollout_release`: a passed batch gate whose next wave this turn releases or escalates.* `rollout_revise`: the owner sent the batch plan back; this turn rewrites it.+ * `rollout_distill`: the round's probes settled; this turn rewrites the plan from them.*/- problemKind?: 'rollout_release' | 'rollout_revise';+ problemKind?: 'rollout_distill' | 'rollout_release' | 'rollout_revise';requirement: string;token: string;turn: number;@@ -168,12 +172,16 @@ export const GOAL_BATCH_RELEASE_RULE =export const GOAL_BATCH_REVISE_RULE ='Plan revision: the owner reviewed the batch\'s experiments and sent the plan back with the correction in <problem>. Read the current plan skill and the experiment results with lh goal show, then rewrite the whole plan so every remaining unit follows the correction — fold it into the steps it changes instead of appending a note. Then decide which delivered experiment units the correction covers: those run again on the revised plan, continuing their earlier delivery (same branch / PR), and the owner reviews the new round\'s results — not the old ones. A correction about how the units were delivered (review, CI, quality, a missed step) covers all of them; one that only changes units still owed covers none. Answer {"action":"revise_plan","reason":"what changed and why it answers the correction","recipe":"the full revised plan, in the language of the Goal requirement","rerun":["node ids of the experiment units to run again"]} — omit "rerun" to run every experiment unit again, or pass [] when none needs it. Where the correction conflicts with the plan, resolve it in the rewrite and say how in reason. No other action is accepted on this turn.';+/** A takeover whose problem is a round's settled probes: rewrite the plan from them. */+export const GOAL_BATCH_DISTILL_RULE =+ 'Plan distillation: every probe of the batch has settled, and before the gate judges them the plan skill must learn from them. Read the current plan skill and each probe\'s task, topic, deliverables, review comments and acceptance evidence with lh goal show and lh task view. Then rewrite the whole plan so every remaining unit benefits from what the probes ran into: steps they had to add or reorder, pitfalls and how they were resolved, conventions reviewers enforced, commands and checks that proved the work, and anything a probe got wrong that later units must avoid. Fold each lesson into the step it changes instead of appending a log of what happened; keep what is specific to one probe out unless it generalizes. When the probes taught nothing new, return the current plan unchanged and say so in reason. Answer {"action":"revise_plan","reason":"what the probes taught and where it landed in the plan","recipe":"the full plan, in the language of the Goal requirement"}. The probes are not run again and the owner reviews them with the plan you wrote. No other action is accepted on this turn.';+/*** When to declare a batch, and how. The judgement is the planning agent's; the* server only checks the declaration is well formed.*/export const GOAL_BATCH_PLANNING_RULE =- 'Batch (one repeated mould): when the remaining work applies one recipe to many units — migrate N stores to one mechanism, give N resources the same caching, update N callers — and the first units will likely need a person (unsettled conventions, review, acceptance), do not plan every unit as a task. Add "rollout" to the tasks plan instead: "tasks" become 2-5 probes, the most representative units covering every variant, each with a full brief; "rollout.recipe" is the one procedure every unit follows; "rollout.units" lists every other unit in delivery order, as a title or as {"title","description"} when the unit has its own pointers; "rollout.variants" names the axes the units differ along, and the gate holds until the probes cover each value. The probes run first; once every probe ran through without a person, the owner approves the first wave, each later wave is handed to you to release or escalate, and a rejected release comes back to you to rewrite the plan for the owner to review again. Units that differ only in names, files or details are still one mould; work whose steps differ from task to task is not, so plan it as ordinary tasks. Never declare a batch on a Goal whose rollout is off. While a batch is in flight no planning turn starts; the next one comes after its roster is delivered.';+ 'Batch (one repeated mould): when the remaining work applies one recipe to many units — migrate N stores to one mechanism, give N resources the same caching, update N callers — and the first units will likely need a person (unsettled conventions, review, acceptance), do not plan every unit as a task. Add "rollout" to the tasks plan instead: "tasks" become 2-5 probes, the most representative units covering every variant, each with a full brief; "rollout.recipe" is the one procedure every unit follows; "rollout.units" lists every other unit in delivery order, as a title or as {"title","description"} when the unit has its own pointers; "rollout.variants" names the axes the units differ along, and the gate holds until the probes cover each value. The probes run first; once they settle you rewrite the plan from what they ran into, and once every probe ran through without a person, the owner approves the first wave, each later wave is handed to you to release or escalate, and a rejected release comes back to you to rewrite the plan for the owner to review again. Units that differ only in names, files or details are still one mould; work whose steps differ from task to task is not, so plan it as ordinary tasks. Never declare a batch on a Goal whose rollout is off. While a batch is in flight no planning turn starts; the next one comes after its roster is delivered.';const contract = (input: GoalManagerPromptInput) =>[@@ -184,7 +192,9 @@ const contract = (input: GoalManagerPromptInput) =>? GOAL_BATCH_RELEASE_RULE: input.problemKind === 'rollout_revise'? GOAL_BATCH_REVISE_RULE- : takeoverRules,+ : input.problemKind === 'rollout_distill'+ ? GOAL_BATCH_DISTILL_RULE+ : takeoverRules,]: []),'Reading this block: <requirement> is the Goal; <ownerInstruction> is the owner’s standing note; <problem> (takeover) and <continuation> say why this turn started; <previousTurn> is how the last turn ended; <feedback new="true"> was written since the last turn and <feedback> without it is an excerpt the last turn already had; truncated="true" or <omittedFeedback> means the list is incomplete, so read the full comments with lh task view.',diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.tsindex 116c3d79fa0..73312ea50c1 100644--- a/packages/types/src/goal.ts+++ b/packages/types/src/goal.ts@@ -1,4 +1,5 @@import type { GoalReportDispatch, GoalReportState } from './goalReport';+import type { GoalRolloutRetro, GoalRolloutVerifier } from './goalRetro';import type { InitialGoalOverviewContext } from './stepContext';import type { AcceptanceStatus, VerifyCheckTally } from './verify';import type { WorkType } from './work';@@ -333,8 +334,12 @@ export interface GoalManagerState {* What kind of problem was handed over. `rollout_release`: a batch gate passed* and the main Agent decides whether the next wave goes out (`release`) or a* person approves it (`escalate`); no other answer applies to it.+ * `rollout_revise`: the owner sent the batch plan back and the main Agent+ * rewrites it (`revise_plan`). `rollout_distill`: a round's probes settled+ * and the main Agent rewrites the plan from what they ran into+ * (`revise_plan`) before the gate judges them.*/- problemKind?: 'rollout_release' | 'rollout_revise';+ problemKind?: 'rollout_distill' | 'rollout_release' | 'rollout_revise';/** The blocked task that problem belongs to, so accepting a plan that replaces* it can retire exactly that node without parsing the key. */problemTaskId?: string;@@ -514,7 +519,15 @@ export interface GoalRolloutPolicy {* why a gate passed or held, not only that it did.*/export type GoalRolloutGateCheckKey =- 'axes_covered' | 'no_open_decision' | 'plan_written' | 'units_settled' | 'units_succeeded';+ | 'axes_covered'+ /** Every person's intervention in the batch was accounted for by its retro. */+ | 'interventions_accounted'+ | 'no_open_decision'+ | 'plan_written'+ /** The batch's delivered units passed the verifier its retro produced. */+ | 'reverified'+ | 'units_settled'+ | 'units_succeeded';export interface GoalRolloutGateCheck {/** For a count check: how many of `total` held, e.g. 5 of 5 units ran through. */@@ -579,6 +592,11 @@ export type GoalRolloutPhase =| 'release_review'/** The owner sent the plan back; the main Agent is rewriting it for the owner to review again. */| 'plan_revision'+ /**+ * The round's probes settled; the main Agent rewrites the plan from them, and+ * the gate judges them straight from here (`release_review` / `pattern_break`).+ */+ | 'plan_distill'| 'done';/**@@ -684,6 +702,13 @@ export interface GoalRolloutState {assayNodeId?: string;/** The `batch` container node. */batchNodeId: string;+ /**+ * The probe set the plan was last distilled from (see `probeSetKey`), or+ * skipped for want of a main Agent turn. Set while still in `plan_distill`, it+ * tells the gate the plan is ready to judge the probes on. Re-opened or re-run+ * probes form a new set and are distilled again.+ */+ distilledProbes?: string;/*** Gate verdicts, oldest first. Each round keeps its most recent few, so a* round that was judged never loses its latest verdict to later rounds.@@ -698,6 +723,12 @@ export interface GoalRolloutState {* A restarted canary starts a new round and clears it.*/massNodeIds?: string[];+ /**+ * The main Agent's plan rewritten from the settled probes, while the phase is+ * `plan_distill`. The next advance lands it as the plan skill's next version+ * and judges the gate in the same step.+ */+ pendingDistill?: { reason: string; recipe: string };/*** The owner's correction a sent-back release waits on, while the phase is* `plan_revision`. The main Agent rewrites the plan from it (`revisedRecipe`)@@ -739,6 +770,8 @@ export interface GoalRolloutState {releaseGateAcceptanceId?: string;/** The decision node a held release waits on, while the phase is `release_review`. */releaseReviewNodeId?: string;+ /** One retro per execution — the probes, then each roster wave — oldest first. */+ retros?: GoalRolloutRetro[];/** Node id of the current Template (finding) node. */templateNodeId?: string;/** Current Template revision; incremented each time the recipe is revised. */@@ -751,6 +784,8 @@ export interface GoalRolloutState {* delivered under the old recipe drop out.*/unitTitles?: string[];+ /** The batch's verifier, once a retro produced one. */+ verifier?: GoalRolloutVerifier;/** How many mass waves have been released. */waveIndex: number;/** Roster waves released so far across every round; `waveIndex` restarts per round. */diff --git a/packages/types/src/goalRetro.ts b/packages/types/src/goalRetro.tsnew file mode 100644index 00000000000..52fa62851df--- /dev/null+++ b/packages/types/src/goalRetro.ts@@ -0,0 +1,35 @@+/**+ * The retro after one execution of a batch — its probes, or one roster wave.+ * It distills two layers from what ran: experience into the plan skill (how a+ * unit is done) and criteria into the verifier (what a unit is judged on). The+ * gate only opens on a retro that is done.+ */+export interface GoalRolloutRetro {+ /** Every person's intervention in that execution, and how many it accounted for. */+ interventions?: { accounted: number; total: number };+ /**+ * The round this retro opened: a wave sent back at its gate is distilled into+ * the plan and criteria the next round runs on.+ */+ opens?: number;+ /** The delivered units re-verified against the retro's verifier. */+ reverify?: { failed?: number; passed: number; total: number };+ /** Plan steps the retro added or changed. */+ skillChanges?: number;+ /** The plan skill version the retro produced. */+ skillVersion?: number;+ status: 'blocked' | 'done' | 'running';+ /** Criteria the retro added, tightened, or loosened (loosening waits on a person). */+ verifierChanges?: { added?: number; loosened?: number; tightened?: number };+ /** The verifier version the retro produced. */+ verifierVersion?: number;+ /** What it read: 0 for the probes, N for roster wave N (1-based). */+ wave: number;+}++/** The batch's verifier: what every unit's acceptance is judged on, versioned by its retros. */+export interface GoalRolloutVerifier {+ /** Blocking and advisory criteria in the current version. */+ criteria: { block: number; warn: number };+ version: number;+}diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex 91b863b8c5f..77d794340db 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -36,6 +36,7 @@ export * from './ftsSearch';export * from './generation';export * from './goal';export * from './goalReport';+export * from './goalRetro';export * from './goalSubscription';export * from './heteroSessionImport';export * from './home';diff --git a/src/features/AgentGoals/ProcessControl/BatchGate/GateChecksHint.tsx b/src/features/AgentGoals/ProcessControl/BatchGate/GateChecksHint.tsxnew file mode 100644index 00000000000..83132326df7--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/BatchGate/GateChecksHint.tsx@@ -0,0 +1,81 @@+import type { GoalRolloutGateCheckKey } from '@lobechat/types';+import { createStaticStyles, cssVar, Flexbox, Icon } from '@lobehub/ui';+import { CircleCheck, CircleDashed, CircleX } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { type GateCheckLike, useGateCheckCopy } from './useGateCheckCopy';++/** Checks a batch's retro answers for; every other check is about the execution. */+const RETRO_CHECKS = new Set<GoalRolloutGateCheckKey>(['interventions_accounted', 'reverified']);++const styles = createStaticStyles(({ css }) => ({+ root: css`+ min-width: 220px;+ max-width: 300px;+ padding-block: 2px;+ font-size: 12px;+ `,+ section: css`+ font-size: 11px;+ color: ${cssVar.colorTextTertiary};+ `,+ detail: css`+ color: ${cssVar.colorTextTertiary};+ `,+}));++const CheckRow = memo<{ check: GateCheckLike }>(({ check }) => {+ const copy = useGateCheckCopy();+ const { detail, label } = copy(check);+ const visual =+ check.passed === undefined+ ? { color: cssVar.colorTextQuaternary, icon: CircleDashed }+ : check.passed+ ? { color: cssVar.green9, icon: CircleCheck }+ : { color: cssVar.colorError, icon: CircleX };+ return (+ <Flexbox horizontal align={'flex-start'} gap={6}>+ <Icon+ icon={visual.icon}+ size={13}+ style={{ color: visual.color, flex: 'none', marginTop: 2 }}+ />+ <span>+ {label}+ {detail && <span className={styles.detail}> · {detail}</span>}+ </span>+ </Flexbox>+ );+});++CheckRow.displayName = 'GoalGateCheckRow';++/**+ * What a batch gate checks, behind the info icon on its card: the execution's+ * checks, then what the retro answers for. Before a verdict every check reads+ * as still to be judged; after one, each carries its result.+ */+const GateChecksHint = memo<{ checks: GateCheckLike[] }>(({ checks }) => {+ const { t } = useTranslation('chat');+ const sections = [+ { checks: checks.filter((check) => !RETRO_CHECKS.has(check.key)), key: 'execution' as const },+ { checks: checks.filter((check) => RETRO_CHECKS.has(check.key)), key: 'retro' as const },+ ].filter((section) => section.checks.length);+ return (+ <Flexbox className={styles.root} gap={8}>+ {sections.map((section) => (+ <Flexbox gap={4} key={section.key}>+ <span className={styles.section}>{t(`goalBatch.gate.hintSection.${section.key}`)}</span>+ {section.checks.map((check) => (+ <CheckRow check={check} key={check.key} />+ ))}+ </Flexbox>+ ))}+ </Flexbox>+ );+});++GateChecksHint.displayName = 'GoalGateChecksHint';++export default GateChecksHint;diff --git a/src/features/AgentGoals/ProcessControl/BatchGate/GateDetail.tsx b/src/features/AgentGoals/ProcessControl/BatchGate/GateDetail.tsxindex 2c0277548d9..93dd02a2eba 100644--- a/src/features/AgentGoals/ProcessControl/BatchGate/GateDetail.tsx+++ b/src/features/AgentGoals/ProcessControl/BatchGate/GateDetail.tsx@@ -129,6 +129,8 @@ const GateDetail = memo<GateDetailProps>(({ decide, graph, model, onOpenNode, rocase 'checking': {if (isCurrent && model.phase === 'plan_revision')return t('goalBatch.gatePanel.next.revising');+ if (isCurrent && model.phase === 'plan_distill')+ return t('goalBatch.gatePanel.next.distilling');return t('goalBatch.gatePanel.next.checking');}case 'locked': {diff --git a/src/features/AgentGoals/ProcessControl/Graph/BatchGroups.tsx b/src/features/AgentGoals/ProcessControl/Graph/BatchGroups.tsxindex a2b2bfa218c..72dd8c272c6 100644--- a/src/features/AgentGoals/ProcessControl/Graph/BatchGroups.tsx+++ b/src/features/AgentGoals/ProcessControl/Graph/BatchGroups.tsx@@ -1,5 +1,6 @@'use client';+import type { GoalRolloutPlanSkill, GoalRolloutRetro, GoalRolloutVerifier } from '@lobechat/types';import {ActionIcon,Button,@@ -21,7 +22,10 @@ import {HandIcon,Info,type LucideIcon,+ NotebookPen,+ ShieldCheck,TestTubeDiagonal,+ TriangleAlert,Waves,} from 'lucide-react';import { memo, type ReactNode, useState } from 'react';@@ -31,8 +35,15 @@ import { TASK_STATUS_VISUALS } from '@/components/ExecutionStatus';import RunningGlyph from '@/features/Home/components/RunningGlyph';import type { GoalNodeView } from '../goalGraphViewModel';-import { KIND_COLOR, KIND_ICON } from '../shared';-import { BATCH_FRAME_HEAD, BATCH_ROW_LABEL, BATCH_SQUARE, BATCH_SQUARE_GAP } from './batchLayout';+import { GATE_COLOR, KIND_COLOR, KIND_ICON, SKILL_COLOR, SKILL_ICON } from '../shared';+import {+ BATCH_FRAME_HEAD,+ BATCH_RETRO_MARK,+ BATCH_RETRO_ROW,+ BATCH_ROW_LABEL,+ BATCH_SQUARE,+ BATCH_SQUARE_GAP,+} from './batchLayout';import {type BatchCell,type BatchCellState,@@ -157,8 +168,13 @@ const styles = createStaticStyles(({ css }) => ({background: ${cssVar.colorBgContainer};`,groupTitle: css`+ overflow: hidden;++ min-width: 0;+font-size: 13px;font-weight: 600;+ text-overflow: ellipsis;white-space: nowrap;`,/* Trials: one row of two cards, status above each card. */@@ -230,6 +246,41 @@ const styles = createStaticStyles(({ css }) => ({font-size: 11px;color: ${cssVar.colorTextTertiary};`,+ retroMark: css`+ display: inline-flex;+ flex: none;+ gap: 4px;+ align-items: center;++ width: ${BATCH_RETRO_MARK}px;+ margin-inline-start: 4px;+ padding-inline-start: 8px;+ border-inline-start: 1px dashed ${cssVar.colorBorder};++ font-size: 10px;+ line-height: 1;+ white-space: nowrap;+ `,+ retroBody: css`+ display: flex;+ flex-direction: column;+ gap: 6px;++ padding-block: 8px 10px;+ padding-inline: 10px;+ `,+ retroLayer: css`+ /* A short row: the card radius would read as a pill. */+ border-radius: ${cssVar.borderRadiusSM};+ `,+ retroRow: css`+ cursor: default;+ height: ${BATCH_RETRO_ROW}px;++ &:hover {+ border-color: ${cssVar.colorBorderSecondary};+ }+ `,rowLabel: css`flex: none;@@ -353,16 +404,18 @@ const GroupShell = memo<{iconColor: string;onEnter?: () => void;status: GroupStatus;+ /** Status (and foot) in the head's right corner, with no foot row of its own. */+ statusInHead?: boolean;title: string;/** A control that belongs in the head, before the enter button. */toolbar?: ReactNode;-}>(({ children, foot, hint, icon, iconColor, onEnter, status, title, toolbar }) => {+}>(({ children, foot, hint, icon, iconColor, onEnter, status, statusInHead, title, toolbar }) => {const { t } = useTranslation('chat');return (<div className={styles.group}><GroupHandles /><div className={styles.groupHead}>- <Flexbox horizontal align={'center'} gap={7} style={{ minWidth: 0 }}>+ <Flexbox horizontal align={'center'} gap={7} style={{ minWidth: 0, overflow: 'hidden' }}><Icon color={iconColor} icon={icon} size={14} /><span className={styles.groupTitle}>{title}</span>{hint && (@@ -374,6 +427,12 @@ const GroupShell = memo<{)}</Flexbox><Flexbox horizontal align={'center'} gap={8} style={{ flex: 'none' }}>+ {statusInHead && (+ <>+ <StatusText {...status} />+ {foot && <span className={styles.muted}>{foot}</span>}+ </>+ )}{toolbar}{onEnter && (<Button@@ -390,10 +449,12 @@ const GroupShell = memo<{</Flexbox></div>{children}- <div className={styles.foot}>- <StatusText {...status} />- {foot && <span className={styles.muted}>{foot}</span>}- </div>+ {!statusInHead && (+ <div className={styles.foot}>+ <StatusText {...status} />+ {foot && <span className={styles.muted}>{foot}</span>}+ </div>+ )}</div>);});@@ -648,51 +709,90 @@ export interface BatchWaveRow {wave: number;}-const WaveRows = memo<{ onSelect: (nodeId: string) => void; rows: BatchWaveRow[] }>(- ({ onSelect, rows }) => {- const { t } = useTranslation('chat');- const label = useCellLabel();- return (- <>- {rows.map(({ cells, wave }) => {- const hot = cells.some((cell) => cell.state === 'human' || cell.reopenedIn);- return (- <Flexbox horizontal align={'center'} data-wave={wave} gap={8} key={wave}>- <span className={cx(styles.rowLabel, hot && styles.rowLabelHot)}>- {t('goalBatch.waves.row', { number: wave + 1 })}- </span>- <Flexbox horizontal gap={BATCH_SQUARE_GAP}>- {cells.map((cell) => (- <Square- key={cell.index}- nodeId={cell.nodeId}- state={cell.state}- tooltip={[- t('goalBatch.cell.tooltip', {- index: cell.index + 1,- state: label(cell.state),- title: cell.title,- wave: wave + 1,- }),- cell.reopenedIn- ? t('goalBatch.cell.reopened', { revision: cell.reopenedIn })- : cell.runIn- ? t('goalBatch.cell.runIn', { revision: cell.runIn })- : undefined,- ]- .filter(Boolean)- .join(' · ')}- onSelect={onSelect}- />- ))}- </Flexbox>+/**+ * The mark after a wave's squares: the retro that read it. Each execution+ * ends in one — experience into the plan, criteria into the verifier — so a+ * wave that finished without one says it still owes it.+ */+const RetroMark = memo<{ cells: BatchCell[]; retro?: GoalRolloutRetro }>(({ cells, retro }) => {+ const { t } = useTranslation('chat');+ const finished = cells.length > 0 && cells.every((cell) => cell.state === 'done');+ if (!retro && !finished) return <span className={styles.retroMark} />;+ const status = !retro+ ? { ...CELL_VISUAL.backlog, text: t('goalBatch.retro.mark.pending') }+ : retro.status === 'running'+ ? { ...CELL_VISUAL.running, running: true, text: t('goalBatch.retro.mark.running') }+ : retro.status === 'blocked'+ ? { color: cssVar.colorError, icon: TriangleAlert, text: t('goalBatch.retro.mark.blocked') }+ : {+ ...CELL_VISUAL.done,+ text: t('goalBatch.retro.mark.done', {+ skill: retro.skillVersion,+ verifier: retro.verifierVersion,+ }),+ };+ return (+ <Tooltip title={retro ? <RetroSummary retro={retro} /> : t('goalBatch.retro.mark.pendingHint')}>+ <span className={cx('nodrag', styles.retroMark)} data-retro-mark={retro?.status ?? 'pending'}>+ <StatusText {...status} />+ </span>+ </Tooltip>+ );+});++RetroMark.displayName = 'GoalBatchRetroMark';++const WaveRows = memo<{+ onSelect: (nodeId: string) => void;+ /** The retro after each roster wave, when the batch runs them. */+ retros?: GoalRolloutRetro[];+ rows: BatchWaveRow[];+}>(({ onSelect, retros, rows }) => {+ const { t } = useTranslation('chat');+ const label = useCellLabel();+ return (+ <>+ {rows.map(({ cells, wave }) => {+ const hot = cells.some((cell) => cell.state === 'human' || cell.reopenedIn);+ return (+ <Flexbox horizontal align={'center'} data-wave={wave} gap={8} key={wave}>+ <span className={cx(styles.rowLabel, hot && styles.rowLabelHot)}>+ {t('goalBatch.waves.row', { number: wave + 1 })}+ </span>+ <Flexbox horizontal gap={BATCH_SQUARE_GAP}>+ {cells.map((cell) => (+ <Square+ key={cell.index}+ nodeId={cell.nodeId}+ state={cell.state}+ tooltip={[+ t('goalBatch.cell.tooltip', {+ index: cell.index + 1,+ state: label(cell.state),+ title: cell.title,+ wave: wave + 1,+ }),+ cell.reopenedIn+ ? t('goalBatch.cell.reopened', { revision: cell.reopenedIn })+ : cell.runIn+ ? t('goalBatch.cell.runIn', { revision: cell.runIn })+ : undefined,+ ]+ .filter(Boolean)+ .join(' · ')}+ onSelect={onSelect}+ />+ ))}</Flexbox>- );- })}- </>- );- },-);+ {retros && (+ <RetroMark cells={cells} retro={retros.find((retro) => retro.wave === wave + 1)} />+ )}+ </Flexbox>+ );+ })}+ </>+ );+});WaveRows.displayName = 'GoalBatchWaveRows';@@ -724,6 +824,8 @@ export interface BatchWavesData extends Record<string, unknown> {onSelect: (nodeId: string) => void;/** The units this round re-opened — its own canary (rounds after the first). */probes: BatchProbe[];+ /** The retro after each roster wave, when the batch runs them. */+ retros?: GoalRolloutRetro[];revision: number;/** The roster waves this round released, or still holds as the latest round. */rows: BatchWaveRow[];@@ -733,7 +835,8 @@ export interface BatchWavesData extends Record<string, unknown> {/** A round's waves: the units it re-opened, then the roster waves it owns. */export const BatchWavesGroup = memo<NodeProps>(({ data }) => {- const { onEnter, onSelect, probes, revision, rows, started, waveSize } = data as BatchWavesData;+ const { onEnter, onSelect, probes, retros, revision, rows, started, waveSize } =+ data as BatchWavesData;const { t } = useTranslation('chat');const label = useCellLabel();const originCopy = useOriginCopy();@@ -793,7 +896,7 @@ export const BatchWavesGroup = memo<NodeProps>(({ data }) => {</Flexbox></Flexbox>))}- <WaveRows rows={rows} onSelect={onSelect} />+ <WaveRows retros={retros} rows={rows} onSelect={onSelect} /></div></GroupShell>);@@ -801,6 +904,160 @@ export const BatchWavesGroup = memo<NodeProps>(({ data }) => {BatchWavesGroup.displayName = 'GoalBatchWavesGroup';+// ─── Retro (what an execution taught, before the gate) ──────────────────++/** What one retro produced and what it checked, for a tooltip. */+const RetroSummary = memo<{ retro: GoalRolloutRetro }>(({ retro }) => {+ const { t } = useTranslation('chat');+ return (+ <Flexbox gap={4}>+ {retro.skillVersion !== undefined && (+ <span>+ {t('goalBatch.retro.summary.skill', {+ count: retro.skillChanges ?? 0,+ version: retro.skillVersion,+ })}+ </span>+ )}+ {retro.verifierVersion !== undefined && (+ <span>+ {t('goalBatch.retro.summary.verifier', {+ added: retro.verifierChanges?.added ?? 0,+ loosened: retro.verifierChanges?.loosened ?? 0,+ version: retro.verifierVersion,+ })}+ </span>+ )}+ {retro.interventions && (+ <span>{t('goalBatch.retro.summary.interventions', retro.interventions)}</span>+ )}+ {retro.reverify && <span>{t('goalBatch.retro.summary.reverify', retro.reverify)}</span>}+ </Flexbox>+ );+});++RetroSummary.displayName = 'GoalBatchRetroSummary';++const RetroLayer = memo<{+ color: { line: string; soft: string };+ icon: LucideIcon;+ onOpen?: () => void;+ subtitle: string;+ title: string;+}>(({ color, icon, onOpen, subtitle, title }) => (+ <div+ className={cx('nodrag', styles.card, styles.retroLayer, !onOpen && styles.retroRow)}+ role={onOpen ? 'button' : undefined}+ style={{ height: BATCH_RETRO_ROW }}+ tabIndex={onOpen ? 0 : undefined}+ onClick={(event) => {+ event.stopPropagation();+ onOpen?.();+ }}+ onKeyDown={(event) => {+ if (onOpen && (event.key === 'Enter' || event.key === ' ')) {+ event.preventDefault();+ onOpen();+ }+ }}+ >+ <Flexbox horizontal align={'center'} gap={7}>+ <span className={styles.glyph} style={{ background: color.soft, color: color.line }}>+ <Icon icon={icon} size={14} />+ </span>+ <Flexbox style={{ flex: 1, minWidth: 0 }}>+ <span className={styles.cardTitle}>{title}</span>+ <span className={cx(styles.cardTitle, styles.muted)} style={{ fontWeight: 400 }}>+ {subtitle}+ </span>+ </Flexbox>+ </Flexbox>+ </div>+));++RetroLayer.displayName = 'GoalBatchRetroLayer';++export interface BatchRetroData extends Record<string, unknown> {+ onSelect: (nodeId: string) => void;+ planSkill?: GoalRolloutPlanSkill;+ retro: GoalRolloutRetro;+ /** The plan node the experience layer opens. */+ templateId?: string;+ verifier?: GoalRolloutVerifier;+}++/**+ * The retro after the trials, ahead of the gate: two layers distilled from what+ * the trials ran into — experience into the plan skill every unit loads, and+ * criteria into the verifier every unit is judged on. The gate opens on it.+ */+export const BatchRetroGroup = memo<NodeProps>(({ data }) => {+ const { onSelect, planSkill, retro, templateId, verifier } = data as BatchRetroData;+ const { t } = useTranslation('chat');+ const status: GroupStatus =+ retro.status === 'running'+ ? { ...CELL_VISUAL.running, running: true, text: t('goalBatch.retro.status.running') }+ : retro.status === 'blocked'+ ? {+ color: cssVar.colorError,+ icon: TriangleAlert,+ text: t('goalBatch.retro.status.blocked'),+ }+ : { ...CELL_VISUAL.done, text: t('goalBatch.retro.status.done') };+ // Re-verifying the units is the gate's check; the retro answers for the interventions.+ const foot = retro.interventions+ ? t('goalBatch.retro.interventionsShort', retro.interventions)+ : undefined;+ const criteria = verifier?.criteria;+ return (+ <GroupShell+ statusInHead+ foot={foot}+ hint={t('goalBatch.retro.hint')}+ icon={NotebookPen}+ iconColor={GATE_COLOR.line}+ status={status}+ title={+ retro.wave === 0+ ? t('goalBatch.retro.title')+ : t('goalBatch.retro.titleWave', { wave: retro.wave })+ }+ >+ <div className={styles.retroBody}>+ <RetroLayer+ color={SKILL_COLOR}+ icon={SKILL_ICON}+ title={t('goalBatch.retro.skill', { version: retro.skillVersion ?? 1 })}+ subtitle={[+ planSkill && `user-skills:${planSkill.name}`,+ retro.skillChanges !== undefined &&+ t('goalBatch.retro.changes', { count: retro.skillChanges }),+ ]+ .filter(Boolean)+ .join(' · ')}+ onOpen={templateId ? () => onSelect(templateId) : undefined}+ />+ <RetroLayer+ color={{ line: cssVar.colorInfo, soft: cssVar.colorInfoBg }}+ icon={ShieldCheck}+ title={t('goalBatch.retro.verifier', { version: retro.verifierVersion ?? 1 })}+ subtitle={[+ criteria && t('goalBatch.retro.criteria', criteria),+ retro.verifierChanges?.added &&+ t('goalBatch.retro.added', { count: retro.verifierChanges.added }),+ retro.verifierChanges?.loosened &&+ t('goalBatch.retro.loosened', { count: retro.verifierChanges.loosened }),+ ]+ .filter(Boolean)+ .join(' · ')}+ />+ </div>+ </GroupShell>+ );+});++BatchRetroGroup.displayName = 'GoalBatchRetroGroup';+export interface BatchRoundFrameData extends Record<string, unknown> {revision: number;}diff --git a/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx b/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsxindex 01994952ee8..41a8077ac50 100644--- a/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx+++ b/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx@@ -45,6 +45,8 @@ export interface GraphNodeData extends Record<string, unknown> {chip?: StateChip | null;/** Detail behind an info icon beside the title, e.g. what a gate checks. */hint?: ReactNode;+ /** Where the hint opens; beside the card when above would cover its neighbours. */+ hintPlacement?: 'rightTop' | 'top';icon?: LucideIcon;/** Glyph colours when the card is not its kind — a release gate. */palette?: { line: string; soft: string };@@ -408,7 +410,7 @@ const GraphNodeView = memo<NodeProps>(({ data }) => {{presentation?.title ??(coordinatorTitleKey ? t(coordinatorTitleKey as any) : node.title)}{presentation?.hint && (- <Tooltip title={presentation.hint}>+ <Tooltip placement={presentation.hintPlacement} title={presentation.hint}><span data-hint className={cx('nodrag', styles.hint)} role="img"><Icon icon={Info} size={13} /></span>diff --git a/src/features/AgentGoals/ProcessControl/Graph/batchFlowNodes.ts b/src/features/AgentGoals/ProcessControl/Graph/batchFlowNodes.tsnew file mode 100644index 00000000000..f7c48920420--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/Graph/batchFlowNodes.ts@@ -0,0 +1,117 @@+import type { Node as FlowNode } from '@xyflow/react';++import type { GoalGraphView } from '../goalGraphViewModel';+import type { BatchRetroData, BatchRoundFrameData, BatchWavesData } from './BatchGroups';+import type { BatchLayout } from './batchLayout';+import { type BatchModel, roundRetro } from './batchModel';+import { batchStageId } from './batchScopeLayout';+import type { LayoutBox } from './layout';++/** Where a batch piece lands on the map: its parent and position. */+type PlaceInMap = (+ id: string,+ box: LayoutBox | undefined,+ owner?: string,+) => { parentId?: string; position: { x: number; y: number } };++interface BatchFlowNodesInput {+ batches: Map<string, { layout?: BatchLayout; model: BatchModel }>;+ byId: GoalGraphView['byId'];+ onEnter: (id: string) => void;+ onSelect: (id: string) => void;+ placeInMap: PlaceInMap;+ visibleIds: ReadonlySet<string>;+}++/**+ * The map nodes an open batch draws for its groups — the trials, each round's+ * frame, its retro and its waves. The plan and gate are real graph nodes and+ * are placed with the rest of the map.+ */+export const buildBatchFlowNodes = ({+ batches,+ byId,+ onEnter,+ onSelect,+ placeInMap,+ visibleIds,+}: BatchFlowNodesInput): FlowNode[] =>+ [...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.+ const rowsOf = (revision: number) =>+ model.waves.flatMap((cells, wave) =>+ model.waveRounds[wave] === revision ? [{ cells, wave }] : [],+ );+ return layout.groups.flatMap((group): FlowNode[] => {+ const round = model.rounds[group.revision - 1];+ const base = {+ draggable: false,+ id: group.id,+ ...placeInMap(group.id, group.box, batchId),+ selectable: false,+ width: group.box.width,+ };+ // A round's frame sits behind its nodes and the links between them.+ if (group.kind === 'round')+ return [+ {+ ...base,+ data: { revision: group.revision } satisfies BatchRoundFrameData,+ style: { height: group.box.height, width: group.box.width },+ type: 'goalBatchRound',+ zIndex: -1,+ },+ ];+ if (group.kind === 'retro') {+ const retro = roundRetro(model, group.revision);+ if (!retro) return [];+ return [+ {+ ...base,+ data: {+ onSelect,+ planSkill: model.planSkill,+ retro,+ templateId: round.templateId,+ verifier: model.verifier,+ } satisfies BatchRetroData,+ style: { width: group.box.width },+ type: 'goalBatchRetro',+ },+ ];+ }+ const data =+ group.kind === 'experimentProbe'+ ? {+ onEnter: () => onEnter(batchStageId(batchId, 0)),+ onSelect,+ probes: first.probes,+ started: first.probes.some((probe) => probe.state !== 'backlog'),+ views: byId,+ }+ : ({+ onEnter: () => onEnter(batchStageId(batchId, group.revision)),+ onSelect,+ probes: round.probes,+ retros: model.retros.length ? model.retros : undefined,+ revision: group.revision,+ rows: rowsOf(group.revision),+ started:+ group.revision === 1+ ? !first.assayId || first.gate === 'passed' || first.gate === 'rejected'+ : round.probes.some((probe) => probe.state !== 'backlog'),+ waveSize: model.waveSize,+ } satisfies BatchWavesData);+ return [+ {+ ...base,+ data,+ // Width is the layout's; height hugs the content, the layout only reserves it.+ style: { width: group.box.width },+ type: group.kind === 'experimentProbe' ? 'goalBatchExperimentProbe' : 'goalBatchWaves',+ },+ ];+ });+ });diff --git a/src/features/AgentGoals/ProcessControl/Graph/batchLayout.ts b/src/features/AgentGoals/ProcessControl/Graph/batchLayout.tsindex ec6473fc0cc..561c1dc5440 100644--- a/src/features/AgentGoals/ProcessControl/Graph/batchLayout.ts+++ b/src/features/AgentGoals/ProcessControl/Graph/batchLayout.ts@@ -1,5 +1,5 @@import type { GoalGraphView } from '../goalGraphViewModel';-import { type BatchModel, type BatchRound, reopenedRows } from './batchModel';+import { type BatchModel, type BatchRound, reopenedRows, roundRetro } from './batchModel';import type { LayoutBox } from './layout';/**@@ -30,6 +30,11 @@ export const BATCH_SQUARE = 12;/** Row gap equals column gap, so the waves read as a square grid. */export const BATCH_SQUARE_GAP = 10;export const BATCH_ROW_LABEL = 44;+/** Room after a wave's squares for the mark of the retro that read it. */+export const BATCH_RETRO_MARK = 150;+/** One layer row of a retro group: experience, then criteria. */+export const BATCH_RETRO_ROW = 44;+const BATCH_RETRO_ROW_GAP = 6;/** A round frame's label row; its side links leave at half this height. */export const BATCH_FRAME_HEAD = 38;@@ -48,8 +53,9 @@ const DECISION_GAP = 16;* `experimentProbe`: the cold start — the first round's trials, not a* candidate-answer `experiment`. `round`: the frame around one round's nodes.* `waves`: the units one round re-opened and the roster waves it owns.+ * `retro`: what the round's trials taught — experience and criteria — before its gate.*/-export type BatchGroupKind = 'experimentProbe' | 'round' | 'waves';+export type BatchGroupKind = 'experimentProbe' | 'retro' | 'round' | 'waves';export interface BatchGroupSpec {box: LayoutBox;@@ -93,10 +99,15 @@ const groupHeight = (body: number) => BATCH_GROUP_HEAD + 8 + body + 4 + BATCH_GRconst stack = (count: number, size: number, gap: number) =>count > 0 ? count * size + (count - 1) * gap : 0;-export const wavesWidth = (waveSize: number) =>+export const wavesWidth = (waveSize: number, retroMarks = false) =>Math.max(CARD.width,- BATCH_GROUP_PAD * 2 + BATCH_ROW_LABEL + 8 + stack(waveSize, BATCH_SQUARE, BATCH_SQUARE_GAP) + 2,+ BATCH_GROUP_PAD * 2 ++ BATCH_ROW_LABEL ++ 8 ++ stack(waveSize, BATCH_SQUARE, BATCH_SQUARE_GAP) ++ 2 ++ (retroMarks ? BATCH_RETRO_MARK : 0),);/** How many square rows a round's waves draw: its re-opened rows, then its waves. */@@ -118,7 +129,8 @@ export const layoutBatch = (graph: GoalGraphView, model: BatchModel): BatchLayou};const [first] = rounds;- const innerW = Math.max(CARD.width, wavesWidth(model.waveSize));+ const retroMarks = model.retros.length > 0;+ const innerW = Math.max(CARD.width, wavesWidth(model.waveSize, retroMarks));const frameW = innerW + FRAME_PAD * 2;let right = 0;let previous: string | undefined;@@ -147,7 +159,21 @@ export const layoutBatch = (graph: GoalGraphView, model: BatchModel): BatchLayouabove = id;y = box.y + box.height + STACK_GAP;};- for (const id of [round.templateId, round.assayId]) {+ // A round starts from the retro that produced its plan and criteria — the+ // cold start's, or the broken wave's — in the place the plan card stood,+ // ahead of the gate.+ const retro = roundRetro(model, round.revision);+ if (retro) {+ // Its status sits in the head, so it has no foot row.+ const box = {+ height: groupHeight(stack(2, BATCH_RETRO_ROW, BATCH_RETRO_ROW_GAP)) - BATCH_GROUP_FOOT + 8,+ width: innerW,+ x: left,+ y,+ };+ place(addGroup('retro', round.revision, box), box);+ }+ for (const id of [retro ? undefined : round.templateId, round.assayId]) {if (!id) continue;nodeIds.add(id);place(id, { ...CARD, x: left + (innerW - CARD.width) / 2, y });diff --git a/src/features/AgentGoals/ProcessControl/Graph/batchModel.ts b/src/features/AgentGoals/ProcessControl/Graph/batchModel.tsindex aac1b622098..f9989b396a7 100644--- a/src/features/AgentGoals/ProcessControl/Graph/batchModel.ts+++ b/src/features/AgentGoals/ProcessControl/Graph/batchModel.ts@@ -11,6 +11,8 @@ import type {GoalRolloutLearning,GoalRolloutPhase,GoalRolloutPlanSkill,+ GoalRolloutRetro,+ GoalRolloutVerifier,} from '@lobechat/types';import { experimentMembers } from '@lobechat/utils/goalGraph';@@ -117,7 +119,11 @@ export interface BatchModel {phase?: GoalRolloutPhase;/** The execution plan as a skill in the user's library; round N is its version N. */planSkill?: GoalRolloutPlanSkill;+ /** The retro after each execution: index 0 reads the probes, N reads roster wave N. */+ retros: GoalRolloutRetro[];rounds: BatchRound[];+ /** What every unit is judged on, once a retro produced it. */+ verifier?: GoalRolloutVerifier;/*** The round (1-based revision) each wave belongs to. A released wave belongs* to the plan it went out under; the waves not yet released belong to the@@ -414,6 +420,10 @@ export const buildBatchModel = (graph: GoalGraphView, batchId: string): BatchMod{ key: 'no_open_decision' },{ key: 'plan_written' },...(policy?.spec?.variantAxes?.length ? [{ key: 'axes_covered' as const }] : []),+ // A batch that runs retros opens its gate on them: re-verified, every intervention accounted.+ ...(state?.retros?.length+ ? [{ key: 'reverified' as const }, { key: 'interventions_accounted' as const }]+ : []),];return {@@ -423,7 +433,9 @@ export const buildBatchModel = (graph: GoalGraphView, batchId: string): BatchModlearnings: state?.learnings ?? [],phase: state?.phase,planSkill: state?.planSkill,+ retros: state?.retros ?? [],rounds,+ verifier: state?.verifier,waveRounds,waves,waveSize,@@ -557,3 +569,11 @@ export const findBatchPlan = (const round = model.rounds.find((item) => item.templateId === nodeId);return round ? { model, round } : undefined;};++/**+ * The retro a round starts from, drawn at the top of its frame: the cold+ * start's for the first round, and for a later one the retro of the wave whose+ * break opened it.+ */+export const roundRetro = (model: Pick<BatchModel, 'retros'>, revision: number) =>+ model.retros.find((retro) => (revision === 1 ? retro.wave === 0 : retro.opens === revision));diff --git a/src/features/AgentGoals/ProcessControl/Graph/experimentStatus.test.ts b/src/features/AgentGoals/ProcessControl/Graph/experimentStatus.test.tsindex 7a6421f7ddb..fba672bd3c6 100644--- a/src/features/AgentGoals/ProcessControl/Graph/experimentStatus.test.ts+++ b/src/features/AgentGoals/ProcessControl/Graph/experimentStatus.test.ts@@ -6,6 +6,7 @@ describe('batchContainerStatus', () => {it('reads an open batch from its rollout phase, not its never-moving node', () => {expect(batchContainerStatus('probe')).toBe('active');expect(batchContainerStatus('mass')).toBe('active');+ expect(batchContainerStatus('plan_distill')).toBe('active');expect(batchContainerStatus('pattern_break')).toBe('waiting');expect(batchContainerStatus('done')).toBe('resolved');});diff --git a/src/features/AgentGoals/ProcessControl/Graph/experimentStatus.ts b/src/features/AgentGoals/ProcessControl/Graph/experimentStatus.tsindex 3aa8649c621..7be64d4a921 100644--- a/src/features/AgentGoals/ProcessControl/Graph/experimentStatus.ts+++ b/src/features/AgentGoals/ProcessControl/Graph/experimentStatus.ts@@ -28,6 +28,7 @@ export const batchContainerStatus = (phase?: GoalRolloutPhase): GoalNodeStatus |case 'release_review': {return 'waiting';}+ case 'plan_distill':case 'plan_revision':case 'probe':case 'mass': {diff --git a/src/features/AgentGoals/ProcessControl/Graph/index.tsx b/src/features/AgentGoals/ProcessControl/Graph/index.tsxindex 1f2c0a2e984..90246ba0ed1 100644--- a/src/features/AgentGoals/ProcessControl/Graph/index.tsx+++ b/src/features/AgentGoals/ProcessControl/Graph/index.tsx@@ -46,7 +46,7 @@ import {graphNodeLabel,isContainerKind,} from '../../Experiments/model';-import { useGateCheckCopy } from '../BatchGate/useGateCheckCopy';+import GateChecksHint from '../BatchGate/GateChecksHint';import {type GoalGraphView,type GoalNodeView,@@ -54,11 +54,11 @@ import {scopeGraphView,} from '../goalGraphViewModel';import { GATE_COLOR, SKILL_COLOR, SKILL_ICON } from '../shared';+import { buildBatchFlowNodes } from './batchFlowNodes';import {BatchExperimentProbeGroup,+ BatchRetroGroup,BatchRoundFrame,- type BatchRoundFrameData,- type BatchWavesData,BatchWavesGroup,CELL_VISUAL,} from './BatchGroups';@@ -352,6 +352,7 @@ const edgeTypes = { exploration: ExplorationEdge };const nodeTypes = {goalBatchExperimentProbe: BatchExperimentProbeGroup,+ goalBatchRetro: BatchRetroGroup,goalBatchRound: BatchRoundFrame,goalBatchWaves: BatchWavesGroup,goalExperiment: GraphNodeView,@@ -363,6 +364,7 @@ const nodeTypes = {/** Frames and groups a click passes through: their own buttons and cards act. */const PASSIVE_NODE_TYPES = new Set(['goalBatchExperimentProbe',+ 'goalBatchRetro','goalBatchRound','goalBatchWaves','goalExperimentGroup',@@ -382,7 +384,6 @@ type BatchRole = { kind: 'assay' | 'template'; model: BatchModel; round: BatchRoconst useBatchCopy = () => {const { t } = useTranslation('chat');- const checkCopy = useGateCheckCopy();return useMemo(() => ({gate: (round: BatchRound, model: BatchModel): GraphNodeData['presentation'] => {@@ -405,22 +406,12 @@ const useBatchCopy = () => {) : (t('goalBatch.gate.checkCount', { count: model.gateChecks.length }));- const checks = (latest ? judged : model.gateChecks).map((check) => {- const { detail, label } = checkCopy(check);- const mark = 'passed' in check ? (check.passed ? '✓ ' : '✗ ') : '';- return `${mark}${label}${detail ? `(${detail})` : ''}`;- });return {chip: { ...chip, text: t(`goalBatch.gate.status.${key}` as any) },- // How many conditions decide the release, and which, one hover away.- hint: (- <Flexbox gap={4}>- <span>{t('goalBatch.gate.hintTitle')}</span>- {checks.map((text, index) => (- <span key={index}>{latest ? text : `${index + 1}. ${text}`}</span>- ))}- </Flexbox>- ),+ // Which conditions decide the release, and how each stands, one hover away —+ // to the side, so it never covers the retro the gate sits under.+ hint: <GateChecksHint checks={latest ? judged : model.gateChecks} />,+ hintPlacement: 'rightTop',icon: DoorOpen,palette: GATE_COLOR,// Passed / sent back / waiting sits after the title, right-aligned.@@ -450,7 +441,7 @@ const useBatchCopy = () => {title: t(batchPlanTitleKey(model, round), { revision: round.planVersion }),}),}),- [t, checkCopy],+ [t],);};@@ -818,65 +809,15 @@ 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 }]) => {- if (!layout || !visibleIds.has(batchId)) return [];- const [first] = model.rounds;- // The roster waves a round owns, keeping each one's roster position.- const rowsOf = (revision: number) =>- model.waves.flatMap((cells, wave) =>- model.waveRounds[wave] === revision ? [{ cells, wave }] : [],- );- return layout.groups.map((group) => {- const round = model.rounds[group.revision - 1];- const base = {- draggable: false,- id: group.id,- ...placeInMap(group.id, group.box, batchId),- selectable: false,- width: group.box.width,- };- // A round's frame sits behind its nodes and the links between them.- if (group.kind === 'round')- return {- ...base,- data: { revision: group.revision } satisfies BatchRoundFrameData,- style: { height: group.box.height, width: group.box.width },- type: 'goalBatchRound',- zIndex: -1,- } satisfies FlowNode;- const data =- group.kind === 'experimentProbe'- ? {- onEnter: () => onEnter(batchStageId(batchId, 0)),- onSelect,- probes: first.probes,- started: first.probes.some((probe) => probe.state !== 'backlog'),- views: graph.byId,- }- : ({- onEnter: () => onEnter(batchStageId(batchId, group.revision)),- onSelect,- probes: round.probes,- revision: group.revision,- rows: rowsOf(group.revision),- started:- group.revision === 1- ? !first.assayId || first.gate === 'passed' || first.gate === 'rejected'- : round.probes.some((probe) => probe.state !== 'backlog'),- waveSize: model.waveSize,- } satisfies BatchWavesData);- return {- ...base,- data,- // Width is the layout's; height hugs the content, the layout only reserves it.- style: { width: group.box.width },- type:- group.kind === 'experimentProbe' ? 'goalBatchExperimentProbe' : 'goalBatchWaves',- } satisfies FlowNode;- });+ () =>+ buildBatchFlowNodes({+ batches,+ byId: graph.byId,+ onEnter,+ onSelect,+ placeInMap,+ visibleIds,}),- ],[batches, visibleIds, graph.byId, onEnter, onSelect, placeInMap],);