Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(goal): STAMP — batch canary rollout for one repeated mould (#20704)

Arvin Xu46873d534469
diff --git a/apps/cli/src/commands/goal.test.ts b/apps/cli/src/commands/goal.test.ts
index e1701837882..93078a32f6b 100644
--- a/apps/cli/src/commands/goal.test.ts
+++ b/apps/cli/src/commands/goal.test.ts
@@ -380,6 +380,7 @@ describe('goal show command', () => {
node('task', 'Ask vendor A'),
node('finding', 'Vendor A quoted 1200'),
node('decision', 'Retry or retire?'),
+ node('batch', 'Migrate 50 stores'),
],
workVersions: [],
},
@@ -390,6 +391,7 @@ describe('goal show command', () => {
expect(output).toContain('▣ task');
expect(output).toContain('◇ problem');
expect(output).toContain('● finding');
+ expect(output).toContain('▦ batch');
expect(output).toContain('◆ decision');
expect(output).not.toContain('undefined');
});
diff --git a/apps/cli/src/commands/goal.ts b/apps/cli/src/commands/goal.ts
index 0f4537fbe54..8d4ffc98136 100644
--- a/apps/cli/src/commands/goal.ts
+++ b/apps/cli/src/commands/goal.ts
@@ -23,6 +23,7 @@ import { resolveAppUrlBuilder } from './task/url';
// `any` node kind, which is how a renamed kind silently printed `undefined`
// here after the type checker had signed off everywhere else.
const nodeIcon: Record<GoalNodeKind, string> = {
+ batch: '▦',
decision: '◆',
experiment: '⚗',
finding: '●',
@@ -590,6 +591,12 @@ export function registerGoalCommand(program: Command) {
'--max-concurrent-tasks <n>',
"How many of this goal's tasks may run at once (default 3)",
)
+ .option(
+ '--rollout <mode>',
+ 'Batch roll-out for one repeated mould: canary (probe first, then waves), full, or off to forbid a batch. Omit to let the planner decide',
+ )
+ .option('--canary-size <n>', 'Probe size K for --rollout canary (default 5, maximum 5)')
+ .option('--wave-size <n>', 'Units released per wave after the gate passes (default 5)')
.option('--max-steps-per-run <n>', 'Optional agent step cap per Task run (for example 500)')
.option(
@@ -608,6 +615,9 @@ export function registerGoalCommand(program: Command) {
if (options.maxExperiments && !options.explore) {
throw new Error('--max-experiments requires --explore');
}
+ if (options.rollout && !['canary', 'full', 'off'].includes(options.rollout)) {
+ throw new Error('--rollout must be one of: canary, full, off');
+ }
const operationId = process.env.LOBEHUB_OPERATION_ID;
const fromTopic = Boolean(options.topic || options.conversation);
if (fromTopic && !operationId) {
@@ -650,6 +660,17 @@ export function registerGoalCommand(program: Command) {
? { maxIncidents: Number.parseInt(options.maxSupervisionIncidents, 10) }
: {}),
},
+ // Auto-detection is the default: with no `--rollout`, the planner's
+ // homogeneity claim decides. `off` forbids a batch outright.
+ rollout: options.rollout
+ ? {
+ canarySize: options.canarySize
+ ? Number.parseInt(options.canarySize, 10)
+ : undefined,
+ trigger: options.rollout,
+ waveSize: options.waveSize ? Number.parseInt(options.waveSize, 10) : undefined,
+ }
+ : undefined,
taskAgentId: options.taskAgent,
},
criteria: (options.criterion as string[] | undefined)?.map((criterion) => ({
diff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.ts
index 3cd42fa384d..4cb94b1c0bb 100644
--- a/apps/server/src/routers/lambda/goal.ts
+++ b/apps/server/src/routers/lambda/goal.ts
@@ -1,4 +1,4 @@
-import { goalStatuses } from '@lobechat/const/goal';
+import { goalStatuses, ROLLOUT_MAX_CANARY_SIZE } from '@lobechat/const/goal';
import { MAX_GOAL_METRIC_CRITERIA, summarizeGoalSupervision } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
@@ -10,6 +10,7 @@ import { heteroAuthedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { GoalService } from '@/server/services/goal';
import { advanceGoal } from '@/server/services/goal/advanceGoal';
+import { graphForClient } from '@/server/services/goal/graphCompat';
import { GoalManagerService, goalPlanSchema } from '@/server/services/goal/manager';
import {
DEFAULT_MANAGER_MAX_TURNS,
@@ -106,6 +107,19 @@ const conversationGoalInput = z.object({
operationLeaseTimeoutMs: z.number().int().min(60_000).optional(),
})
.optional(),
+ /**
+ * Batch roll-out policy for a goal that is one repeated mould. Omit it and
+ * the planner's own homogeneity claim decides; `off` forbids a batch even
+ * when the planner claims one.
+ */
+ rollout: z
+ .object({
+ canarySize: z.number().int().min(2).max(ROLLOUT_MAX_CANARY_SIZE).optional(),
+ minHomogeneousUnits: z.number().int().min(1).max(200).optional(),
+ trigger: z.enum(['canary', 'full', 'off']),
+ waveSize: z.number().int().min(1).max(50).optional(),
+ })
+ .optional(),
schedule: z
.object({
/** ISO-8601 instant; past it the coordinator stops dispatching. */
@@ -933,13 +947,23 @@ export const goalRouter = router({
}
}),
- graph: goalProcedure.input(idInput).query(async ({ ctx, input }) => {
- try {
- return { data: await ctx.goalService.graph(input.id), success: true };
- } catch (error) {
- mapGoalError(error, 'graph');
- }
- }),
+ graph: goalProcedure
+ .input(
+ idInput.extend({
+ /** Graph features this client renders (see `GOAL_GRAPH_CAPABILITY`). */
+ capabilities: z.array(z.string()).max(20).optional(),
+ }),
+ )
+ .query(async ({ ctx, input }) => {
+ try {
+ return {
+ data: graphForClient(await ctx.goalService.graph(input.id), input.capabilities),
+ success: true,
+ };
+ } catch (error) {
+ mapGoalError(error, 'graph');
+ }
+ }),
/**
* Why `submitPlan` would accept or refuse a plan right now, without writing.
diff --git a/apps/server/src/services/goal/criteriaGenerator.test.ts b/apps/server/src/services/goal/criteriaGenerator.test.ts
index 007efd0e613..dc82402dc43 100644
--- a/apps/server/src/services/goal/criteriaGenerator.test.ts
+++ b/apps/server/src/services/goal/criteriaGenerator.test.ts
@@ -68,7 +68,7 @@ describe('GoalCriteriaGeneratorService', () => {
expect.objectContaining({ schema: expect.objectContaining({ name: 'goal_decomposition' }) }),
expect.objectContaining({
tracing: {
- promptVersion: 'v6',
+ promptVersion: 'v8',
scenario: 'goal_decompose',
schemaName: 'goal_decomposition',
},
diff --git a/apps/server/src/services/goal/criteriaGenerator.ts b/apps/server/src/services/goal/criteriaGenerator.ts
index 8981d4c2722..fea3e3d54d2 100644
--- a/apps/server/src/services/goal/criteriaGenerator.ts
+++ b/apps/server/src/services/goal/criteriaGenerator.ts
@@ -73,6 +73,26 @@ const decompositionSchema = z.object({
/** Readings the plan relies on that the goal did not state. */
assumptions: z.array(z.string()).default([]),
problemStatement: z.string().min(1),
+ /**
+ * The planner's batch claim. Present only when it judged the goal to be one
+ * repeated mould; the coordinator validates it with `spec.ts` before creating
+ * a `batch`, so a planner that over-claims still decomposes normally.
+ */
+ rollout: z
+ .object({
+ recipeOutline: z.string().optional(),
+ repeatable: z.boolean(),
+ /** Honest count of the homogeneous units in the whole goal. */
+ unitCount: z.number().int().positive(),
+ /** Roster of every homogeneous unit, probes first, in delivery order. */
+ units: z.array(z.string().min(1)).default([]),
+ /** Axes the units vary along; a probe must cover each declared value. */
+ variants: z
+ .array(z.object({ axis: z.string().min(1), values: z.array(z.string()) }))
+ .default([]),
+ })
+ .nullable()
+ .optional(),
/**
* What the planner could not determine and would change the deliverable.
* Defaulted so an older answer without the field still plans.
diff --git a/apps/server/src/services/goal/decideNextMove.test.ts b/apps/server/src/services/goal/decideNextMove.test.ts
index 68414b1f193..8df9a2d7983 100644
--- a/apps/server/src/services/goal/decideNextMove.test.ts
+++ b/apps/server/src/services/goal/decideNextMove.test.ts
@@ -623,3 +623,30 @@ describe('exploration terminal phase', () => {
);
});
});
+
+describe('batch rollout gate', () => {
+ const decideWithGate = (rolloutGate: Parameters<typeof decideNextMove>[0]['rolloutGate']) =>
+ decideNextMove({
+ concurrency: 3,
+ frontier: selectFrontier(graph()),
+ graph: graph(),
+ rolloutGate,
+ tasksById: new Map(),
+ });
+
+ it('releases the next wave when the gate passed', () => {
+ const move = decideWithGate({ blockers: [], met: true, provisional: false });
+ expect(move.branch).toBe('rollout_gate');
+ expect(move.outcome).toBe('advanced');
+ });
+
+ it('hands a blocked gate to a person instead of parking the goal', () => {
+ const move = decideWithGate({
+ blockers: ['1 probe(s) did not succeed'],
+ met: false,
+ provisional: false,
+ });
+ expect(move.branch).toBe('pattern_break');
+ expect(move.outcome).toBe('waiting_human');
+ });
+});
diff --git a/apps/server/src/services/goal/decideNextMove.ts b/apps/server/src/services/goal/decideNextMove.ts
index 25d2da64174..9b4010ed479 100644
--- a/apps/server/src/services/goal/decideNextMove.ts
+++ b/apps/server/src/services/goal/decideNextMove.ts
@@ -21,6 +21,7 @@ import type {
import { toMetricScale } from '@lobechat/types';
import { isGoalReportNode } from './report';
+import type { RolloutGateResult } from './rolloutGate';
export { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';
@@ -213,6 +214,12 @@ export interface GoalMoveInput {
* budget does.
*/
metricCriteria?: GoalMetricCriteriaState;
+ /**
+ * The repeated batch's gate verdict, present only once the wave it released
+ * has fully settled. Absent while a wave is running — the ordinary frontier
+ * owns that tick.
+ */
+ rolloutGate?: RolloutGateResult;
/**
* The responsible Task of every candidate that has one, keyed by task id.
* A candidate whose task id is absent from the map has lost its row.
@@ -262,6 +269,7 @@ export const decideNextMove = ({
frontier,
graph,
metricCriteria,
+ rolloutGate,
tasksById,
}: GoalMoveInput): GoalMove => {
const { candidates, chosen } = frontier;
@@ -298,6 +306,27 @@ export const decideNextMove = ({
};
}
+ // A repeated batch settles its own gate before the terminal phase: a passed
+ // gate releases the next wave, a blocked one hands the stall to a person
+ // rather than letting the goal look finished while units remain undelivered.
+ if (rolloutGate) {
+ if (rolloutGate.met) {
+ return {
+ ...base,
+ branch: 'rollout_gate',
+ message: 'Batch gate passed; release the next wave',
+ outcome: 'advanced',
+ };
+ }
+ return {
+ ...base,
+ branch: 'pattern_break',
+ focusNodeId: graph.goal.config?.rolloutState?.assayNodeId,
+ message: rolloutGate.blockers.join('; ') || 'Batch gate is blocked',
+ outcome: 'waiting_human',
+ };
+ }
+
// Walk the whole ranked frontier rather than stopping at its head. Four bug
// fixes that share no code have no reason to run one after another, and the
// old single-node frontier made them: the running node stayed eligible, was
diff --git a/apps/server/src/services/goal/goalBriefs.ts b/apps/server/src/services/goal/goalBriefs.ts
index 9ad499c7dc9..25ea4b830b4 100644
--- a/apps/server/src/services/goal/goalBriefs.ts
+++ b/apps/server/src/services/goal/goalBriefs.ts
@@ -1,6 +1,6 @@
import { GOAL_BRIEF_TRIGGER, GOAL_CLARIFICATION_OPTION } from '@lobechat/const/goal';
import type { BriefAction, BriefGoalMetadata, GoalDecisionOption, GoalItem } from '@lobechat/types';
-import { coordinatorGateReason, coordinatorReasonCopy } from '@lobechat/utils/goalCopy';
+import { coordinatorGateReason, coordinatorReasonCopies } from '@lobechat/utils/goalCopy';
import { and, eq, isNull, sql } from 'drizzle-orm';
import { BriefModel } from '@/database/models/brief';
@@ -79,8 +79,12 @@ export class GoalBriefService {
const { t } = await this.chatCopy();
const { t: tHome } = await this.homeCopy();
const reason = coordinatorGateReason(input.question) ?? input.question;
- const reasonCopy = coordinatorReasonCopy(reason);
- const localizedReason = reasonCopy ? t(reasonCopy.key, reasonCopy.params) : reason;
+ // A batch gate lists every blocker it hit at once, joined by `; `; localize
+ // each so the brief carries no English into a non-English inbox.
+ const reasonCopies = coordinatorReasonCopies(reason);
+ const localizedReason = reasonCopies
+ ? reasonCopies.map((copy) => t(copy.key, copy.params)).join('; ')
+ : reason;
// The machine gate's retry means "I fixed the setup", not "try again".
const machine = MACHINE_GATE_TAIL.test(input.question);
const label = (option: GoalDecisionOption) => {
diff --git a/apps/server/src/services/goal/graphCompat.test.ts b/apps/server/src/services/goal/graphCompat.test.ts
new file mode 100644
index 00000000000..6fd7865390f
--- /dev/null
+++ b/apps/server/src/services/goal/graphCompat.test.ts
@@ -0,0 +1,28 @@
+import type { GoalGraphSnapshot } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { graphForClient } from './graphCompat';
+
+const graph = {
+ nodes: [
+ { id: 'p', kind: 'problem' },
+ { id: 'b', kind: 'batch' },
+ { id: 't', kind: 'task' },
+ ],
+} as unknown as GoalGraphSnapshot;
+
+describe('graphForClient', () => {
+ it('sends a batch as an experiment container to a client that does not declare batches', () => {
+ // A cached web bundle or an installed desktop app predates the kind.
+ expect(graphForClient(graph).nodes.map((node) => node.kind)).toEqual([
+ 'problem',
+ 'experiment',
+ 'task',
+ ]);
+ expect(graphForClient(graph, ['other']).nodes[1].kind).toBe('experiment');
+ });
+
+ it('keeps the real kind for a client that renders batches', () => {
+ expect(graphForClient(graph, ['batch'])).toBe(graph);
+ });
+});
diff --git a/apps/server/src/services/goal/graphCompat.ts b/apps/server/src/services/goal/graphCompat.ts
new file mode 100644
index 00000000000..e7b256cbd6c
--- /dev/null
+++ b/apps/server/src/services/goal/graphCompat.ts
@@ -0,0 +1,25 @@
+import { GOAL_GRAPH_CAPABILITY } from '@lobechat/const/goal';
+import type { GoalGraphSnapshot } from '@lobechat/types';
+
+/**
+ * The graph as a client that declared `capabilities` can render it.
+ *
+ * A client released before the `batch` node kind has no style, icon or size
+ * for it, and would crash or lay out garbage on a batched goal. Unless the
+ * client declares the capability, a batch goes out as an `experiment` — the
+ * container those clients already draw, holding the same members — and only a
+ * client that knows batches sees the real kind.
+ */
+export const graphForClient = (
+ graph: GoalGraphSnapshot,
+ capabilities: readonly string[] = [],
+): GoalGraphSnapshot => {
+ if (capabilities.includes(GOAL_GRAPH_CAPABILITY.batch)) return graph;
+ if (!graph.nodes.some((node) => node.kind === 'batch')) return graph;
+ return {
+ ...graph,
+ nodes: graph.nodes.map((node) =>
+ node.kind === 'batch' ? { ...node, kind: 'experiment' as const } : node,
+ ),
+ };
+};
diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.ts
index 1631a312524..c1804ac257d 100644
--- a/apps/server/src/services/goal/index.test.ts
+++ b/apps/server/src/services/goal/index.test.ts
@@ -1,6 +1,7 @@
// @vitest-environment node
import {
DEVICE_OFFLINE_RUN_STATUS,
+ GOAL_BATCH_ASSAY_TITLE,
GOAL_COORDINATOR_ACTOR_ID,
GOAL_MACHINE_GATE_TITLE,
QUOTA_LIMITED_RUN_STATUS,
@@ -23,6 +24,7 @@ import {
acceptances,
agentOperations,
agents,
+ briefs,
documents,
goalEdges,
goalEvents,
@@ -57,6 +59,7 @@ import { MAX_QUOTA_RETRIES } from './machineRecovery';
import { DEVICE_OFFLINE_GATE_REASON, VERIFY_SETTLE_GRACE_MS } from './recoveryPolicy';
import * as scheduler from './scheduler';
import { LocalGoalScheduler } from './scheduler/impls';
+import { uncoveredAxisValues } from './spec';
import { TaskRecoveryCoordinator } from './taskRecoveryCoordinator';
import type { GoalTickObservation } from './traceObservation';
@@ -1969,6 +1972,1085 @@ describe('GoalService', () => {
expect(after.edges.filter((e) => e.kind === 'depends_on')).toHaveLength(1);
});
+ it('collapses a repeated mould into one batch, materializing only the probes', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ problemStatement: '把 50 个同构的 store 迁移到 replica',
+ rollout: {
+ recipeOutline: '把 store 换成 replica 支撑的实现',
+ repeatable: true,
+ unitCount: 50,
+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
+ variants: [],
+ },
+ tasks: Array.from({ length: 5 }, (_, i) => ({
+ dependsOn: [],
+ instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
+ title: `Unit ${i + 1}`,
+ })),
+ });
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ title: 'Migrate stores' });
+
+ expect((await service.tick(graph.goal.id)).outcome).toBe('advanced');
+
+ const after = await service.graph(graph.goal.id);
+ // ① Only the K probes exist as Tasks — the whole 50-unit fan-out never lands.
+ expect(after.nodes.filter((n) => n.kind === 'task')).toHaveLength(5);
+ expect(after.nodes.filter((n) => n.kind === 'batch')).toHaveLength(1);
+ expect(after.nodes.filter((n) => n.kind === 'finding')).toHaveLength(1);
+ expect(after.nodes.filter((n) => n.kind === 'decision')).toHaveLength(1);
+
+ const state = after.goal.config?.rolloutState;
+ expect(state?.phase).toBe('probe');
+ expect(state?.probeNodeIds).toHaveLength(5);
+ expect(state?.unitTitles).toHaveLength(50);
+ expect(after.goal.config?.rollout?.trigger).toBe('canary');
+
+ // The probes are contained by the batch; the gate waits on each of them.
+ const batch = after.nodes.find((n) => n.kind === 'batch')!;
+ const containedIds = new Set(
+ after.edges
+ .filter((e) => e.kind === 'contains' && e.sourceNodeId === batch.id)
+ .map((e) => e.targetNodeId),
+ );
+ // Five probes inside the batch — never the whole 50-unit roster.
+ expect(after.nodes.filter((n) => containedIds.has(n.id) && n.kind === 'task')).toHaveLength(5);
+ // Plus the one Template and the one Assay that make the batch a batch.
+ expect(after.nodes.filter((n) => containedIds.has(n.id) && n.kind === 'finding')).toHaveLength(
+ 1,
+ );
+ expect(after.nodes.filter((n) => containedIds.has(n.id) && n.kind === 'decision')).toHaveLength(
+ 1,
+ );
+ });
+
+ it('does not grow a batch for a goal that is not one repeated mould', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ problemStatement: '分两步上线一个新功能',
+ rollout: {
+ recipeOutline: '',
+ repeatable: false,
+ unitCount: 3,
+ units: [],
+ variants: [],
+ },
+ tasks: [
+ { dependsOn: [], instruction: '第一步:加 schema', title: '第一步' },
+ { dependsOn: [0], instruction: '第二步:接 UI', title: '第二步' },
+ ],
+ });
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ title: 'Ship a feature' });
+
+ expect((await service.tick(graph.goal.id)).outcome).toBe('advanced');
+
+ const after = await service.graph(graph.goal.id);
+ expect(after.nodes.filter((n) => n.kind === 'batch')).toHaveLength(0);
+ expect(after.goal.config?.rolloutState).toBeUndefined();
+ // The ordinary decomposition is untouched: both steps are plain tasks.
+ expect(after.nodes.filter((n) => n.kind === 'task')).toHaveLength(2);
+ });
+
+ it('keeps every roster unit when a rollout claim cannot become a batch', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ problemStatement: '把 12 个同构的 store 迁移到 replica',
+ rollout: {
+ recipeOutline: '把 store 换成 replica 支撑的实现',
+ repeatable: true,
+ unitCount: 12,
+ units: Array.from({ length: 12 }, (_, i) => `Unit ${i + 1}`),
+ variants: [],
+ },
+ tasks: Array.from({ length: 3 }, (_, i) => ({
+ dependsOn: [],
+ instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
+ title: `Unit ${i + 1}`,
+ })),
+ });
+ const service = new GoalService(serverDB, userId);
+ // The caller forbade a batch, so the planner's claim must NOT drop the
+ // units its probe-only `tasks` left out.
+ const graph = await service.create({
+ config: { rollout: { trigger: 'off' } },
+ title: 'Migrate stores, no batch',
+ });
+ await service.tick(graph.goal.id);
+
+ const after = await service.graph(graph.goal.id);
+ expect(after.nodes.filter((n) => n.kind === 'batch')).toHaveLength(0);
+ // All 12 units are planned, not only the 3 the planner listed as probes.
+ expect(after.nodes.filter((n) => n.kind === 'task')).toHaveLength(12);
+ });
+
+ it('materializes a fallback roster above the batch cap without trimming it', async () => {
+ const units = Array.from({ length: 64 }, (_, i) => `Unit ${i + 1}`);
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ problemStatement: '把 64 个同构的 store 迁移到 replica',
+ rollout: {
+ recipeOutline: '把 store 换成 replica 支撑的实现',
+ repeatable: true,
+ unitCount: 64,
+ units,
+ variants: [],
+ },
+ tasks: Array.from({ length: 3 }, (_, i) => ({
+ dependsOn: [],
+ instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
+ title: `Unit ${i + 1}`,
+ })),
+ });
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({
+ config: { rollout: { trigger: 'off' } },
+ title: 'Migrate stores, no batch',
+ });
+ await service.tick(graph.goal.id);
+
+ const after = await service.graph(graph.goal.id);
+ expect(after.nodes.filter((n) => n.kind === 'batch')).toHaveLength(0);
+ // Every one of the 64 units is planned: the batch config's 60-unit roster
+ // cap must never trim the ordinary decomposition.
+ expect(after.nodes.filter((n) => n.kind === 'task')).toHaveLength(64);
+ });
+
+ it('refuses to batch a roster above the cap instead of silently trimming it', async () => {
+ const units = Array.from({ length: 64 }, (_, i) => `Unit ${i + 1}`);
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ problemStatement: '把 64 个同构的 store 迁移到 replica',
+ rollout: {
+ recipeOutline: '把 store 换成 replica 支撑的实现',
+ repeatable: true,
+ unitCount: 64,
+ units,
+ variants: [],
+ },
+ tasks: Array.from({ length: 3 }, (_, i) => ({
+ dependsOn: [],
+ instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
+ title: `Unit ${i + 1}`,
+ })),
+ });
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ title: 'Migrate stores' });
+ await service.tick(graph.goal.id);
+
+ const after = await service.graph(graph.goal.id);
+ // A roster the batch cannot carry whole is refused, not truncated: the goal
+ // still delivers all 64 units, as plain tasks.
+ expect(after.nodes.filter((n) => n.kind === 'batch')).toHaveLength(0);
+ expect(after.goal.config?.rolloutState).toBeUndefined();
+ expect(after.nodes.filter((n) => n.kind === 'task')).toHaveLength(64);
+ });
+
+ it('numbers a release after the waves a batch released before the counter existed', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ problemStatement: '把 50 个同构的 store 迁移到 replica',
+ rollout: {
+ recipeOutline: '把 store 换成 replica 支撑的实现',
+ repeatable: true,
+ unitCount: 50,
+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
+ variants: [],
+ },
+ tasks: Array.from({ length: 5 }, (_, i) => ({
+ dependsOn: [],
+ instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
+ title: `Unit ${i + 1}`,
+ })),
+ });
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ title: 'Migrate stores' });
+ await service.tick(graph.goal.id);
+ const graphModel = new GoalGraphModel(serverDB, userId);
+ const goalModel = new GoalModel(serverDB, userId);
+ const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;
+ for (const id of state.probeNodeIds)
+ await graphModel.updateNodeStatus(graph.goal.id, id, 'resolved');
+ // A rollout from before this change: two waves out, no counter, no log.
+ await goalModel.updateRolloutState(graph.goal.id, {
+ ...state,
+ gateLog: undefined,
+ phase: 'mass',
+ waveIndex: 2,
+ wavesReleased: undefined,
+ });
+
+ await service.tick(graph.goal.id);
+ const next = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;
+ expect(next.gateLog?.at(-1)).toMatchObject({ outcome: 'released', wave: 3 });
+ expect(next.wavesReleased).toBe(3);
+ });
+
+ it('numbers a release after the waves a batch released before the counter existed, across a restart', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ problemStatement: '把 50 个同构的 store 迁移到 replica',
+ rollout: {
+ recipeOutline: '把 store 换成 replica 支撑的实现',
+ repeatable: true,
+ unitCount: 50,
+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
+ variants: [],
+ },
+ tasks: Array.from({ length: 5 }, (_, i) => ({
+ dependsOn: [],
+ instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
+ title: `Unit ${i + 1}`,
+ })),
+ });
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ title: 'Migrate stores' });
+ await service.tick(graph.goal.id);
+ const graphModel = new GoalGraphModel(serverDB, userId);
+ const goalModel = new GoalModel(serverDB, userId);
+ const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;
+ for (const id of state.probeNodeIds)
+ await graphModel.updateNodeStatus(graph.goal.id, id, 'resolved');
+ // A rollout from before this change, restarted once: `waveIndex` reset to 0,
+ // no counter, no log — but 20 roster units beyond the first canary are out.
+ await goalModel.updateRolloutState(graph.goal.id, {
+ ...state,
+ gateLog: undefined,
+ phase: 'mass',
+ releasedCount: state.releasedCount! + 20,
+ waveIndex: 0,
+ wavesReleased: undefined,
+ });
+
+ await service.tick(graph.goal.id);
+ const next = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;
+ // 20 units at the default wave size of 5 are four waves; this one is the fifth.
+ expect(next.gateLog?.at(-1)).toMatchObject({ outcome: 'released', wave: 5 });
+ expect(next.wavesReleased).toBe(5);
+ });
+
+ it('records each gate verdict — the release and the hold — with what it checked', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ problemStatement: '把 50 个同构的 store 迁移到 replica',
+ rollout: {
+ recipeOutline: '把 store 换成 replica 支撑的实现',
+ repeatable: true,
+ unitCount: 50,
+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
+ variants: [],
+ },
+ tasks: Array.from({ length: 5 }, (_, i) => ({
+ dependsOn: [],
+ instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
+ title: `Unit ${i + 1}`,
+ })),
+ });
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ title: 'Migrate stores' });
+ await service.tick(graph.goal.id);
+ const graphModel = new GoalGraphModel(serverDB, userId);
+ const probeIds = (await service.graph(graph.goal.id)).goal.config!.rolloutState!.probeNodeIds;
+ for (const id of probeIds) await graphModel.updateNodeStatus(graph.goal.id, id, 'resolved');
+
+ // The probes settled clean: the gate releases the first wave and says why.
+ await service.tick(graph.goal.id);
+ let state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;
+ expect(state.gateLog).toHaveLength(1);
+ expect(state.gateLog![0]).toMatchObject({
+ outcome: 'released',
+ releasedCount: 5,
+ revision: 1,
+ trigger: 'gate',
+ wave: 1,
+ waveIndex: 1,
+ });
+ expect(state.wavesReleased).toBe(1);
+ expect(state.gateLog![0].checks).toContainEqual(
+ expect.objectContaining({ count: 5, key: 'units_succeeded', passed: true, total: 5 }),
+ );
+
+ // One unit of that wave was rejected: the next verdict holds and names it.
+ const [rejected, ...rest] = state.massNodeIds!;
+ for (const id of rest) await graphModel.updateNodeStatus(graph.goal.id, id, 'resolved');
+ await graphModel.updateNodeStatus(graph.goal.id, rejected, 'rejected');
+ await service.tick(graph.goal.id);
+ state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;
+ expect(state.phase).toBe('pattern_break');
+ expect(state.gateLog![1]).toMatchObject({ outcome: 'blocked', trigger: 'gate' });
+ expect(state.gateLog![1].checks).toContainEqual(
+ expect.objectContaining({ key: 'units_succeeded', nodeIds: [rejected], passed: false }),
+ );
+ });
+
+ it('restarts the canary loop when a person answers a broken batch gate', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ problemStatement: '把 50 个同构的 store 迁移到 replica',
+ rollout: {
+ recipeOutline: '把 store 换成 replica 支撑的实现',
+ repeatable: true,
+ unitCount: 50,
+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
+ variants: [],
+ },
+ tasks: Array.from({ length: 5 }, (_, i) => ({
+ dependsOn: [],
+ instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
+ title: `Unit ${i + 1}`,
+ })),
+ });
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ title: 'Migrate stores' });
+ await service.tick(graph.goal.id);
+
+ const graphModel = new GoalGraphModel(serverDB, userId);
+ const goalModel = new GoalModel(serverDB, userId);
+ const before = await service.graph(graph.goal.id);
+ const state = before.goal.config!.rolloutState!;
+ const assayId = state.assayNodeId!;
+
+ // Simulate the break the coordinator opens when a gate blocks.
+ const decision = await graphModel.createDecision(graph.goal.id, assayId, {
+ authority: 'user',
+ options: [
+ { description: '修订配方', id: 'revise', label: '修订配方并重探' },
+ { description: '新类型', id: 'new_class', label: '作为新类型并排处理' },
+ ],
+ question: 'Batch gate blocked',
+ requestedUserId: userId,
+ });
+ await graphModel.updateNodeStatus(graph.goal.id, assayId, 'waiting');
+ await goalModel.updateRolloutState(graph.goal.id, { ...state, phase: 'pattern_break' });
+ await serverDB.update(goals).set({ status: 'paused' }).where(eq(goals.id, graph.goal.id));
+
+ // R5: the answer itself restarts the loop — no manual rerun.
+ await service.decide(graph.goal.id, decision!.id, 'revise', '补上 SSR 播种这一步');
+
+ const after = await service.graph(graph.goal.id);
+ const next = after.goal.config!.rolloutState!;
+ expect(next.phase).toBe('probe');
+ expect(next.waveIndex).toBe(0);
+ expect(next.templateRevision).toBe(state.templateRevision + 1);
+ expect(
+ after.edges.some((e) => e.kind === 'revises' && e.sourceNodeId === next.templateNodeId),
+ ).toBe(true);
+ // A fresh gate and a fresh probe batch: the class is proved again.
+ expect(next.assayNodeId).not.toBe(assayId);
+ expect(next.probeNodeIds.length).toBeGreaterThan(0);
+
+ // The correction is folded into the batch's recipe and briefs the re-opened
+ // probes — later waves only read `policy.spec.recipeOutline`, so a note kept
+ // only on the Template would never reach the tasks meant to test it.
+ expect(after.goal.config!.rollout!.spec?.recipeOutline).toContain('补上 SSR 播种这一步');
+ const openedProbe = after.nodes.find((n) => next.probeNodeIds.includes(n.id))!;
+ expect(openedProbe.description).toContain('补上 SSR 播种这一步');
+ });
+
+ it('materializes and answers a pattern-break gate on a full rollout', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ problemStatement: '把 50 个同构的 store 迁移到 replica',
+ rollout: {
+ recipeOutline: '把 store 换成 replica 支撑的实现',
+ repeatable: true,
+ unitCount: 50,
+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
+ variants: [],
+ },
+ tasks: Array.from({ length: 5 }, (_, i) => ({
+ dependsOn: [],
+ instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
+ title: `Unit ${i + 1}`,
+ })),
+ });
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({
+ config: { rollout: { trigger: 'full' } },
+ title: 'Migrate stores',
+ });
+ await service.tick(graph.goal.id);
+
+ const before = await service.graph(graph.goal.id);
+ const state = before.goal.config!.rolloutState!;
+ // A `full` rollout creates no Assay — it skips the probe gate.
+ expect(state.assayNodeId).toBeUndefined();
+
+ // A break still has to be answerable: the coordinator must open the question
+ // on a `decision` node even though this trigger made none.
+ const openGate = (
+ service as unknown as {
+ openPatternBreakGate: (g: unknown, message: string, effects: unknown[]) => Promise<unknown>;
+ }
+ ).openPatternBreakGate.bind(service);
+ await openGate(before, 'Unit 1 did not pass', []);
+
+ const after = await service.graph(graph.goal.id);
+ const next = after.goal.config!.rolloutState!;
+ expect(next.phase).toBe('pattern_break');
+ const gateNode = after.nodes.find((n) => n.id === next.assayNodeId);
+ expect(gateNode?.kind).toBe('decision');
+ const decision = after.decisions.find(
+ (item) => item.nodeId === next.assayNodeId && item.status === 'pending',
+ );
+ expect(decision).toBeDefined();
+ // The options carry ids only; labels and consequences are localized on the
+ // client by id, so nothing English is persisted into the gate payload.
+ expect(decision!.options?.map((option) => option.id)).toEqual(['revise', 'new_class']);
+ expect(decision!.options?.every((option) => option.description === undefined)).toBe(true);
+
+ // Answering it restarts the class, rather than leaving the goal parked.
+ await service.decide(graph.goal.id, decision!.id, 'revise', '补上冷启动这一步');
+ const restarted = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;
+ expect(restarted.phase).toBe('probe');
+ expect(restarted.templateRevision).toBe(next.templateRevision + 1);
+ // The break must not redispatch the whole 50-unit rollout at once: only a
+ // canary re-probes, and the rest stay owed on the re-cut roster for waves.
+ expect(restarted.probeNodeIds).toHaveLength(5);
+ expect(restarted.releasedCount).toBe(5);
+ expect(restarted.unitTitles).toHaveLength(50);
+ });
+
+ it('opens one gate when two advances see a full rollout break together', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ problemStatement: '把 50 个同构的 store 迁移到 replica',
+ rollout: {
+ recipeOutline: '把 store 换成 replica 支撑的实现',
+ repeatable: true,
+ unitCount: 50,
+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
+ variants: [],
+ },
+ tasks: Array.from({ length: 5 }, (_, i) => ({
+ dependsOn: [],
+ instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
+ title: `Unit ${i + 1}`,
+ })),
+ });
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({
+ config: { rollout: { trigger: 'full' } },
+ title: 'Migrate stores',
+ });
+ await service.tick(graph.goal.id);
+ const before = await service.graph(graph.goal.id);
+ const openGate = (
+ service as unknown as {
+ openPatternBreakGate: (g: unknown, message: string, effects: unknown[]) => Promise<unknown>;
+ }
+ ).openPatternBreakGate.bind(service);
+
+ // Both read the same snapshot with no Assay yet.
+ await Promise.all([
+ openGate(before, 'Unit 1 did not pass', []),
+ openGate(before, 'Unit 2 did not pass', []),
+ ]);
+
+ // One Assay, one pending question, and it is the one the state records.
+ const after = await service.graph(graph.goal.id);
+ const next = after.goal.config!.rolloutState!;
+ const assays = after.nodes.filter(
+ (n) => n.kind === 'decision' && n.title === GOAL_BATCH_ASSAY_TITLE,
+ );
+ expect(assays).toHaveLength(1);
+ const pending = after.decisions.filter((item) => item.status === 'pending');
+ expect(pending.map((item) => item.nodeId)).toEqual([next.assayNodeId]);
+ });
+
+ it('judges the final wave like any other before closing the batch', async () => {
+ const rollout = {
+ recipeOutline: '把 store 换成 replica 支撑的实现',
+ repeatable: true,
+ unitCount: 7,
+ units: Array.from({ length: 7 }, (_, i) => `Unit ${i + 1}`),
+ variants: [],
+ };
+ const tasks = Array.from({ length: 5 }, (_, i) => ({
+ dependsOn: [],
+ instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
+ title: `Unit ${i + 1}`,
+ }));
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ problemStatement: '把 7 个同构的 store 迁移到 replica',
+ rollout,
+ tasks,
+ });
+ const graphModel = new GoalGraphModel(serverDB, userId);
+ const service = new GoalService(serverDB, userId);
+
+ const releaseFinalWave = async (title: string) => {
+ const graph = await service.create({
+ config: {
+ rollout: { canarySize: 5, minHomogeneousUnits: 5, trigger: 'canary', waveSize: 7 },
+ },
+ title,
+ });
+ await service.tick(graph.goal.id);
+ const probeIds = (await service.graph(graph.goal.id)).goal.config!.rolloutState!.probeNodeIds;
+ for (const id of probeIds) await graphModel.updateNodeStatus(graph.goal.id, id, 'resolved');
+ await service.tick(graph.goal.id);
+ const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;
+ // The last two units went out, and the batch is not closed on release.
+ expect(state.massNodeIds).toHaveLength(2);
+ expect(state.phase).toBe('mass');
+ return { goalId: graph.goal.id, finalWave: state.massNodeIds! };
+ };
+
+ // A unit retired from the final wave stops the batch, as in any earlier wave.
+ const held = await releaseFinalWave('Final wave with a retired unit');
+ await service.retireNodes(held.goalId, [held.finalWave[0]], 'not needed');
+ await graphModel.updateNodeStatus(held.goalId, held.finalWave[1], 'resolved');
+ await service.tick(held.goalId);
+ expect((await service.graph(held.goalId)).goal.config!.rolloutState!.phase).toBe(
+ 'pattern_break',
+ );
+
+ // A clean final wave closes it.
+ const clean = await releaseFinalWave('Final wave delivered');
+ for (const id of clean.finalWave)
+ await graphModel.updateNodeStatus(clean.goalId, id, 'resolved');
+ await service.tick(clean.goalId);
+ expect((await service.graph(clean.goalId)).goal.config!.rolloutState!.phase).toBe('done');
+ });
+
+ describe('answering a batch break', () => {
+ const decompose = (variants: { axis: string; values: string[] }[] = []) =>
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ problemStatement: '把 7 个同构的 store 迁移到 replica',
+ rollout: {
+ recipeOutline: '把 store 换成 replica 支撑的实现',
+ repeatable: true,
+ unitCount: 7,
+ units: Array.from({ length: 7 }, (_, i) => `Unit ${i + 1}`),
+ variants,
+ },
+ tasks: Array.from({ length: 5 }, (_, i) => ({
+ dependsOn: [],
+ instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
+ title: `Unit ${i + 1}`,
+ })),
+ });
+ const pendingBreak = async (service: GoalService, goalId: string) =>
+ (await service.graph(goalId)).decisions.find(
+ (item) =>
+ item.status === 'pending' && item.options?.some((option) => option.id === 'revise'),
+ )!;
+
+ it('re-probes delivered units when the roster is exhausted and the gate held anyway', async () => {
+ // An axis value no unit's brief mentions keeps the gate shut even with
+ // every unit delivered.
+ decompose([{ axis: 'render', values: ['ssr'] }]);
+ const service = new GoalService(serverDB, userId);
+ const graphModel = new GoalGraphModel(serverDB, userId);
+ const graph = await service.create({
+ config: { rollout: { minHomogeneousUnits: 5, trigger: 'full' } },
+ title: 'Full rollout, axis untested',
+ });
+ await service.tick(graph.goal.id);
+ const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;
+ for (const id of [...state.probeNodeIds, ...(state.massNodeIds ?? [])])
+ await graphModel.updateNodeStatus(graph.goal.id, id, 'resolved');
+ await service.tick(graph.goal.id);
+ expect((await service.graph(graph.goal.id)).goal.config!.rolloutState!.phase).toBe(
+ 'pattern_break',
+ );
+
+ const decision = await pendingBreak(service, graph.goal.id);
+ await service.decide(graph.goal.id, decision.id, 'revise', '每个单元都按 ssr 路径验证');
+
+ // The new canary is not empty: delivered units are re-probed under v2.
+ const next = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;
+ expect(next.phase).toBe('probe');
+ expect(next.probeNodeIds.length).toBeGreaterThan(0);
+ });
+
+ it('leaves the question open when the restart fails part-way, and restarts on a retry', async () => {
+ decompose();
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({
+ config: { rollout: { minHomogeneousUnits: 5, trigger: 'canary' } },
+ title: 'Restart is atomic',
+ });
+ await service.tick(graph.goal.id);
+ const openGate = (
+ service as unknown as {
+ openPatternBreakGate: (
+ g: unknown,
+ message: string,
+ effects: unknown[],
+ ) => Promise<unknown>;
+ }
+ ).openPatternBreakGate.bind(service);
+ await openGate(await service.graph(graph.goal.id), 'Unit 1 did not pass', []);
+ const before = await service.graph(graph.goal.id);
+ const decision = await pendingBreak(service, graph.goal.id);
+
+ // The restart dies after writing its new plan, while creating the next gate.
+ await serverDB.execute(sql`
+ CREATE OR REPLACE FUNCTION fail_next_assay() RETURNS trigger AS $$
+ BEGIN
+ IF NEW.kind = 'decision' THEN RAISE EXCEPTION 'worker stopped'; END IF;
+ RETURN NEW;
+ END $$ LANGUAGE plpgsql
+ `);
+ await serverDB.execute(sql`
+ CREATE TRIGGER fail_next_assay BEFORE INSERT ON goal_nodes
+ FOR EACH ROW EXECUTE FUNCTION fail_next_assay()
+ `);
+ try {
+ await expect(
+ service.decide(graph.goal.id, decision.id, 'revise', '补上冷启动这一步'),
+ ).rejects.toThrow();
+ } finally {
+ await serverDB.execute(sql`DROP TRIGGER IF EXISTS fail_next_assay ON goal_nodes`);
+ await serverDB.execute(sql`DROP FUNCTION IF EXISTS fail_next_assay()`);
+ }
+
+ // Nothing of the half round survived, and the question is still open.
+ const failed = await service.graph(graph.goal.id);
+ expect(failed.nodes).toHaveLength(before.nodes.length);
+ expect(failed.goal.config!.rolloutState!.phase).toBe('pattern_break');
+ expect((await pendingBreak(service, graph.goal.id)).id).toBe(decision.id);
+
+ // Answering again opens the next round.
+ await service.decide(graph.goal.id, decision.id, 'revise', '补上冷启动这一步');
+ const next = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;
+ expect(next.phase).toBe('probe');
+ expect(next.templateRevision).toBe(2);
+ });
+
+ it('leaves a brief for the batch gate so Home keeps it after a dismissal', async () => {
+ decompose();
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({
+ config: { rollout: { minHomogeneousUnits: 5, trigger: 'canary' } },
+ title: 'Batch gate brief',
+ });
+ await service.tick(graph.goal.id);
+ const openGate = (
+ service as unknown as {
+ openPatternBreakGate: (
+ g: unknown,
+ message: string,
+ effects: unknown[],
+ ) => Promise<unknown>;
+ }
+ ).openPatternBreakGate.bind(service);
+ await openGate(await service.graph(graph.goal.id), 'Unit 1 did not pass', []);
+ const decision = await pendingBreak(service, graph.goal.id);
+
+ const rows = await serverDB.select().from(briefs).where(eq(briefs.userId, userId));
+ const brief = rows.find(
+ (row) =>
+ (row.metadata as { goal?: { decisionId?: string } } | null)?.goal?.decisionId ===
+ decision.id,
+ );
+ expect(brief).toMatchObject({ type: 'decision' });
+ // Revising needs a correction, so the brief sends the person to the goal
+ // page rather than offering one-click answers.
+ expect((brief!.actions as { key: string }[]).map((action) => action.key)).toEqual([
+ 'openGoal',
+ ]);
+ });
+
+ it('does not re-park a goal whose gate was answered while its brief was written', async () => {
+ decompose();
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({
+ config: { rollout: { minHomogeneousUnits: 5, trigger: 'canary' } },
+ title: 'Answered during the brief',
+ });
+ await service.tick(graph.goal.id);
+ const internals = service as unknown as {
+ briefs: { openDecision: (...args: unknown[]) => Promise<void> };
+ openPatternBreakGate: (g: unknown, message: string, effects: unknown[]) => Promise<unknown>;
+ };
+ // The person answers the moment the gate is visible, before the brief lands.
+ internals.briefs.openDecision = async () => {
+ const decision = await pendingBreak(service, graph.goal.id);
+ await service.decide(graph.goal.id, decision.id, 'revise', '补上冷启动这一步');
+ };
+
+ await internals.openPatternBreakGate.bind(service)(
+ await service.graph(graph.goal.id),
+ 'Unit 1 did not pass',
+ [],
+ );
+
+ // The answer resumed the goal on a new round; the opener must not undo it.
+ const after = await service.graph(graph.goal.id);
+ expect(after.goal.config!.rolloutState!.phase).toBe('probe');
+ expect(after.goal.status).toBe('running');
+ expect(after.goal.config?.pausedBy).toBeUndefined();
+ });
+
+ it('refuses to revise the recipe without a correction', async () => {
+ decompose();
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({
+ config: { rollout: { minHomogeneousUnits: 5, trigger: 'canary' } },
+ title: 'Revise needs a correction',
+ });
+ await service.tick(graph.goal.id);
+ const openGate = (
+ service as unknown as {
+ openPatternBreakGate: (
+ g: unknown,
+ message: string,
+ effects: unknown[],
+ ) => Promise<unknown>;
+ }
+ ).openPatternBreakGate.bind(service);
+ await openGate(await service.graph(graph.goal.id), 'Unit 1 did not pass', []);
+ const decision = await pendingBreak(service, graph.goal.id);
+
+ await expect(service.decide(graph.goal.id, decision.id, 'revise', ' ')).rejects.toThrow(
+ 'Revising the recipe needs a correction',
+ );
+ // The question stays open for an answer that says what to change.
+ expect((await pendingBreak(service, graph.goal.id)).id).toBe(decision.id);
+ });
+
+ it('forks a new class from the original outline, not the revised plan', async () => {
+ decompose();
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({
+ config: { rollout: { minHomogeneousUnits: 5, trigger: 'canary' } },
+ title: 'Fork after a revision',
+ });
+ await service.tick(graph.goal.id);
+ const openGate = (
+ service as unknown as {
+ openPatternBreakGate: (
+ g: unknown,
+ message: string,
+ effects: unknown[],
+ ) => Promise<unknown>;
+ }
+ ).openPatternBreakGate.bind(service);
+
+ await openGate(await service.graph(graph.goal.id), 'Unit 1 did not pass', []);
+ let decision = await pendingBreak(service, graph.goal.id);
+ await service.decide(graph.goal.id, decision.id, 'revise', '补上冷启动这一步');
+ await openGate(await service.graph(graph.goal.id), 'Unit 1 did not pass', []);
+ decision = await pendingBreak(service, graph.goal.id);
+ await service.decide(graph.goal.id, decision.id, 'new_class', '按新类型处理');
+
+ const after = await service.graph(graph.goal.id);
+ const plan = after.nodes.find(
+ (node) => node.id === after.goal.config!.rolloutState!.templateNodeId,
+ )!;
+ // The v2 correction belongs to the old class; the fork starts clean.
+ expect(plan.description).not.toContain('补上冷启动这一步');
+ expect(plan.description).toContain('把 store 换成 replica 支撑的实现');
+ });
+ });
+
+ it('routes a batch unit out of verification retries through the batch gate', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ problemStatement: '把 50 个同构的 store 迁移到 replica',
+ rollout: {
+ recipeOutline: '把 store 换成 replica 支撑的实现',
+ repeatable: true,
+ unitCount: 50,
+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
+ variants: [],
+ },
+ tasks: Array.from({ length: 5 }, (_, i) => ({
+ dependsOn: [],
+ instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
+ title: `Unit ${i + 1}`,
+ })),
+ });
+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({
+ config: { recovery: { maxAttemptsPerTask: 1 } },
+ title: 'Migrate stores',
+ });
+ await service.tick(graph.goal.id);
+ const dispatched = await service.tick(graph.goal.id);
+ expect(dispatched.taskId).toBeDefined();
+
+ // The unit's one attempt failed verification: no attempts left.
+ const taskModel = new TaskModel(serverDB, userId);
+ await taskModel.update(dispatched.taskId!, { totalTopics: 1 });
+ await taskModel.updateStatus(dispatched.taskId!, 'paused', {
+ error: VERIFICATION_FAILED_ERROR,
+ });
+ // The other probes dispatch first; the paused unit's turn follows.
+ for (let i = 0; i < 8; i++) {
+ await service.tick(graph.goal.id);
+ if ((await service.graph(graph.goal.id)).goal.config!.rolloutState!.phase !== 'probe') break;
+ }
+
+ // It breaks the class — revise the recipe and re-probe — rather than
+ // parking on an ordinary retry/retire gate for one task.
+ const state = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;
+ expect(state.phase).toBe('pattern_break');
+ expect(state.gateLog?.at(-1)).toMatchObject({
+ nodeId: dispatched.nodeId,
+ outcome: 'blocked',
+ trigger: 'unit',
+ });
+ });
+
+ it('releases a wave once when two advances pass the gate together', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ problemStatement: '把 50 个同构的 store 迁移到 replica',
+ rollout: {
+ recipeOutline: '把 store 换成 replica 支撑的实现',
+ repeatable: true,
+ unitCount: 50,
+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
+ variants: [],
+ },
+ tasks: Array.from({ length: 5 }, (_, i) => ({
+ dependsOn: [],
+ instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
+ title: `Unit ${i + 1}`,
+ })),
+ });
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ title: 'Migrate stores' });
+ await service.tick(graph.goal.id);
+ const graphModel = new GoalGraphModel(serverDB, userId);
+ const probeIds = (await service.graph(graph.goal.id)).goal.config!.rolloutState!.probeNodeIds;
+ for (const id of probeIds) await graphModel.updateNodeStatus(graph.goal.id, id, 'resolved');
+
+ // Two settled tasks each queued an advance; both see the gate pass.
+ await Promise.all([service.tick(graph.goal.id), service.tick(graph.goal.id)]);
+
+ const after = await service.graph(graph.goal.id);
+ const state = after.goal.config!.rolloutState!;
+ const released = after.nodes.filter(
+ (n) => n.kind === 'task' && !probeIds.includes(n.id) && /^Unit \d+$/.test(n.title),
+ );
+ // One wave, once: no duplicate units and the cursor counts it once.
+ expect(released.map((n) => n.title).sort()).toEqual(
+ [...new Set(released.map((n) => n.title))].sort(),
+ );
+ expect(state.massNodeIds).toHaveLength(released.length);
+ expect(state.releasedCount).toBe(probeIds.length + released.length);
+ expect(state.gateLog?.filter((entry) => entry.outcome === 'released')).toHaveLength(1);
+ });
+
+ it('stops the running Tasks of the members a restart retires', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ problemStatement: '把 50 个同构的 store 迁移到 replica',
+ rollout: {
+ recipeOutline: '把 store 换成 replica 支撑的实现',
+ repeatable: true,
+ unitCount: 50,
+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
+ variants: [],
+ },
+ tasks: Array.from({ length: 5 }, (_, i) => ({
+ dependsOn: [],
+ instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
+ title: `Unit ${i + 1}`,
+ })),
+ });
+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ title: 'Migrate stores' });
+ await service.tick(graph.goal.id);
+ for (let i = 0; i < 5; i++) await service.tick(graph.goal.id);
+
+ const graphModel = new GoalGraphModel(serverDB, userId);
+ const goalModel = new GoalModel(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const before = await service.graph(graph.goal.id);
+ const state = before.goal.config!.rolloutState!;
+ const [broken, sibling] = state.probeNodeIds.map((id) =>
+ before.nodes.find((node) => node.id === id)!,
+ );
+ expect(sibling.taskId).toBeTruthy();
+ // One unit broke while a sibling is still running.
+ await graphModel.updateNodeStatus(graph.goal.id, broken.id, 'rejected');
+ await taskModel.updateStatus(sibling.taskId!, 'running');
+
+ const decision = await graphModel.createDecision(graph.goal.id, state.assayNodeId!, {
+ authority: 'user',
+ options: [{ id: 'revise', label: 'Revise' }],
+ question: 'Unit 1 did not pass',
+ requestedUserId: userId,
+ });
+ await graphModel.updateNodeStatus(graph.goal.id, state.assayNodeId!, 'waiting');
+ await goalModel.updateRolloutState(graph.goal.id, { ...state, phase: 'pattern_break' });
+ await serverDB.update(goals).set({ status: 'paused' }).where(eq(goals.id, graph.goal.id));
+
+ await service.decide(graph.goal.id, decision!.id, 'revise', '补上冷启动这一步');
+
+ // The sibling is retired and its Task stopped — it no longer runs beside
+ // the probe that replaces it.
+ const after = await service.graph(graph.goal.id);
+ expect(after.nodes.find((node) => node.id === sibling.id)?.status).toBe('retired');
+ const [task] = await taskModel.findByIds([sibling.taskId!]);
+ expect(task.status).toBe('canceled');
+ });
+
+ it('keeps a re-opened probe briefed with its variant assignment', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ problemStatement: '把 50 个同构的 store 迁移到 replica',
+ rollout: {
+ recipeOutline: '把 store 换成 replica 支撑的实现',
+ repeatable: true,
+ unitCount: 50,
+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
+ variants: [{ axis: 'render', values: ['ssr', 'csr'] }],
+ },
+ tasks: Array.from({ length: 5 }, (_, i) => ({
+ dependsOn: [],
+ instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现,按 ${i === 0 ? 'ssr' : 'csr'} 路径验证`,
+ title: `Unit ${i + 1}`,
+ })),
+ });
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ title: 'Migrate stores' });
+ await service.tick(graph.goal.id);
+
+ const graphModel = new GoalGraphModel(serverDB, userId);
+ const goalModel = new GoalModel(serverDB, userId);
+ const before = await service.graph(graph.goal.id);
+ const state = before.goal.config!.rolloutState!;
+ const ssrProbe = before.nodes.find((node) => node.title === 'Unit 1')!;
+ await graphModel.updateNodeStatus(graph.goal.id, ssrProbe.id, 'rejected');
+ const decision = await graphModel.createDecision(graph.goal.id, state.assayNodeId!, {
+ authority: 'user',
+ options: [{ id: 'revise', label: 'Revise' }],
+ question: 'Unit 1 did not pass',
+ requestedUserId: userId,
+ });
+ await graphModel.updateNodeStatus(graph.goal.id, state.assayNodeId!, 'waiting');
+ await goalModel.updateRolloutState(graph.goal.id, { ...state, phase: 'pattern_break' });
+ await serverDB.update(goals).set({ status: 'paused' }).where(eq(goals.id, graph.goal.id));
+
+ await service.decide(graph.goal.id, decision!.id, 'revise', '补上冷启动这一步');
+
+ // The re-opened probe still says which variant it covers, so the gate does
+ // not report the axis value it tested as untested.
+ const after = await service.graph(graph.goal.id);
+ const next = after.goal.config!.rolloutState!;
+ const reopened = after.nodes.find(
+ (node) => next.probeNodeIds.includes(node.id) && node.title === 'Unit 1',
+ )!;
+ expect(reopened.description).toContain('按 ssr 路径验证');
+ const probes = after.nodes.filter((node) => next.probeNodeIds.includes(node.id));
+ expect(
+ uncoveredAxisValues(
+ [{ axis: 'render', values: ['ssr', 'csr'] }],
+ probes.map((node) => ({ instruction: node.description ?? '', title: node.title })),
+ ),
+ ).not.toContainEqual({ axis: 'render', value: 'ssr' });
+ });
+
+ it('re-opens the broken unit as a new task when the canary loop restarts', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ problemStatement: '把 50 个同构的 store 迁移到 replica',
+ rollout: {
+ recipeOutline: '把 store 换成 replica 支撑的实现',
+ repeatable: true,
+ unitCount: 50,
+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
+ variants: [],
+ },
+ tasks: Array.from({ length: 5 }, (_, i) => ({
+ dependsOn: [],
+ instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
+ title: `Unit ${i + 1}`,
+ })),
+ });
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ title: 'Migrate stores' });
+ await service.tick(graph.goal.id);
+
+ const graphModel = new GoalGraphModel(serverDB, userId);
+ const goalModel = new GoalModel(serverDB, userId);
+ const before = await service.graph(graph.goal.id);
+ const state = before.goal.config!.rolloutState!;
+ const [broken, ...settled] = state.probeNodeIds;
+ for (const id of settled) await graphModel.updateNodeStatus(graph.goal.id, id, 'resolved');
+ await graphModel.updateNodeStatus(graph.goal.id, broken, 'waiting');
+ // A wave the round already released, whose member broke and was retired.
+ const massMember = await graphModel.createNode(graph.goal.id, {
+ kind: 'task',
+ scopeId: state.batchNodeId,
+ title: 'Unit 6',
+ });
+ await graphModel.updateNodeStatus(graph.goal.id, massMember!.id, 'retired');
+
+ const decision = await graphModel.createDecision(graph.goal.id, state.assayNodeId!, {
+ authority: 'user',
+ options: [
+ { description: '修订配方', id: 'revise', label: '修订配方并重探' },
+ { description: '新类型', id: 'new_class', label: '作为新类型并排处理' },
+ ],
+ question: 'Unit 1 did not pass',
+ requestedUserId: userId,
+ });
+ await graphModel.updateNodeStatus(graph.goal.id, state.assayNodeId!, 'waiting');
+ await goalModel.updateRolloutState(graph.goal.id, {
+ ...state,
+ massNodeIds: [massMember!.id],
+ phase: 'pattern_break',
+ });
+ await serverDB.update(goals).set({ status: 'paused' }).where(eq(goals.id, graph.goal.id));
+
+ await service.decide(graph.goal.id, decision!.id, 'revise', '补上冷启动这一步');
+
+ const after = await service.graph(graph.goal.id);
+ const next = after.goal.config!.rolloutState!;
+ // Decision #4: the broken unit runs again as a new task, the old one retires.
+ expect(after.nodes.find((n) => n.id === broken)?.status).toBe('retired');
+ // Both units that broke this round — the probe and the wave member — re-open.
+ const reopenedNodes = next.probeNodeIds.map((id) => after.nodes.find((n) => n.id === id)!);
+ expect(reopenedNodes.map((n) => n.title).sort()).toEqual(['Unit 1', 'Unit 6']);
+ const reopened = reopenedNodes.find((n) => n.title === 'Unit 1')!;
+ expect(
+ after.edges.some(
+ (e) =>
+ e.kind === 'derived_from' && e.sourceNodeId === reopened.id && e.targetNodeId === broken,
+ ),
+ ).toBe(true);
+ // Re-opening is not a new release: the roster is re-cut to what is still
+ // owed, so the cursor counts the re-opened probes over the shorter roster,
+ // and the units the class still owes stay queued for the waves.
+ expect(next.releasedCount).toBe(next.probeNodeIds.length);
+ expect(next.unitTitles).toContain('Unit 50');
+ expect(new Set(next.unitTitles).size).toBe(next.unitTitles!.length);
+ // The revised plan carries v1 forward and appends what changed, so the two
+ // versions diff as "v1 + the v2 section", not as a replacement.
+ const plan = after.nodes.find((n) => n.id === next.templateNodeId)!;
+ expect(plan.description).toBe('把 store 换成 replica 支撑的实现\n\n### v2\n补上冷启动这一步');
+ // The new canary is a fresh round: the old wave's retired member no longer
+ // counts against its gate (it would re-open the same break at once).
+ expect(next.massNodeIds).toBeUndefined();
+ });
+
+ it('persists the planned recipe when the caller already chose a canary rollout', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ problemStatement: '把 50 个同构的 store 迁移到 replica',
+ rollout: {
+ recipeOutline: '把 store 换成 replica 支撑的实现',
+ repeatable: true,
+ unitCount: 50,
+ units: Array.from({ length: 50 }, (_, i) => `Unit ${i + 1}`),
+ variants: [{ axis: 'cold-start', values: ['yes', 'no'] }],
+ },
+ tasks: Array.from({ length: 5 }, (_, i) => ({
+ dependsOn: [],
+ instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
+ title: `Unit ${i + 1}`,
+ })),
+ });
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({
+ config: { rollout: { canarySize: 3, trigger: 'canary', waveSize: 7 } },
+ title: 'Migrate stores',
+ });
+ await service.tick(graph.goal.id);
+
+ const policy = (await service.graph(graph.goal.id)).goal.config!.rollout!;
+ // What the planner derived is kept — later waves brief from it, the gate checks its axes…
+ expect(policy.spec?.recipeOutline).toBe('把 store 换成 replica 支撑的实现');
+ expect(policy.spec?.variantAxes).toEqual([{ axis: 'cold-start', values: ['yes', 'no'] }]);
+ expect(policy.units).toHaveLength(50);
+ // …and what the caller chose still wins.
+ expect(policy).toMatchObject({ canarySize: 3, trigger: 'canary', waveSize: 7 });
+ });
+
it('asks a blocking question before planning, then plans once with the answer', async () => {
const planner = vi
.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose')
@@ -2797,6 +3879,57 @@ describe('GoalService', () => {
).toEqual(leaves.sort());
});
+ it('builds the Goal-level Acceptance Task on the units a batch delivered', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ problemStatement: '把 7 个同构的 store 迁移到 replica',
+ rollout: {
+ recipeOutline: '把 store 换成 replica 支撑的实现',
+ repeatable: true,
+ unitCount: 7,
+ units: Array.from({ length: 7 }, (_, i) => `Unit ${i + 1}`),
+ variants: [],
+ },
+ tasks: Array.from({ length: 5 }, (_, i) => ({
+ dependsOn: [],
+ instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
+ title: `Unit ${i + 1}`,
+ })),
+ });
+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({
+ config: { rollout: { minHomogeneousUnits: 5, trigger: 'full' } },
+ requirement: 'Migrate every store.',
+ title: 'Batch to acceptance',
+ });
+
+ let acceptance;
+ for (let i = 0; i < 30 && !acceptance; i++) {
+ await service.tick(graph.goal.id);
+ const current = await service.graph(graph.goal.id);
+ for (const node of current.nodes) {
+ if (node.taskId && node.title !== 'Complete full Goal acceptance')
+ await taskModel.updateStatus(node.taskId, 'completed');
+ }
+ acceptance = current.nodes.find((node) => node.title === 'Complete full Goal acceptance');
+ }
+
+ // The report walks back from acceptance; the batch's units must be on that path.
+ const current = await service.graph(graph.goal.id);
+ const units = current.nodes
+ .filter((node) => /^Unit \d+$/.test(node.title) && node.status === 'resolved')
+ .map((node) => node.id);
+ expect(acceptance).toBeTruthy();
+ expect(units).toHaveLength(7);
+ expect(
+ current.edges
+ .filter((edge) => edge.kind === 'depends_on' && edge.sourceNodeId === acceptance!.id)
+ .map((edge) => edge.targetNodeId)
+ .sort(),
+ ).toEqual(units.sort());
+ });
+
/**
* Regression: the acceptance node and its dependency edges were written in
* separate transactions. A failure between them left the node without its
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index 205f41f80c1..05eb3663ae7 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -2,10 +2,19 @@ import type { GoalAdvanceEffect, GoalMetricCriteriaState } from '@lobechat/agent
import { buildGoalRequirement } from '@lobechat/builtin-tool-goal';
import {
DEVICE_OFFLINE_RUN_STATUS,
+ GOAL_BATCH_ASSAY_TITLE,
+ GOAL_BATCH_BREAK_OPTION,
+ GOAL_BATCH_BREAK_QUESTION_TAIL,
+ GOAL_BATCH_TEMPLATE_TITLE,
+ GOAL_BATCH_TITLE,
GOAL_CLARIFICATION_OPTION,
GOAL_CLARIFICATION_TITLE,
GOAL_COORDINATOR_ACTOR_ID,
GOAL_MACHINE_GATE_TITLE,
+ PATTERN_BREAK_PAUSE_REASON,
+ ROLLOUT_CANARY_SIZE_DEFAULT,
+ ROLLOUT_MAX_CANARY_SIZE,
+ ROLLOUT_WAVE_SIZE_DEFAULT,
} from '@lobechat/const/goal';
import type {
ChatTopicMetadata,
@@ -24,6 +33,7 @@ import type {
GoalNodeKind,
GoalNodeStatus,
GoalPauseReason,
+ GoalRolloutState,
GoalStatus,
GoalTickResult,
MetricKind,
@@ -34,6 +44,7 @@ import type {
import { isAgentOperationInFlight } from '@lobechat/types';
import { experimentOwner, provenanceParentId } from '@lobechat/utils/goalGraph';
import { TRPCError } from '@trpc/server';
+import debug from 'debug';
import { sql } from 'drizzle-orm';
import { AgentModel } from '@/database/models/agent';
@@ -92,7 +103,9 @@ import {
import { isGoalReportNode, withoutGoalReport } from './report';
import { GoalReportService } from './reportService';
import { GoalReportStore } from './reportStore';
+import { evaluateRolloutGate, type RolloutGateResult, withGateVerdict } from './rolloutGate';
import { scheduleGoalAdvance } from './scheduler';
+import { evaluateHomogeneity } from './spec';
import { GoalSupervisorService } from './supervisor';
import { statusAuthoredByActor } from './supervisor/policy';
import { claimGoalTask } from './taskClaim';
@@ -130,6 +143,84 @@ const TASK_DESCRIPTION_MAX_LENGTH = 255;
const GOAL_ENDED_STATUSES = new Set<string>(['achieved', 'canceled']);
/** Advisory-lock namespace for goal dispatch. `0x676f_6469` is ASCII `godi`. */
const GOAL_DISPATCH_LOCK_NAMESPACE = 0x67_6f_64_69;
+/** Why a decomposition did or did not become a batch: DEBUG=lobe-server:goal-rollout. */
+const log = debug('lobe-server:goal-rollout');
+/** Upper bound on a batch roster; a planner that over-lists cannot swamp the config. */
+const MAX_ROLLOUT_ROSTER = 60;
+/**
+ * The roster the coordinator promotes from, probes first. The probe titles come
+ * from the tasks actually created; the rest come from the planner's `units`,
+ * de-duplicated. A planner that omitted `units` degrades to probes-only, which
+ * delivers the class without a mass phase rather than inventing units.
+ *
+ * `limit` bounds the roster a *batch* carries (its config safety valve); the
+ * ordinary fallback passes no limit, because trimming there would silently drop
+ * units the goal promised to deliver.
+ */
+const normalizeRolloutRoster = (
+ units: string[] | undefined,
+ probeDrafts: GoalDecompositionDraft['tasks'],
+ canarySize: number,
+ limit: number = MAX_ROLLOUT_ROSTER,
+): string[] => {
+ const probeTitles = probeDrafts.slice(0, canarySize).map((draft) => draft.title);
+ const seen = new Set(probeTitles);
+ const rest: string[] = [];
+ for (const unit of units ?? []) {
+ const title = unit.trim();
+ if (!title || seen.has(title)) continue;
+ seen.add(title);
+ rest.push(title);
+ if (probeTitles.length + rest.length >= limit) break;
+ }
+ return [...probeTitles, ...rest];
+};
+
+/** Heads the brief a unit carries over from its first run when it is re-opened. */
+const UNIT_BRIEF_HEADING = 'Unit brief (from its first run):';
+
+/**
+ * The per-unit brief a re-opened unit must keep: the first-hand probe brief
+ * (which may be the only place its variant assignment is stated), or the one a
+ * previous re-open already carried over. A unit briefed only from the shared
+ * recipe has none of its own.
+ */
+const carriedUnitBrief = (node: { description?: string | null; title: string }) => {
+ const description = node.description?.trim();
+ if (!description) return undefined;
+ const carried = description.indexOf(UNIT_BRIEF_HEADING);
+ if (carried >= 0) return description.slice(carried + UNIT_BRIEF_HEADING.length).trim();
+ return description.endsWith(`Unit: ${node.title}`) ? undefined : description;
+};
+
+/**
+ * Materialize one roster unit as a Task inside a batch. The brief is the shared
+ * recipe applied to this unit — the probes carry the full first-hand brief, the
+ * units promoted later reuse what the Template already proved. A re-opened unit
+ * also keeps its own first-hand brief.
+ */
+const createRecipeUnitTask = async (
+ writer: GoalGraphModel,
+ goalId: string,
+ batchNodeId: string,
+ title: string,
+ recipeOutline?: string,
+ unitBrief?: string,
+): Promise<string | undefined> => {
+ const node = await writer.createNode(goalId, {
+ description: [
+ recipeOutline,
+ `Unit: ${title}`,
+ unitBrief && `${UNIT_BRIEF_HEADING}\n${unitBrief}`,
+ ]
+ .filter(Boolean)
+ .join('\n\n'),
+ kind: 'task',
+ scopeId: batchNodeId,
+ title,
+ });
+ return node?.id;
+};
/** Who does the goal's Tasks: its dedicated executor, else the goal agent itself. */
export const goalTaskAgentId = (goal: Pick<GoalItem, 'agentId' | 'config'>) =>
@@ -1576,6 +1667,52 @@ export class GoalService {
taskTopicModel: new TaskTopicModel(this.db, goal.userId, this.workspaceId),
};
+ /**
+ * Stop the Tasks bound to nodes already fenced as `retired`, so a retired
+ * node cannot keep spending or deliver into the Goal afterwards. Bound Tasks
+ * are read after the fence so a Task bound just before it is included.
+ * Returns the graph as read after the fence.
+ */
+ private stopFencedTasks = async (goalId: string, targetIds: ReadonlySet<string>) => {
+ const fenced = await this.requireGraph(goalId);
+ const taskIds = fenced.nodes.flatMap((node) =>
+ targetIds.has(node.id) && node.taskId ? [node.taskId] : [],
+ );
+ if (taskIds.length > 0) {
+ // The caller may be a workspace owner retiring a colleague's goal (the
+ // router authorizes that). The nodes' Tasks were created by the goal's
+ // coordinator, which runs as the goal's owner — and may be `private`,
+ // inherited from that owner's private agent — so reads under the caller's
+ // visibility would miss them and leave them running. Stop them under the
+ // goal owner's principal instead, limited to the Tasks bound to the nodes
+ // being retired.
+ const { taskModel, taskService, taskTopicModel } = this.goalOwnerTaskScope(fenced.goal);
+ const cancelTasks = async () => {
+ for (const id of taskIds) {
+ // CAS against the status just read; a runner flipping the Task to
+ // `running` in between makes it miss, so re-read and try again.
+ for (let attempt = 0; attempt < 3; attempt++) {
+ const [task] = await taskModel.findByIds([id]);
+ if (!task || ['canceled', 'completed', 'failed'].includes(task.status)) break;
+ if (await taskModel.updateStatusIfCurrent(id, task.status, 'canceled')) break;
+ }
+ }
+ };
+ // Cancel the Tasks FIRST: that is the fence a run still being dispatched
+ // checks under the Task's row lock before recording its operation, so a
+ // run started from here on stops itself (TaskRunnerService.runTask).
+ // Runs recorded before the fence are then found and stopped below.
+ await cancelTasks();
+ for (const topic of await taskTopicModel.findRunningByTaskIds(taskIds)) {
+ if (topic.topicId) await taskService.cancelTopic(topic.topicId);
+ }
+ // `cancelTopic` parks its Task as `paused`; settle them back to canceled.
+ await cancelTasks();
+ }
+
+ return fenced;
+ };
+
/**
* Retire Task nodes a person no longer wants run — a duplicated plan branch,
* work that landed elsewhere. Without this a stray node that never got a Task
@@ -1651,43 +1788,8 @@ export class GoalService {
}
// Stop what the nodes are still running, so a retired node cannot keep
- // spending or deliver into the Goal afterwards. Bound Tasks are read after
- // the fence so a Task bound just before it is included.
- const fenced = await this.requireGraph(goalId);
- const taskIds = fenced.nodes.flatMap((node) =>
- targetIds.has(node.id) && node.taskId ? [node.taskId] : [],
- );
- if (taskIds.length > 0) {
- // The caller may be a workspace owner retiring a colleague's goal (the
- // router authorizes that). The nodes' Tasks were created by the goal's
- // coordinator, which runs as the goal's owner — and may be `private`,
- // inherited from that owner's private agent — so reads under the caller's
- // visibility would miss them and leave them running. Stop them under the
- // goal owner's principal instead, limited to the Tasks bound to the nodes
- // being retired.
- const { taskModel, taskService, taskTopicModel } = this.goalOwnerTaskScope(fenced.goal);
- const cancelTasks = async () => {
- for (const id of taskIds) {
- // CAS against the status just read; a runner flipping the Task to
- // `running` in between makes it miss, so re-read and try again.
- for (let attempt = 0; attempt < 3; attempt++) {
- const [task] = await taskModel.findByIds([id]);
- if (!task || ['canceled', 'completed', 'failed'].includes(task.status)) break;
- if (await taskModel.updateStatusIfCurrent(id, task.status, 'canceled')) break;
- }
- }
- };
- // Cancel the Tasks FIRST: that is the fence a run still being dispatched
- // checks under the Task's row lock before recording its operation, so a
- // run started from here on stops itself (TaskRunnerService.runTask).
- // Runs recorded before the fence are then found and stopped below.
- await cancelTasks();
- for (const topic of await taskTopicModel.findRunningByTaskIds(taskIds)) {
- if (topic.topicId) await taskService.cancelTopic(topic.topicId);
- }
- // `cancelTopic` parks its Task as `paused`; settle them back to canceled.
- await cancelTasks();
- }
+ // spending or deliver into the Goal afterwards.
+ const fenced = await this.stopFencedTasks(goalId, targetIds);
// A pending recovery gate on a retired node asks a question nobody needs
// answered any more; left pending it keeps the Goal parked in review.
@@ -2022,13 +2124,31 @@ export class GoalService {
if (optionId === GOAL_CLARIFICATION_OPTION.answer && !resolution?.trim()) {
throw new TRPCError({ code: 'BAD_REQUEST', message: 'This answer needs a note' });
}
+ // Revising a batch recipe without a correction would re-run the plan that
+ // just failed under a new version number. The correction is the revision.
+ if (optionId === GOAL_BATCH_BREAK_OPTION.revise && !resolution?.trim()) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Revising the recipe needs a correction',
+ });
+ }
const chosen = decision.options?.find((option) => option.id === optionId);
- const resolved = await this.graphModel.resolveDecision(
- goalId,
- decisionId,
- optionId,
- resolution,
- );
+ // R5: a person answering a batch gate IS the intervention, and an
+ // intervention rolls the class back to canary. Open the next recipe round
+ // automatically — revise the same mould, or fork it as a new class — rather
+ // than leaving the goal parked for someone to rerun by hand. The gate hangs
+ // on the Assay (materialized on demand for a `full` rollout), so match that,
+ // falling back to the batch node for any gate opened elsewhere. The restart
+ // consumes the answer itself, atomically with the round it opens.
+ const rolloutState = graph.goal.config?.rolloutState;
+ const patternBreakNodeId = rolloutState?.assayNodeId ?? rolloutState?.batchNodeId;
+ const answersBatchBreak =
+ rolloutState?.phase === 'pattern_break' &&
+ patternBreakNodeId !== undefined &&
+ decision.nodeId === patternBreakNodeId;
+ const resolved = answersBatchBreak
+ ? await this.restartRolloutLoop(goalId, decisionId, optionId, resolution)
+ : await this.graphModel.resolveDecision(goalId, decisionId, optionId, resolution);
if (!resolved)
throw new TRPCError({ code: 'CONFLICT', message: 'Decision was already resolved' });
@@ -2307,12 +2427,16 @@ export class GoalService {
: undefined;
const concurrency = resolveMaxConcurrentTasks(graph.goal);
+ // A repeated batch judges its own gate once the wave it released has fully
+ // settled; while a wave is still running the ordinary frontier owns the tick.
+ const rolloutGate = this.collectRolloutGate(graph);
const move = decideNextMove({
budget,
concurrency,
frontier,
graph,
metricCriteria,
+ rolloutGate,
tasksById,
});
// The scheduler may pick past the head of the frontier, so every arm below
@@ -2414,6 +2538,16 @@ export class GoalService {
return observe(await this.planDecomposition(graph, effects));
}
+ case 'rollout_gate': {
+ return observe(await this.releaseRolloutWave(graph, effects, rolloutGate));
+ }
+
+ case 'pattern_break': {
+ return observe(
+ await this.openPatternBreakGate(graph, move.message, effects, { gate: rolloutGate }),
+ );
+ }
+
case 'no_frontier': {
// Say so on the row instead of leaving a goal that reads as `running`
// while it cannot run — and, just as importantly, take it out of the
@@ -2464,6 +2598,20 @@ export class GoalService {
}
case 'failure_decision': {
+ // R6: a batch member that did not pass its own check IS the same
+ // intervention as a blocked gate. Route it through the batch gate so
+ // the class rolls back to canary, instead of parking on a standalone
+ // task decision that never touches the recipe.
+ if (this.isBatchMember(graph, acting!.id)) {
+ return observe(
+ await this.openPatternBreakGate(
+ graph,
+ `${acting!.title}: ${move.message}`,
+ effects,
+ { unitId: acting!.id },
+ ),
+ );
+ }
const waiting =
(await this.waitForDevice(graph, acting!.id, task, effects)) ??
(await this.waitForQuotaReset(graph, acting!.id, task, effects));
@@ -2486,6 +2634,18 @@ export class GoalService {
}
case 'task_paused': {
+ // R6: a paused batch member (e.g. its delivery did not pass
+ // verification) is an intervention on the class, not on one task.
+ if (this.isBatchMember(graph, acting!.id)) {
+ return observe(
+ await this.openPatternBreakGate(
+ graph,
+ `${acting!.title}: ${move.message}`,
+ effects,
+ { unitId: acting!.id },
+ ),
+ );
+ }
return observe({
goalId,
message: move.message,
@@ -2598,13 +2758,19 @@ export class GoalService {
// Acceptance closes the whole Goal, so it builds on the work that ends each
// line of the graph. Linking the delivered leaf Tasks lays it out below them
// instead of beside the first round. They are all resolved, so nothing blocks.
- const delivered = graph.nodes.filter(
- (node) =>
- node.kind === 'task' &&
- node.status === 'resolved' &&
- node.id !== created.node.id &&
- !experimentOwner(graph, node.id),
- );
+ // An experiment's Tasks are a candidate answer and stay inside it; a
+ // batch's units ARE the delivered work, so they count as leaves too —
+ // otherwise the report, which walks back from acceptance, never sees them.
+ const ownerKind = (nodeId: string) => {
+ const owner = experimentOwner(graph, nodeId);
+ return owner ? graph.nodes.find((node) => node.id === owner)?.kind : undefined;
+ };
+ const delivered = graph.nodes.filter((node) => {
+ if (node.kind !== 'task' || node.status !== 'resolved' || node.id === created.node.id)
+ return false;
+ const kind = ownerKind(node.id);
+ return !kind || kind === 'batch';
+ });
const deliveredIds = new Set(delivered.map((node) => node.id));
const builtUpon = new Set(
graph.edges
@@ -2846,6 +3012,22 @@ export class GoalService {
: recovery.outcome === 'exhausted-rounds'
? 'Task attempt budget was exhausted'
: 'Automatic recovery could not start the next attempt';
+ // R6: a batch member that ran out of attempts to pass its own check breaks
+ // the class, like one that failed outright — revise the recipe and re-probe,
+ // not a standalone retry/retire gate (retiring a last-wave member would let
+ // the goal head for acceptance with the unit undone). A spent goal budget
+ // and a run that never started are not the recipe's fault: those keep the
+ // ordinary gate.
+ if (
+ recovery.outcome !== 'exhausted-cost' &&
+ recovery.outcome !== 'spawn-failed' &&
+ this.isBatchMember(graph, nodeId)
+ ) {
+ const title = graph.nodes.find((node) => node.id === nodeId)?.title ?? task.identifier;
+ return this.openPatternBreakGate(graph, `${title}: ${exhaustedReason}`, effects, {
+ unitId: nodeId,
+ });
+ }
return this.gateOrTakeOver(graph, nodeId, task.id, exhaustedReason, effects, {
machine: recovery.outcome === 'spawn-failed',
});
@@ -3631,8 +3813,192 @@ export class GoalService {
return committedEffects;
}
+ // Batch roll-out: when the planner judges this goal to be one repeated
+ // mould — and `spec.ts` agrees — decompose it as a class rather than as
+ // N flat siblings. The graph gets one `batch` container, one Template,
+ // one Assay and only the K fully-briefed probe tasks; the roster waits in
+ // `rolloutState` and the coordinator releases it one wave at a time.
+ const rolloutClaim = plan?.rollout ?? null;
+ const existingRollout = current.config?.rollout;
+ const rolloutTrigger = existingRollout?.trigger ?? 'canary';
+ const rolloutEnabled = rolloutTrigger !== 'off';
+ const verdict =
+ rolloutClaim && rolloutEnabled
+ ? evaluateHomogeneity(
+ rolloutClaim,
+ draftTasks.map((draft) => ({ instruction: draft.instruction, title: draft.title })),
+ {
+ maxUnits: MAX_ROLLOUT_ROSTER,
+ minUnits: existingRollout?.minHomogeneousUnits,
+ },
+ )
+ : { batch: false, reasons: [] as string[] };
+
+ log(
+ 'decomposition rollout: trigger=%s claim=%o tasks=%d verdict=%o',
+ rolloutTrigger,
+ rolloutClaim,
+ draftTasks.length,
+ verdict,
+ );
+
+ if (rolloutClaim && rolloutEnabled && verdict.batch && currentProblem) {
+ const roster = normalizeRolloutRoster(rolloutClaim.units, draftTasks, draftTasks.length);
+ const canarySize =
+ rolloutTrigger === 'full'
+ ? roster.length
+ : Math.max(
+ 2,
+ Math.min(
+ existingRollout?.canarySize ?? ROLLOUT_CANARY_SIZE_DEFAULT,
+ ROLLOUT_MAX_CANARY_SIZE,
+ draftTasks.length,
+ ),
+ );
+
+ const batch = await writer.createNode(goalId, {
+ description: rolloutClaim.recipeOutline,
+ kind: 'batch',
+ title: GOAL_BATCH_TITLE,
+ });
+ if (!batch) throw new Error('Failed to create a planned batch');
+ await writer.createEdge(goalId, currentProblem.id, batch.id, 'decomposes');
+
+ const template = await writer.createNode(goalId, {
+ description: rolloutClaim.recipeOutline,
+ kind: 'finding',
+ scopeId: batch.id,
+ title: GOAL_BATCH_TEMPLATE_TITLE,
+ });
+ if (!template) throw new Error('Failed to create a batch template');
+
+ // The Assay is the gate. It is a `decision` node so a failed gate has
+ // somewhere to hang the human question, but it carries NO pending
+ // decision yet — opening one now would park the goal before a probe ran.
+ // A `full` roll-out skips the probe, so it opens no gate at all.
+ const assay =
+ rolloutTrigger === 'full'
+ ? undefined
+ : await writer.createNode(goalId, {
+ description:
+ 'Whether this repeated batch can be delivered without further human decisions.',
+ kind: 'decision',
+ scopeId: batch.id,
+ status: 'proposed',
+ title: GOAL_BATCH_ASSAY_TITLE,
+ });
+ if (rolloutTrigger !== 'full' && !assay)
+ throw new Error('Failed to create a batch assay');
+
+ const probeDrafts = draftTasks.slice(0, canarySize);
+ const probeIds: string[] = [];
+ for (const draft of probeDrafts) {
+ const node = await writer.createNode(goalId, {
+ description: draft.instruction,
+ kind: 'task',
+ scopeId: batch.id,
+ title: draft.title,
+ });
+ if (!node) throw new Error('Failed to create a probe task');
+ probeIds.push(node.id);
+ committedEffects.push({ nodeId: node.id, type: 'created_node', detail: draft.title });
+ }
+
+ // The gate depends on every probe: `selectFrontier` reads `depends_on`
+ // as blocks, so the gate cannot be evaluated until they settle.
+ if (assay) {
+ for (const probeId of probeIds) {
+ await writer.createEdge(goalId, assay.id, probeId, 'depends_on');
+ }
+ }
+ // Honour the planner's own intra-probe dependencies too.
+ for (const [index, draft] of probeDrafts.entries()) {
+ for (const dep of new Set(draft.dependsOn ?? [])) {
+ if (dep < index && probeIds[dep]) {
+ await writer.createEdge(goalId, probeIds[index], probeIds[dep], 'depends_on');
+ }
+ }
+ }
+
+ // A `full` roll-out releases the rest of the roster immediately, as the
+ // single wave the trigger promises; `canary` waits for the gate.
+ const massNodeIds: string[] = [];
+ if (rolloutTrigger === 'full') {
+ for (const title of roster.slice(probeIds.length)) {
+ const nodeId = await createRecipeUnitTask(
+ writer,
+ goalId,
+ batch.id,
+ title,
+ rolloutClaim.recipeOutline,
+ );
+ if (nodeId) massNodeIds.push(nodeId);
+ }
+ }
+
+ const rolloutState: GoalRolloutState = {
+ batchNodeId: batch.id,
+ assayNodeId: assay?.id,
+ massNodeIds: massNodeIds.length ? massNodeIds : undefined,
+ phase: rolloutTrigger === 'full' ? 'mass' : 'probe',
+ probeNodeIds: probeIds,
+ releasedCount: probeIds.length + massNodeIds.length,
+ templateNodeId: template.id,
+ templateRevision: 1,
+ unitTitles: roster,
+ waveIndex: rolloutTrigger === 'full' ? 1 : 0,
+ };
+ await goalModel.updateRolloutState(goalId, rolloutState);
+
+ // Always persist what the planner derived — later waves brief their
+ // tasks from the recipe and the gate checks its variant axes — while
+ // keeping whatever the caller chose (trigger, sizes) on top.
+ await goalModel.updateRolloutPolicy(goalId, {
+ ...existingRollout,
+ canarySize:
+ rolloutTrigger === 'full' ? undefined : (existingRollout?.canarySize ?? canarySize),
+ spec: {
+ recipeOutline: rolloutClaim.recipeOutline,
+ repeatable: rolloutClaim.repeatable,
+ variantAxes: rolloutClaim.variants,
+ },
+ trigger: rolloutTrigger,
+ units: roster,
+ waveSize: existingRollout?.waveSize ?? ROLLOUT_WAVE_SIZE_DEFAULT,
+ });
+ return committedEffects;
+ }
+
+ // A rollout claim we did NOT turn into a batch — the caller forced
+ // `--rollout off`, or the homogeneity check refused it — still carries
+ // only the 3–5 representative probes in `tasks`, with the complete
+ // roster in `units`. A plain decomposition of `draftTasks` alone would
+ // silently drop every other unit, so materialize the whole roster as
+ // ordinary tasks instead: the probes keep their first-hand briefs, the
+ // rest run from the recipe. The batch config's roster cap does NOT apply
+ // here — trimming the fallback would leave the tail of the requested
+ // goal undelivered. A goal with no claim at all is unchanged.
+ const plannedUnits = rolloutClaim
+ ? normalizeRolloutRoster(
+ rolloutClaim.units,
+ draftTasks,
+ draftTasks.length,
+ Number.POSITIVE_INFINITY,
+ ).map((title, index) => {
+ const draft = draftTasks[index];
+ return {
+ dependsOn: draft?.dependsOn ?? [],
+ hypothesis: draft?.hypothesis,
+ instruction:
+ draft?.instruction ??
+ [rolloutClaim.recipeOutline, `Unit: ${title}`].filter(Boolean).join('\n\n'),
+ title: draft?.title ?? title,
+ };
+ })
+ : draftTasks;
+
const createdIds: string[] = [];
- for (const draft of draftTasks) {
+ for (const draft of plannedUnits) {
// An experiment is a container for a candidate answer, not the
// default shell around every planned step. Only a direction the
// planner marked with a hypothesis gets one; a certain delivery step
@@ -3667,7 +4033,7 @@ export class GoalService {
// dependent → prerequisite the way `decideNextMove` reads a blocker. Only
// earlier indices are honoured, so a hallucinated forward or self reference
// can never form a cycle that deadlocks the frontier.
- for (const [index, draft] of draftTasks.entries()) {
+ for (const [index, draft] of plannedUnits.entries()) {
const nodeId = createdIds[index];
if (!nodeId) continue;
for (const dep of new Set(draft.dependsOn ?? [])) {
@@ -3713,6 +4079,492 @@ export class GoalService {
}
};
+ /**
+ * Judge a repeated batch's gate, but only once the wave it released has fully
+ * settled. Returns undefined when there is nothing to judge: no batch, a batch
+ * already through its gate or parked on a pattern break, or a wave still
+ * running (the ordinary frontier owns that tick). The final wave is judged
+ * like every other — a unit retired or broken in it must stop the batch the
+ * same way — and a pass with the roster exhausted closes the batch.
+ */
+ private collectRolloutGate = (graph: GoalGraphSnapshot): RolloutGateResult | undefined => {
+ const policy = graph.goal.config?.rollout;
+ const state = graph.goal.config?.rolloutState;
+ if (!policy || !state || state.phase === 'done' || state.phase === 'pattern_break')
+ return undefined;
+ const materializedIds = new Set([...state.probeNodeIds, ...(state.massNodeIds ?? [])]);
+ const materialized = graph.nodes.filter((node) => materializedIds.has(node.id));
+ if (materialized.some((node) => !TERMINAL_NODE_STATUSES.has(node.status))) return undefined;
+ return evaluateRolloutGate({ graph, policy, state });
+ };
+
+ /** Whether a node is one of the current batch's released members (R6 routing). */
+ private isBatchMember = (graph: GoalGraphSnapshot, nodeId: string): boolean => {
+ const state = graph.goal.config?.rolloutState;
+ if (!state) return false;
+ return state.probeNodeIds.includes(nodeId) || (state.massNodeIds ?? []).includes(nodeId);
+ };
+
+ /** Release the next wave of a repeated batch once its gate passed. */
+ private releaseRolloutWave = async (
+ graph: GoalGraphSnapshot,
+ effects: GoalAdvanceEffect[],
+ gate?: RolloutGateResult,
+ ): Promise<GoalTickResult> => {
+ const goalId = graph.goal.id;
+ const policy = graph.goal.config?.rollout;
+ const state = graph.goal.config?.rolloutState;
+ if (!policy || !state)
+ return { goalId, message: 'Batch state missing; nothing to release', outcome: 'no_progress' };
+
+ const roster = state.unitTitles ?? [];
+ const released = state.releasedCount ?? state.probeNodeIds.length;
+ const waveSize = Math.max(1, policy.waveSize ?? ROLLOUT_WAVE_SIZE_DEFAULT);
+ const wave = roster.slice(released, released + waveSize);
+
+ if (!wave.length) {
+ await this.goalModel.updateRolloutState(goalId, { ...state, phase: 'done' });
+ return { goalId, message: 'Batch roster exhausted', outcome: 'advanced' };
+ }
+
+ // Advances overlap — two settling tasks can each queue one — and both
+ // would read the same cursor and release the same wave twice. Claim it:
+ // under the goal row's lock, release only if the cursor is still where this
+ // advance read it.
+ const created: GoalAdvanceEffect[] = [];
+ const message = 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 ||
+ current.phase !== state.phase ||
+ current.waveIndex !== state.waveIndex ||
+ (current.releasedCount ?? current.probeNodeIds.length) !== released
+ )
+ return undefined;
+ const writer = new GoalGraphModel(tx, this.userId, this.workspaceId, {
+ id: GOAL_COORDINATOR_ACTOR_ID,
+ type: 'system',
+ });
+
+ const newIds: string[] = [];
+ for (const title of wave) {
+ const nodeId = await createRecipeUnitTask(
+ writer,
+ goalId,
+ state.batchNodeId,
+ title,
+ policy.spec?.recipeOutline,
+ );
+ if (nodeId) {
+ newIds.push(nodeId);
+ created.push({ detail: title, nodeId, type: 'created_node' });
+ }
+ }
+
+ const message = `Batch gate passed; released wave ${state.waveIndex + 1} (${newIds.length} unit${newIds.length === 1 ? '' : 's'})`;
+ // A batch that predates the counter has no `gateLog` either, and a restart
+ // resets `waveIndex`; the roster position still says how many waves are out:
+ // everything released beyond the first canary went out a wave at a time.
+ const waveNumber =
+ (state.wavesReleased ??
+ Math.max(
+ state.waveIndex,
+ (state.gateLog ?? []).filter((entry) => entry.outcome === 'released').length,
+ Math.ceil(Math.max(0, released - (policy.canarySize ?? 0)) / waveSize),
+ )) + 1;
+ const next: GoalRolloutState = withGateVerdict(
+ {
+ ...state,
+ massNodeIds: [...(state.massNodeIds ?? []), ...newIds],
+ phase: 'mass',
+ releasedCount: released + newIds.length,
+ waveIndex: state.waveIndex + 1,
+ wavesReleased: waveNumber,
+ },
+ {
+ checks: gate?.checks ?? [],
+ message,
+ outcome: 'released',
+ releasedCount: newIds.length,
+ revision: state.templateRevision,
+ trigger: 'gate',
+ wave: waveNumber,
+ waveIndex: state.waveIndex + 1,
+ },
+ );
+ // Even the final wave stays `mass`: the gate still judges it once it
+ // settles, and only a pass with the roster exhausted closes the batch.
+ await goalModel.updateRolloutState(goalId, next);
+ return message;
+ });
+
+ if (!message)
+ return {
+ goalId,
+ message: 'Another advance already released this wave',
+ outcome: 'no_progress',
+ };
+ effects.push(...created);
+ return { goalId, message, outcome: 'advanced' };
+ };
+
+ /**
+ * Hand a blocked batch gate to a person.
+ *
+ * The batch cannot advance on its own, so this opens a decision on the Assay
+ * and pauses the goal with the pattern-break reason. The choice is the v3
+ * fork: revise the same recipe (repeat the v1 → v2 loop) or fork a fresh
+ * recipe for the units that broke, inside this batch — never a silent park.
+ */
+ private openPatternBreakGate = async (
+ graph: GoalGraphSnapshot,
+ message: string,
+ effects: GoalAdvanceEffect[],
+ /** What held the batch: the gate's own verdict, or one unit's failed check (R6). */
+ cause: { gate?: RolloutGateResult; unitId?: string } = {},
+ ): Promise<GoalTickResult> => {
+ const goalId = graph.goal.id;
+ const state = graph.goal.config?.rolloutState;
+ if (!state) return { goalId, message, outcome: 'waiting_human' };
+
+ const reason = `${PATTERN_BREAK_PAUSE_REASON}: ${message}`;
+ // Overlapping advances can both see the batch break. Claim it under the
+ // goal row's lock: the first opens the gate — materializing the Assay a
+ // `full` rollout never created — and records it in the same transaction;
+ // the rest find the break already open and reuse its gate instead of
+ // opening a second assay and decision that would re-park the goal later.
+ const claim = await this.db.transaction(async (tx) => {
+ const goalModel = new GoalModel(tx, this.userId, this.workspaceId);
+ const locked = await goalModel.lockById(goalId);
+ const current = locked?.config?.rolloutState;
+ if (!locked || !current) return undefined;
+ if (current.phase === 'pattern_break')
+ return { gateNodeId: current.assayNodeId, opened: false as const };
+ const writer = new GoalGraphModel(tx, this.userId, this.workspaceId, {
+ id: GOAL_COORDINATOR_ACTOR_ID,
+ type: 'system',
+ });
+
+ // The gate hangs on the Assay. A `full` rollout never created one — it
+ // skips the probe gate — but a break still needs a `decision` node for the
+ // human question and, later, for the restart (a `batch` node cannot carry
+ // a decision), so the gate target is stable whichever trigger opened it.
+ let gateNodeId = current.assayNodeId;
+ if (!gateNodeId) {
+ const assay = await writer.createNode(goalId, {
+ description:
+ 'Whether this repeated batch can be delivered without further human decisions.',
+ kind: 'decision',
+ scopeId: current.batchNodeId,
+ status: 'proposed',
+ title: GOAL_BATCH_ASSAY_TITLE,
+ });
+ if (!assay) return undefined;
+ gateNodeId = assay.id;
+ }
+ // The ids are the stable vocabulary; the human-facing labels and their
+ // consequences live in the locale files and are resolved by option id on
+ // the client (like the retry/retire/fail gates), so no English copy is
+ // persisted into a gate a non-English reader has to answer.
+ const decision = await writer.createDecision(goalId, gateNodeId, {
+ authority: 'user',
+ options: [
+ {
+ id: GOAL_BATCH_BREAK_OPTION.revise,
+ label: 'Revise the recipe and re-probe',
+ },
+ {
+ // One batch carries one roster and one gate, so this is not a second
+ // batch running in parallel: it forks the recipe (no `revises`
+ // chain) for the units that broke, inside this same batch.
+ id: GOAL_BATCH_BREAK_OPTION.newClass,
+ label: 'Fork a fresh recipe',
+ },
+ ],
+ question: `${message}\n\n${GOAL_BATCH_BREAK_QUESTION_TAIL}`,
+ requestedUserId: this.userId,
+ });
+ await writer.updateNodeStatus(goalId, gateNodeId, 'waiting', reason);
+ await goalModel.updateRolloutState(
+ goalId,
+ withGateVerdict(
+ { ...current, assayNodeId: gateNodeId, phase: 'pattern_break' },
+ {
+ checks: cause.gate?.checks ?? [],
+ message,
+ nodeId: cause.unitId,
+ outcome: 'blocked',
+ revision: current.templateRevision,
+ trigger: cause.unitId ? 'unit' : 'gate',
+ waveIndex: current.waveIndex,
+ },
+ ),
+ );
+ // Park the goal in the same commit, from the locked row: once the gate is
+ // visible an answer may land at any moment, and a pause written after it
+ // from an older snapshot would re-park a goal the answer just resumed.
+ await goalModel.updatePauseReason(goalId, 'pattern_break');
+ if (locked.status !== 'paused' && !GOAL_ENDED_STATUSES.has(locked.status)) {
+ await goalModel.updateStatus(goalId, 'paused');
+ await writer
+ .recordGoalStatus(goalId, locked.status, 'paused', reason)
+ .catch((error) => console.error('[GoalService] failed to record goal status:', error));
+ }
+ return { decisionId: decision?.id, gateNodeId, opened: true as const };
+ });
+ if (!claim) return { goalId, message, outcome: 'waiting_human' };
+ // Another advance opened this break; it parks the goal.
+ if (!claim.opened)
+ return { goalId, message, nodeId: claim.gateNodeId, outcome: 'waiting_human' };
+ const gateNodeId = claim.gateNodeId;
+ effects.push({
+ detail: message,
+ nodeId: gateNodeId,
+ targetId: claim.decisionId ?? gateNodeId,
+ type: 'opened_decision',
+ });
+ // Home lists what waits on the person from its briefs, so the gate stays
+ // findable after it is dismissed from the approval island. It offers no
+ // one-click answers: revising needs a correction, written on the goal page.
+ if (claim.decisionId)
+ await this.briefs.openDecision(graph.goal, {
+ decisionId: claim.decisionId,
+ options: [],
+ question: `${message}\n\n${GOAL_BATCH_BREAK_QUESTION_TAIL}`,
+ });
+ effects.push({ type: 'goal_status', detail: 'paused: pattern_break' });
+ return { goalId, message, nodeId: gateNodeId, outcome: 'waiting_human' };
+ };
+
+ /**
+ * R5: restart the canary loop after a person intervened on a batch gate.
+ *
+ * The person's answer is the single human judgment; the coordinator opens the
+ * next recipe round from it. `revise` chains a new Template onto the old one
+ * (`revises`); `new_class` forks a fresh Template with no chain edge, still
+ * inside this batch. Either way the members that broke are retired and
+ * re-opened as the new canary, and the rollout returns to the probe phase, so
+ * the class is proved again instead of rerun by hand.
+ *
+ * The correction is the *new recipe*: it is folded into the policy and written
+ * on the Template, so the re-opened probes and every later wave are briefed
+ * from the revised transformation — not from the outline that just failed.
+ */
+ private restartRolloutLoop = async (
+ goalId: string,
+ decisionId: string,
+ optionId: string,
+ resolution: string | undefined,
+ ) => {
+ const graph = await this.requireGraph(goalId);
+ const policy = graph.goal.config?.rollout;
+ const state = graph.goal.config?.rolloutState;
+ if (!policy || !state)
+ return this.graphModel.resolveDecision(goalId, decisionId, optionId, resolution);
+
+ const batchId = state.batchNodeId;
+ const roster = state.unitTitles ?? [];
+ const released = state.releasedCount ?? state.probeNodeIds.length;
+ // The correction the person wrote. A revision carries the plan forward and
+ // appends it as its own section, so each version reads whole and diffs
+ // against the last one; a fork starts again from the original outline. The
+ // result is the new recipe: later waves only ever read
+ // `policy.spec.recipeOutline`, so a note kept solely on the Template would
+ // never reach the tasks meant to test it.
+ const baseOutline = policy.spec?.recipeOutline?.trim() ?? '';
+ const correction = (resolution ?? '').trim();
+ const revision = state.templateRevision + 1;
+ const previousPlan = state.templateNodeId
+ ? graph.nodes.find((node) => node.id === state.templateNodeId)?.description?.trim()
+ : undefined;
+ // A fork starts from the batch's original outline — kept on the batch node,
+ // since every revision rewrites the policy's — not from the revised plan.
+ const originalOutline =
+ graph.nodes.find((node) => node.id === batchId)?.description?.trim() || baseOutline;
+ const basePlan = optionId === 'new_class' ? originalOutline : previousPlan || baseOutline;
+ const revisedOutline = [basePlan, correction && `### v${revision}\n${correction}`]
+ .filter(Boolean)
+ .join('\n\n');
+
+ // The answer and the round it opens land together. Every write below —
+ // resolving the question included — commits in one transaction under the
+ // goal row's lock, so a failure part-way leaves the question open to answer
+ // again rather than consumed beside half a round; and a second answer
+ // racing this one finds the break already restarted.
+ const committed = await this.db.transaction(async (tx) => {
+ const goalModel = new GoalModel(tx, this.userId, this.workspaceId);
+ const current = (await goalModel.lockById(goalId))?.config?.rolloutState;
+ if (current?.phase !== 'pattern_break') return undefined;
+ const resolved = await new GoalGraphModel(tx, this.userId, this.workspaceId).resolveDecision(
+ goalId,
+ decisionId,
+ optionId,
+ resolution,
+ );
+ if (!resolved) return undefined;
+ const writer = new GoalGraphModel(tx, this.userId, this.workspaceId, {
+ id: GOAL_COORDINATOR_ACTOR_ID,
+ type: 'system',
+ });
+
+ // 1. A new recipe revision, or a forked new class (no `revises` chain).
+ const template = await writer.createNode(goalId, {
+ description: revisedOutline || baseOutline,
+ kind: 'finding',
+ scopeId: batchId,
+ title: GOAL_BATCH_TEMPLATE_TITLE,
+ });
+ if (template && optionId !== 'new_class' && state.templateNodeId) {
+ await writer.createEdge(goalId, template.id, state.templateNodeId, 'revises');
+ }
+
+ // 2. Retire the members that broke or were superseded, never delete them —
+ // the new round is `derived_from` them (decision #4). A member an earlier
+ // round already re-opened is history, not a unit to re-open again.
+ const memberIds = new Set([...state.probeNodeIds, ...(state.massNodeIds ?? [])]);
+ const reopenedIds = new Set(
+ graph.edges.filter((edge) => edge.kind === 'derived_from').map((edge) => edge.targetNodeId),
+ );
+ const broken: { brief?: string; id: string; title: string }[] = [];
+ for (const node of graph.nodes) {
+ if (!memberIds.has(node.id) || node.status === 'resolved' || reopenedIds.has(node.id))
+ continue;
+ broken.push({ brief: carriedUnitBrief(node), id: node.id, title: node.title });
+ if (!TERMINAL_NODE_STATUSES.has(node.status)) {
+ await writer.updateNodeStatus(
+ goalId,
+ node.id,
+ 'retired',
+ 'superseded by a new recipe revision',
+ );
+ }
+ }
+
+ // 3. A fresh gate for the fresh round.
+ const assay = await writer.createNode(goalId, {
+ description:
+ 'Whether this repeated batch can be delivered without further human decisions.',
+ kind: 'decision',
+ scopeId: batchId,
+ status: 'proposed',
+ title: GOAL_BATCH_ASSAY_TITLE,
+ });
+ if (!assay) throw new Error('Failed to create the next batch gate');
+
+ // The revised recipe becomes the batch's policy, so the probes below and
+ // every later wave (which read it off the graph) carry the correction.
+ await goalModel.updateRolloutPolicy(goalId, {
+ ...policy,
+ spec: {
+ ...policy.spec,
+ recipeOutline: revisedOutline || baseOutline,
+ repeatable: policy.spec?.repeatable ?? true,
+ },
+ });
+
+ // 4. The new canary re-opens the units that broke, as new tasks that
+ // supersede the retired ones (decision #4: new task + retire, never move).
+ // Cap it at the canary size: a break in a large wave — or a `full` rollout
+ // that released the whole class — must not redispatch every member at once.
+ // The broken units beyond the canary stay owed, and the waves after the gate
+ // re-deliver them under the revised recipe. Only a gate that blocked with
+ // every member resolved has nothing to re-open; it re-probes the next slice.
+ const canarySize = Math.max(
+ 2,
+ Math.min(policy.canarySize ?? ROLLOUT_CANARY_SIZE_DEFAULT, ROLLOUT_MAX_CANARY_SIZE),
+ );
+ const reOpen = broken.slice(0, canarySize);
+ const deferred = broken.slice(canarySize).map((unit) => unit.title);
+ const fresh = broken.length ? [] : roster.slice(released, released + canarySize);
+ // Nothing broke and nothing is left to release — the gate held on something
+ // else, such as an untested axis. Re-probe units this round delivered,
+ // under the revision, so the new canary is never empty (an empty one would
+ // re-open the same break at once).
+ const reProbe =
+ broken.length || fresh.length
+ ? []
+ : [...memberIds]
+ .map((id) => graph.nodes.find((node) => node.id === id))
+ .filter(
+ (node): node is NonNullable<typeof node> =>
+ !!node && node.status === 'resolved' && !reopenedIds.has(node.id),
+ )
+ .slice(0, canarySize)
+ .map((node) => ({ brief: carriedUnitBrief(node), id: node.id, title: node.title }));
+ const units = [
+ ...[...reOpen, ...reProbe].map((unit) => ({
+ brief: unit.brief,
+ from: unit.id,
+ title: unit.title,
+ })),
+ ...fresh.map((title) => ({
+ brief: undefined as string | undefined,
+ from: undefined as string | undefined,
+ title,
+ })),
+ ];
+ const probeIds: string[] = [];
+ const opened: { from: string | undefined; title: string }[] = [];
+ for (const unit of units) {
+ const nodeId = await createRecipeUnitTask(
+ writer,
+ goalId,
+ batchId,
+ unit.title,
+ revisedOutline || baseOutline,
+ unit.brief,
+ );
+ if (!nodeId) continue;
+ probeIds.push(nodeId);
+ opened.push(unit);
+ if (unit.from) {
+ await writer.createEdge(goalId, nodeId, unit.from, 'derived_from').catch(() => {});
+ }
+ }
+ for (const probeId of probeIds) {
+ await writer.createEdge(goalId, assay.id, probeId, 'depends_on');
+ }
+
+ // 5. Back to canary, on the new revision. The roster is re-cut to what is
+ // still owed — the new probes first, then the broken units not re-probed,
+ // then whatever was never released — so the waves deliver only the
+ // remainder and units already delivered under the old recipe drop out.
+ const remaining = Array.from(
+ new Set([
+ ...opened.map((unit) => unit.title),
+ ...deferred,
+ ...roster.slice(released + fresh.length),
+ ]),
+ );
+ await goalModel.updateRolloutState(goalId, {
+ ...state,
+ assayNodeId: assay.id,
+ // The new canary is a fresh round: the old waves' members — the broken
+ // ones now retired — must not count against its gate.
+ massNodeIds: undefined,
+ phase: 'probe',
+ probeNodeIds: probeIds,
+ releasedCount: opened.length,
+ templateNodeId: template?.id ?? state.templateNodeId,
+ templateRevision: state.templateRevision + 1,
+ unitTitles: remaining,
+ waveIndex: 0,
+ });
+ return { brokenIds: broken.map((unit) => unit.id), resolved };
+ });
+ if (!committed) return undefined;
+
+ // A sibling still running when the gate was answered would keep spending —
+ // and could deliver — beside the probe that replaces it. Its node is fenced
+ // as retired above; stop the Task behind it. Not part of the transaction:
+ // stopping a run cannot be rolled back, and retrying it is harmless.
+ if (committed.brokenIds.length)
+ await this.stopFencedTasks(goalId, new Set(committed.brokenIds));
+ await this.setPauseReason(goalId, undefined);
+ return committed.resolved;
+ };
+
private buildTaskAcceptanceRequirement = (
graph: GoalGraphSnapshot,
title: string,
diff --git a/apps/server/src/services/goal/rolloutGate.test.ts b/apps/server/src/services/goal/rolloutGate.test.ts
new file mode 100644
index 00000000000..125a10cfbb9
--- /dev/null
+++ b/apps/server/src/services/goal/rolloutGate.test.ts
@@ -0,0 +1,196 @@
+import type {
+ GoalGraphNode,
+ GoalGraphSnapshot,
+ GoalRolloutPolicy,
+ GoalRolloutState,
+} from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { evaluateRolloutGate, GATE_LOG_PER_ROUND, withGateVerdict } from './rolloutGate';
+
+const node = (id: string, overrides: Partial<GoalGraphNode> = {}): GoalGraphNode =>
+ ({
+ createdAt: new Date(1000),
+ description: id,
+ id,
+ kind: 'task',
+ priority: 0,
+ status: 'resolved',
+ taskId: null,
+ title: id,
+ ...overrides,
+ }) as GoalGraphNode;
+
+const graph = (nodes: GoalGraphNode[]): Pick<GoalGraphSnapshot, 'edges' | 'nodes'> => ({
+ edges: nodes
+ .filter((item) => item.id !== 'batch')
+ .map((item) => ({
+ id: `e-${item.id}`,
+ kind: 'contains',
+ sourceNodeId: 'batch',
+ targetNodeId: item.id,
+ })) as GoalGraphSnapshot['edges'],
+ nodes: [node('batch', { description: 'recipe', kind: 'batch', status: 'active' }), ...nodes],
+});
+
+const state = (overrides: Partial<GoalRolloutState> = {}): GoalRolloutState => ({
+ batchNodeId: 'batch',
+ assayNodeId: 'assay',
+ phase: 'probe',
+ probeNodeIds: ['probe'],
+ releasedCount: 1,
+ templateNodeId: 'template',
+ templateRevision: 1,
+ unitTitles: ['probe', 'rest'],
+ waveIndex: 0,
+ ...overrides,
+});
+
+describe('evaluateRolloutGate', () => {
+ it('passes when the probes settled and the template is complete', () => {
+ const result = evaluateRolloutGate({
+ graph: graph([node('probe'), node('template', { description: 'recipe', kind: 'finding' })]),
+ policy: { trigger: 'canary' },
+ state: state(),
+ });
+ expect(result.met).toBe(true);
+ expect(result.blockers).toEqual([]);
+ // R3: the probe wave alone is provisional, never proof of the class.
+ expect(result.provisional).toBe(true);
+ });
+
+ it('reports every condition it judged, passed or not, with the nodes behind it', () => {
+ const result = evaluateRolloutGate({
+ graph: graph([
+ node('probe', { status: 'rejected' }),
+ node('template', { description: 'recipe', kind: 'finding' }),
+ ]),
+ policy: {
+ spec: { repeatable: true, variantAxes: [{ axis: 'mode', values: ['probe'] }] },
+ trigger: 'canary',
+ },
+ state: state(),
+ });
+ expect(result.checks).toEqual([
+ { count: 1, key: 'units_settled', passed: true, total: 1 },
+ { count: 0, key: 'units_succeeded', nodeIds: ['probe'], passed: false, total: 1 },
+ { key: 'no_open_decision', passed: true },
+ { key: 'plan_written', nodeIds: ['template'], passed: true },
+ { key: 'axes_covered', passed: true },
+ ]);
+ });
+
+ it('is no longer provisional once a later wave has run', () => {
+ const result = evaluateRolloutGate({
+ graph: graph([node('probe'), node('template', { description: 'recipe', kind: 'finding' })]),
+ policy: { trigger: 'canary' },
+ state: state({ waveIndex: 1 }),
+ });
+ expect(result.provisional).toBe(false);
+ });
+
+ it('blocks while a probe has not settled', () => {
+ const result = evaluateRolloutGate({
+ graph: graph([
+ node('probe', { status: 'active' }),
+ node('template', { description: 'recipe', kind: 'finding' }),
+ ]),
+ policy: { trigger: 'canary' },
+ state: state(),
+ });
+ expect(result.met).toBe(false);
+ expect(result.blockers.join(' ')).toContain('have not settled');
+ });
+
+ it('blocks when a probe was rejected — a person must look', () => {
+ const result = evaluateRolloutGate({
+ graph: graph([
+ node('probe', { status: 'rejected' }),
+ node('template', { description: 'recipe', kind: 'finding' }),
+ ]),
+ policy: { trigger: 'canary' },
+ state: state(),
+ });
+ expect(result.met).toBe(false);
+ expect(result.blockers.join(' ')).toContain('did not succeed');
+ });
+
+ it('blocks when the template is incomplete', () => {
+ const result = evaluateRolloutGate({
+ graph: graph([node('probe'), node('template', { description: '', kind: 'finding' })]),
+ policy: { trigger: 'canary' },
+ state: state(),
+ });
+ expect(result.met).toBe(false);
+ expect(result.blockers.join(' ')).toContain('template is incomplete');
+ });
+
+ it('blocks an open human decision inside the batch', () => {
+ const result = evaluateRolloutGate({
+ graph: graph([
+ node('probe'),
+ node('template', { description: 'recipe', kind: 'finding' }),
+ node('assay', { kind: 'decision', status: 'waiting' }),
+ ]),
+ policy: { trigger: 'canary' },
+ state: state(),
+ });
+ expect(result.met).toBe(false);
+ expect(result.blockers.join(' ')).toContain('human decision');
+ });
+
+ it('does not wait on external checks nothing evaluates', () => {
+ // A row persisted with the retired `gate.externalChecks` would otherwise
+ // block every settled wave forever.
+ const policy = {
+ gate: { externalChecks: [{ check: 'ci', title: 'CI green' }] },
+ trigger: 'canary' as const,
+ } as GoalRolloutPolicy;
+ const result = evaluateRolloutGate({
+ graph: graph([node('probe'), node('template', { description: 'recipe', kind: 'finding' })]),
+ policy,
+ state: state(),
+ });
+ expect(result.met).toBe(true);
+ });
+
+ it('blocks an untested variant axis (R4)', () => {
+ const result = evaluateRolloutGate({
+ graph: graph([
+ node('probe', { description: 'no cold start here', title: 'probe' }),
+ node('template', { description: 'recipe', kind: 'finding' }),
+ ]),
+ policy: {
+ spec: { repeatable: true, variantAxes: [{ axis: 'cold-start', values: ['yes'] }] },
+ trigger: 'canary',
+ },
+ state: state(),
+ });
+ expect(result.met).toBe(false);
+ expect(result.blockers.join(' ')).toContain('untested axes');
+ });
+});
+
+describe('withGateVerdict', () => {
+ const verdict = (revision: number) => ({
+ checks: [],
+ outcome: 'blocked' as const,
+ revision,
+ trigger: 'gate' as const,
+ waveIndex: 0,
+ });
+
+ it("keeps each round's latest verdicts, however busy a later round is", () => {
+ let next = withGateVerdict(state(), verdict(1));
+ for (let i = 0; i < GATE_LOG_PER_ROUND + 5; i++) next = withGateVerdict(next, verdict(2));
+ expect(next.gateLog!.filter((item) => item.revision === 1)).toHaveLength(1);
+ expect(next.gateLog!.filter((item) => item.revision === 2)).toHaveLength(GATE_LOG_PER_ROUND);
+ });
+
+ it('numbers verdicts within their round and keeps counting after older ones drop', () => {
+ let next = state();
+ for (let i = 0; i < GATE_LOG_PER_ROUND + 5; i++) next = withGateVerdict(next, verdict(1));
+ expect(next.gateLog!.at(-1)!.seq).toBe(GATE_LOG_PER_ROUND + 5);
+ expect(withGateVerdict(next, verdict(2)).gateLog!.at(-1)!.seq).toBe(1);
+ });
+});
diff --git a/apps/server/src/services/goal/rolloutGate.ts b/apps/server/src/services/goal/rolloutGate.ts
new file mode 100644
index 00000000000..76fdcd03cf9
--- /dev/null
+++ b/apps/server/src/services/goal/rolloutGate.ts
@@ -0,0 +1,166 @@
+import type {
+ GoalGraphNode,
+ GoalGraphSnapshot,
+ GoalRolloutGateCheck,
+ GoalRolloutGateEvaluation,
+ GoalRolloutPolicy,
+ GoalRolloutState,
+} from '@lobechat/types';
+import { experimentMembers } from '@lobechat/utils/goalGraph';
+
+import { uncoveredAxisValues } from './spec';
+
+/** Node states that mean a unit will never produce again. */
+const TERMINAL_NODE_STATUSES = new Set(['resolved', 'rejected', 'retired']);
+
+export interface RolloutGateInput {
+ graph: Pick<GoalGraphSnapshot, 'edges' | 'nodes'>;
+ policy: GoalRolloutPolicy;
+ state: GoalRolloutState;
+}
+
+export interface RolloutGateResult {
+ /** Reasons that keep the gate from passing; empty when `met` is true. */
+ blockers: string[];
+ /** Every condition judged, passed or not — what the gate log records. */
+ checks: GoalRolloutGateCheck[];
+ met: boolean;
+ /**
+ * R3: true while the class-wide green still rests on the probe wave alone. The
+ * probe wave distilled the Template from its own result, so it cannot be the
+ * proof; a later, different wave must also run without a human before the
+ * batch is fully trusted. Recorded rather than used to block, so wave 1 is not
+ * deadlocked behind its own absence.
+ */
+ provisional: boolean;
+}
+
+const asBrief = (node: GoalGraphNode) => ({
+ instruction: node.description ?? '',
+ title: node.title,
+});
+
+/**
+ * Whether a repeated batch has earned its next wave.
+ *
+ * Pure, so the judgment can be replayed and tested like the rest of
+ * `decideNextMove`. Four conditions, all of which must hold:
+ *
+ * 1. every probe settled without a person (no rejected / retired probe);
+ * 2. no human decision is open anywhere in the batch;
+ * 3. the Template is complete enough to apply (a recipe outline exists);
+ * 4. every declared variant axis value is represented among the probes (R4).
+ *
+ * An external anchor (real CI, a real remote merge) is not judged here yet:
+ * nothing evaluates such a check, and a declared one could only ever block.
+ */
+export const evaluateRolloutGate = ({
+ graph,
+ policy,
+ state,
+}: RolloutGateInput): RolloutGateResult => {
+ const checks: GoalRolloutGateCheck[] = [];
+ const blockers: string[] = [];
+ const members = experimentMembers(graph, state.batchNodeId);
+ const probeNodes = graph.nodes.filter((node) => state.probeNodeIds.includes(node.id));
+ // R6 (per-item check): every released member — probe or mass — ends with a
+ // check, so a rejection anywhere in the batch breaks it, not only a rejected
+ // probe. Only the CURRENT round's members decide this gate: a member the
+ // coordinator retired when re-opening the round (R5) is history, not a live
+ // failure, and must not keep blocking the new canary.
+ const roundIds = new Set([...state.probeNodeIds, ...(state.massNodeIds ?? [])]);
+ const memberTaskNodes = graph.nodes.filter(
+ (node) => roundIds.has(node.id) && node.kind === 'task',
+ );
+ const total = memberTaskNodes.length;
+
+ const unsettled = memberTaskNodes.filter((node) => !TERMINAL_NODE_STATUSES.has(node.status));
+ checks.push({
+ count: total - unsettled.length,
+ key: 'units_settled',
+ nodeIds: unsettled.length ? unsettled.map((node) => node.id) : undefined,
+ passed: unsettled.length === 0,
+ total,
+ });
+ if (unsettled.length) blockers.push(`${unsettled.length} unit(s) have not settled`);
+
+ const broken = memberTaskNodes.filter(
+ (node) => node.status === 'rejected' || node.status === 'retired',
+ );
+ checks.push({
+ count: total - broken.length,
+ key: 'units_succeeded',
+ nodeIds: broken.length ? broken.map((node) => node.id) : undefined,
+ passed: broken.length === 0,
+ total,
+ });
+ if (broken.length) blockers.push(`${broken.length} unit(s) did not succeed`);
+
+ const openDecision = graph.nodes.find(
+ (node) => members.has(node.id) && node.kind === 'decision' && node.status === 'waiting',
+ );
+ checks.push({
+ key: 'no_open_decision',
+ nodeIds: openDecision ? [openDecision.id] : undefined,
+ passed: !openDecision,
+ });
+ if (openDecision) blockers.push('a human decision is still open in this batch');
+
+ const template = state.templateNodeId
+ ? graph.nodes.find((node) => node.id === state.templateNodeId)
+ : undefined;
+ const planWritten = !!template?.description?.trim();
+ checks.push({
+ key: 'plan_written',
+ nodeIds: template ? [template.id] : undefined,
+ passed: planWritten,
+ });
+ if (!planWritten) blockers.push('the batch template is incomplete');
+
+ if (policy.spec?.variantAxes?.length) {
+ const gaps = uncoveredAxisValues(policy.spec.variantAxes, probeNodes.map(asBrief));
+ checks.push({
+ details: gaps.length ? gaps.map((gap) => `${gap.axis}=${gap.value}`) : undefined,
+ key: 'axes_covered',
+ passed: gaps.length === 0,
+ });
+ if (gaps.length) {
+ blockers.push(`untested axes: ${gaps.map((gap) => `${gap.axis}=${gap.value}`).join(', ')}`);
+ }
+ }
+
+ return {
+ blockers,
+ checks,
+ met: blockers.length === 0,
+ provisional: blockers.length === 0 && state.waveIndex === 0,
+ };
+};
+
+/**
+ * How many gate verdicts each round keeps. Per round, not overall: a busy later
+ * round must never push an earlier round's latest verdict out of the record.
+ */
+export const GATE_LOG_PER_ROUND = 10;
+
+/** Append one gate verdict to the batch's own record of them. */
+export const withGateVerdict = (
+ state: GoalRolloutState,
+ entry: Omit<GoalRolloutGateEvaluation, 'at' | 'seq'>,
+): GoalRolloutState => {
+ const log = state.gateLog ?? [];
+ // The round's latest verdict is always kept, so its ordinal continues from it.
+ const previous = log.findLast((item) => item.revision === entry.revision);
+ const seq = (previous?.seq ?? log.filter((item) => item.revision === entry.revision).length) + 1;
+ const appended = [...log, { ...entry, at: new Date().toISOString(), seq }];
+ const kept = new Map<number, number>();
+ const gateLog = appended
+ .toReversed()
+ .filter((item) => {
+ const count = kept.get(item.revision) ?? 0;
+ kept.set(item.revision, count + 1);
+ return count < GATE_LOG_PER_ROUND;
+ })
+ .toReversed();
+ return { ...state, gateLog };
+};
diff --git a/apps/server/src/services/goal/spec.test.ts b/apps/server/src/services/goal/spec.test.ts
new file mode 100644
index 00000000000..7166f29c40f
--- /dev/null
+++ b/apps/server/src/services/goal/spec.test.ts
@@ -0,0 +1,122 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ evaluateHomogeneity,
+ HOMOGENEITY_MIN_SIMILARITY,
+ maskConcreteNames,
+ minPairwiseSimilarity,
+ uncoveredAxisValues,
+} from './spec';
+
+describe('maskConcreteNames', () => {
+ it('masks paths, identifiers and numbers so one recipe reads the same twice', () => {
+ const a = maskConcreteNames('Migrate src/store/userStore.ts using the same 3 steps');
+ const b = maskConcreteNames('Migrate src/store/topicStore.ts using the same 3 steps');
+ expect(a).toBe(b);
+ });
+});
+
+describe('minPairwiseSimilarity', () => {
+ it('is 1 for briefs that are one masked shape', () => {
+ const similarity = minPairwiseSimilarity([
+ { instruction: 'Move src/a.ts to the new API', title: 'Migrate A' },
+ { instruction: 'Move src/b.ts to the new API', title: 'Migrate B' },
+ ]);
+ expect(similarity).toBeGreaterThanOrEqual(HOMOGENEITY_MIN_SIMILARITY);
+ });
+
+ it('falls below the threshold for unrelated briefs', () => {
+ const similarity = minPairwiseSimilarity([
+ { instruction: 'Write a benchmark paper', title: 'Paper' },
+ { instruction: 'Provision a Postgres cluster', title: 'Infra' },
+ ]);
+ expect(similarity).toBeLessThan(HOMOGENEITY_MIN_SIMILARITY);
+ });
+});
+
+describe('evaluateHomogeneity', () => {
+ const spec = {
+ recipeOutline: 'Replace the store with the replica-backed one',
+ repeatable: true,
+ unitCount: 50,
+ units: Array.from({ length: 50 }, (_, i) => `Migrate ${i + 1}`),
+ variants: [],
+ };
+ const probes = [
+ { instruction: 'Migrate src/a.ts the same way', title: 'Migrate A' },
+ { instruction: 'Migrate src/b.ts the same way', title: 'Migrate B' },
+ ];
+
+ it('accepts one repeated mould above the threshold', () => {
+ expect(evaluateHomogeneity(spec, probes).batch).toBe(true);
+ });
+
+ it('accepts a roster within the caller’s batch cap', () => {
+ expect(evaluateHomogeneity(spec, probes, { maxUnits: 60 }).batch).toBe(true);
+ });
+
+ it('refuses a roster above the batch cap so nothing is silently trimmed', () => {
+ const verdict = evaluateHomogeneity(
+ { ...spec, unitCount: 65, units: Array.from({ length: 65 }, (_, i) => `Migrate ${i + 1}`) },
+ probes,
+ { maxUnits: 60 },
+ );
+ expect(verdict.batch).toBe(false);
+ expect(verdict.reasons.join(' ')).toContain('above the batch cap of 60');
+ });
+
+ it('refuses a claim that is not repeatable', () => {
+ expect(evaluateHomogeneity({ ...spec, repeatable: false }, probes).batch).toBe(false);
+ });
+
+ it('refuses a roster below the homogeneous-unit threshold', () => {
+ expect(evaluateHomogeneity({ ...spec, unitCount: 2 }, probes).batch).toBe(false);
+ });
+
+ it('refuses probes that are not one mould', () => {
+ const verdict = evaluateHomogeneity(spec, [
+ { instruction: 'Write a benchmark paper', title: 'Paper' },
+ { instruction: 'Provision a Postgres cluster', title: 'Infra' },
+ ]);
+ expect(verdict.batch).toBe(false);
+ expect(verdict.reasons.join(' ')).toContain('one reusable transformation');
+ });
+
+ it('refuses a claim whose roster does not list every claimed unit', () => {
+ const verdict = evaluateHomogeneity({ ...spec, units: ['Migrate 1', 'Migrate 2'] }, probes);
+ expect(verdict.batch).toBe(false);
+ expect(verdict.reasons.join(' ')).toContain('roster lists 4 of the 50 claimed units');
+ });
+
+ it('refuses a claim with no recipe outline', () => {
+ expect(evaluateHomogeneity({ ...spec, recipeOutline: undefined }, probes).batch).toBe(false);
+ });
+});
+
+describe('uncoveredAxisValues', () => {
+ it('reports a declared value no probe touches', () => {
+ const gaps = uncoveredAxisValues(
+ [{ axis: 'cold-start', values: ['yes', 'no'] }],
+ [{ instruction: 'Handle a cold-start yes path', title: 'Probe' }],
+ );
+ expect(gaps).toEqual([{ axis: 'cold-start', value: 'no' }]);
+ });
+
+ it('reports nothing when every value is covered', () => {
+ const gaps = uncoveredAxisValues(
+ [{ axis: 'mode', values: ['cold-start'] }],
+ [{ instruction: 'Handle a cold-start path', title: 'Probe' }],
+ );
+ expect(gaps).toEqual([]);
+ });
+
+ it('does not let an unrelated word satisfy a short variant value', () => {
+ // `no` must not be covered by `node` / `nothing` — otherwise an all-`yes`
+ // probe set would green the gate without ever testing the `no` variant.
+ const gaps = uncoveredAxisValues(
+ [{ axis: 'cold-start', values: ['no'] }],
+ [{ instruction: 'Handle a node route with nothing cold', title: 'Probe' }],
+ );
+ expect(gaps).toEqual([{ axis: 'cold-start', value: 'no' }]);
+ });
+});
diff --git a/apps/server/src/services/goal/spec.ts b/apps/server/src/services/goal/spec.ts
new file mode 100644
index 00000000000..21ca1976023
--- /dev/null
+++ b/apps/server/src/services/goal/spec.ts
@@ -0,0 +1,182 @@
+import { ROLLOUT_MIN_HOMOGENEOUS_UNITS } from '@lobechat/const/goal';
+import type { GoalRolloutVariantAxis } from '@lobechat/types';
+
+/**
+ * The planner's batch claim, already parsed.
+ *
+ * This is the **S** of STAMP: the specification that decides whether a goal is
+ * one repeated mould. A claim alone never creates a batch — the coordinator
+ * validates it here first, so a planner that over-claims still decomposes one
+ * unit per task as it always did.
+ */
+export interface BatchSpecDraft {
+ recipeOutline?: string;
+ repeatable: boolean;
+ /** Honest count of the homogeneous units in the whole goal. */
+ unitCount: number;
+ /** Roster of every homogeneous unit; probes come first, in delivery order. */
+ units?: string[];
+ variants?: GoalRolloutVariantAxis[];
+}
+
+/** A single probe brief, only the fields homogeneity is judged on. */
+export interface ProbeBrief {
+ instruction: string;
+ title: string;
+}
+
+export interface HomogeneityVerdict {
+ batch: boolean;
+ /** Why it failed; empty when `batch` is true. Kept for the trace and tests. */
+ reasons: string[];
+}
+
+/**
+ * R2's executable core, restated as code: "replace the concrete file / module /
+ * symbol names with placeholders — are the transformation steps still the same?"
+ *
+ * The masking is deliberately crude and deterministic. It is not trying to
+ * understand the prose; it removes the parts that make two applications of one
+ * recipe *look* different (paths, identifiers, numbers, and inline code), so
+ * what is left can be compared. A false negative here only costs the batch
+ * ceremony — the goal decomposes normally — which is the safe direction.
+ */
+export const maskConcreteNames = (text: string): string =>
+ text
+ .replaceAll(/`[^`]*`/g, ' <code> ')
+ // POSIX / URL-ish paths and dotted module specifiers.
+ .replaceAll(/\b[\w.@-]*(?:\/[\w.@-]+)+\b/g, ' <path> ')
+ // camelCase / PascalCase / SCREAMING_CASE symbols. The character classes
+ // after each capital are lowercase/digit/underscore only, so the repeated
+ // group cannot match the same text two ways (no super-linear backtracking).
+ .replaceAll(/\b[a-z][a-z0-9_$]*(?:[A-Z][a-z0-9_$]*)+\b/g, ' <ident> ')
+ .replaceAll(/\b(?:[A-Z][a-z0-9_$]*){2,}\b/g, ' <ident> ')
+ .replaceAll(/\b[A-Z][A-Z0-9_]{2,}\b/g, ' <ident> ')
+ // Bare numbers (counts, indices, thresholds).
+ .replaceAll(/\b\d+(?:\.\d+)?\b/g, ' <n> ')
+ .toLowerCase()
+ .replaceAll(/\s+/g, ' ')
+ .trim();
+
+const tokensOf = (text: string): Set<string> =>
+ new Set(
+ maskConcreteNames(text)
+ .split(/[^\p{L}\p{N}<>]+/u)
+ .filter((token) => token.length > 1),
+ );
+
+const jaccard = (a: Set<string>, b: Set<string>): number => {
+ if (a.size === 0 && b.size === 0) return 1;
+ let intersection = 0;
+ for (const token of a) if (b.has(token)) intersection += 1;
+ return intersection / (a.size + b.size - intersection);
+};
+
+/** Lowest pairwise Jaccard similarity across every pair of probe shapes. */
+export const minPairwiseSimilarity = (briefs: ProbeBrief[]): number => {
+ if (briefs.length < 2) return 1;
+ const shapes = briefs.map((brief) => tokensOf(`${brief.title}\n${brief.instruction}`));
+ let min = 1;
+ for (let i = 0; i < shapes.length; i += 1) {
+ for (let j = i + 1; j < shapes.length; j += 1) {
+ min = Math.min(min, jaccard(shapes[i], shapes[j]));
+ }
+ }
+ return min;
+};
+
+/**
+ * Below this the probe briefs are describing different work, not one recipe
+ * applied to different units.
+ */
+export const HOMOGENEITY_MIN_SIMILARITY = 0.5;
+
+const escapeRegExp = (value: string): string => value.replaceAll(/[.*+?^${}()|[\]\\]/g, '\\$&');
+
+/**
+ * Whether a declared axis value is represented in the probe text.
+ *
+ * A Latin/alphanumeric value must appear on a word boundary, so a value like
+ * `no` is not counted as covered by the word `node` or `not` — otherwise an
+ * all-`yes` probe set would silently satisfy the `no` variant and the gate would
+ * release the mass rollout without ever testing it. Values in scripts without
+ * word boundaries (e.g. CJK) keep substring matching, where boundaries have no
+ * meaning.
+ */
+export const containsAxisValue = (haystack: string, value: string): boolean => {
+ const needle = value.trim().toLowerCase();
+ if (!needle) return false;
+ const text = haystack.toLowerCase();
+ if (!/^[\p{Script=Latin}\p{N} _-]+$/u.test(needle)) return text.includes(needle);
+ return new RegExp(`(^|[^\\p{L}\\p{N}])${escapeRegExp(needle)}([^\\p{L}\\p{N}]|$)`, 'u').test(
+ text,
+ );
+};
+
+/**
+ * R4's coverage check: axes the planner declared, and the values on them that
+ * no probe touches. A declared value with zero coverage is the half the probe
+ * missed, and the gate must not read green until it is seen — so this is a
+ * gate blocker, not a reason to refuse creating the batch.
+ */
+export const uncoveredAxisValues = (
+ axes: GoalRolloutVariantAxis[] | undefined,
+ briefs: ProbeBrief[],
+): Array<{ axis: string; value: string }> => {
+ if (!axes?.length) return [];
+ const haystack = briefs.map((brief) => `${brief.title}\n${brief.instruction}`).join('\n');
+ const uncovered: Array<{ axis: string; value: string }> = [];
+ for (const axis of axes) {
+ for (const value of axis.values) {
+ if (!containsAxisValue(haystack, value)) uncovered.push({ axis: axis.axis, value });
+ }
+ }
+ return uncovered;
+};
+
+/**
+ * Validate the planner's batch claim before decomposition acts on it.
+ *
+ * Every condition must hold: the planner marked it repeatable, named the one
+ * reusable transformation, counted at least the threshold of homogeneous units,
+ * listed every one of them in the roster, listed more than one probe, and the
+ * probes really read as one mould after masking. Any failure keeps the ordinary
+ * one-unit-per-task decomposition and records why.
+ *
+ * `maxUnits` is the batch roster's ceiling (the caller's config bound). A claim
+ * above it is refused here rather than batched, so the roster a batch carries is
+ * always the whole one: the coordinator waves it out unit by unit, and a cap
+ * applied at creation would silently leave the tail undelivered. The refused
+ * claim falls back to the ordinary decomposition, which materializes every unit
+ * the planner listed.
+ */
+export const evaluateHomogeneity = (
+ spec: BatchSpecDraft,
+ briefs: ProbeBrief[],
+ options: { maxUnits?: number; minUnits?: number } = {},
+): HomogeneityVerdict => {
+ const minUnits = options.minUnits ?? ROLLOUT_MIN_HOMOGENEOUS_UNITS;
+ const reasons: string[] = [];
+
+ if (!spec.repeatable) reasons.push('planner did not mark the goal repeatable');
+ if (!spec.recipeOutline?.trim()) reasons.push('no reusable recipe outline');
+ if (!Number.isFinite(spec.unitCount) || spec.unitCount < minUnits)
+ reasons.push(`unitCount ${spec.unitCount} is below the threshold ${minUnits}`);
+ // The roster is what the waves deliver: a claim the roster cannot account for
+ // would exhaust it early and silently drop every unit it left out.
+ const roster = new Set(
+ [...briefs.map((brief) => brief.title), ...(spec.units ?? [])]
+ .map((title) => title.trim())
+ .filter(Boolean),
+ );
+ if (Number.isFinite(spec.unitCount) && roster.size < spec.unitCount)
+ reasons.push(`roster lists ${roster.size} of the ${spec.unitCount} claimed units`);
+ if (options.maxUnits !== undefined && roster.size > options.maxUnits)
+ reasons.push(`roster lists ${roster.size} units, above the batch cap of ${options.maxUnits}`);
+ if (briefs.length < 2) reasons.push('fewer than two probe units');
+
+ if (briefs.length >= 2 && minPairwiseSimilarity(briefs) < HOMOGENEITY_MIN_SIMILARITY)
+ reasons.push('probe briefs do not describe one reusable transformation');
+
+ return { batch: reasons.length === 0, reasons };
+};
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 68438394326..c43471ab842 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -447,6 +447,89 @@
"goalAcceptance.removeConfirm.content": "\"{{title}}\" will no longer gate this goal’s final acceptance.",
"goalAcceptance.removeConfirm.title": "Remove this criterion?",
"goalAcceptance.title": "Acceptance standard",
+ "goalBatch.cell.backlog": "Not run",
+ "goalBatch.cell.done": "Done",
+ "goalBatch.cell.human": "Needs you",
+ "goalBatch.cell.reopened": "Reopened in v{{revision}}",
+ "goalBatch.cell.runIn": "Runs in v{{revision}}",
+ "goalBatch.cell.running": "Running",
+ "goalBatch.cell.stale": "Superseded",
+ "goalBatch.cell.tooltip": "Wave {{wave}} · item {{index}} · {{title}} · {{state}}",
+ "goalBatch.enter": "Open",
+ "goalBatch.gate.checkCount": "{{count}} checks",
+ "goalBatch.gate.hintTitle": "Checked before the rest are released:",
+ "goalBatch.gate.status.checking": "Judging",
+ "goalBatch.gate.status.human": "Needs your decision",
+ "goalBatch.gate.status.locked": "Not judged",
+ "goalBatch.gate.status.passed": "Passed",
+ "goalBatch.gate.status.rejected": "Sent back",
+ "goalBatch.gate.title": "Release gate",
+ "goalBatch.gate.titleRound": "Release gate · v{{revision}}",
+ "goalBatch.gateCheck.axes_covered": "The trials covered every declared variant",
+ "goalBatch.gateCheck.count": "{{count}} / {{total}}",
+ "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.units_settled": "Every unit this round finished",
+ "goalBatch.gateCheck.units_succeeded": "Every unit this round ran through on its own — none failed or was sent back",
+ "goalBatch.gatePanel.checks": "Checks",
+ "goalBatch.gatePanel.checksAt": "Verdict {{index}} · {{time}}",
+ "goalBatch.gatePanel.checksPlanned": "Not judged yet — these will be checked",
+ "goalBatch.gatePanel.history": "Verdicts",
+ "goalBatch.gatePanel.history.blocked": "Held: {{checks}}",
+ "goalBatch.gatePanel.history.empty": "No verdict yet",
+ "goalBatch.gatePanel.history.released": "Released wave {{wave}} ({{count}} units)",
+ "goalBatch.gatePanel.history.unit": "“{{title}}” failed its own check — the batch was held at once",
+ "goalBatch.gatePanel.history.unrecorded": "Judged before verdicts were recorded — no detail kept",
+ "goalBatch.gatePanel.next.checking": "Every unit finished — judged on the coordinator’s next step",
+ "goalBatch.gatePanel.next.human": "Waiting on you: revise the plan, or fork a fresh one for the units that broke",
+ "goalBatch.gatePanel.next.locked": "Judged automatically once this round’s {{count}} units finish",
+ "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.rejected": "Reopened as v{{revision}} on your decision",
+ "goalBatch.gatePanel.question": "Revise the plan and re-probe, or fork a fresh one for the units that broke?",
+ "goalBatch.gatePanel.verdict": "Verdict",
+ "goalBatch.overviewCount": "Total: {{count}} batches · {{nodes}} nodes",
+ "goalBatch.planPanel.compare": "Compare with",
+ "goalBatch.planPanel.diff": "What changed from v{{base}} to v{{revision}}",
+ "goalBatch.planPanel.first": "The first version — nothing earlier to compare with",
+ "goalBatch.planPanel.forked": "A forked plan: it starts again from the batch’s original outline instead of revising the previous version",
+ "goalBatch.planPanel.full": "v{{revision}} in full",
+ "goalBatch.planPanel.same": "Same as v{{base}}",
+ "goalBatch.planPanel.version": "Version",
+ "goalBatch.probes.cell.backlog": "Not started",
+ "goalBatch.probes.cell.done": "Done",
+ "goalBatch.probes.cell.human": "Needs you",
+ "goalBatch.probes.cell.running": "In progress",
+ "goalBatch.probes.cell.stale": "Superseded",
+ "goalBatch.probes.hint": "{{count}} representative units run first — the most different ones and the hardest. The rest are released only once every one of them runs through automatically.",
+ "goalBatch.probes.rowLabel": "Trials",
+ "goalBatch.probes.status.done": "Trials done",
+ "goalBatch.probes.status.pending": "Not started",
+ "goalBatch.probes.status.running": "Trials running",
+ "goalBatch.probes.title": "Cold start · trials",
+ "goalBatch.redispatch.foot": "{{count}} units · on v{{revision}}",
+ "goalBatch.redispatch.fromProbe": "Reopened from trial {{index}}",
+ "goalBatch.redispatch.fromRound": "Reopened from v{{revision}}",
+ "goalBatch.redispatch.fromWave": "Reopened from wave {{wave}}, item {{index}}",
+ "goalBatch.redispatch.labelRound": "v{{revision}}",
+ "goalBatch.redispatch.reopenedRow": "Reopened",
+ "goalBatch.redispatch.title": "Waves · v{{revision}}",
+ "goalBatch.round.foot": "{{count}} units",
+ "goalBatch.round.reviseEdge": "Sent back · revise",
+ "goalBatch.round.title": "Round {{revision}}",
+ "goalBatch.status.done": "All done",
+ "goalBatch.status.human": "{{count}} need you",
+ "goalBatch.status.pending": "Not started",
+ "goalBatch.status.running": "In progress",
+ "goalBatch.status.stale": "{{count}} superseded",
+ "goalBatch.template.forked": "Plan v{{revision}} · new class",
+ "goalBatch.template.title": "Plan v{{revision}}",
+ "goalBatch.templatePlain": "Batch plan",
+ "goalBatch.title": "Repeated batch",
+ "goalBatch.waves.foot": "{{count}} units / {{waves}} waves",
+ "goalBatch.waves.row": "W{{number}}",
+ "goalBatch.waves.title": "Waves",
"goalChat.newTopic": "New conversation",
"goalChat.noTopics": "No conversations yet",
"goalChat.title": "Ask about progress",
@@ -662,9 +745,11 @@
"goalProcess.decision.effect.abandonAcceptance": "Stop acceptance and end the goal without a verdict.",
"goalProcess.decision.effect.fail": "End the goal and record it as failed.",
"goalProcess.decision.effect.fixedRetry": "Run the task again once the setup is fixed.",
+ "goalProcess.decision.effect.newClassBatch": "Fork a fresh recipe for the units that broke; the rest of the batch continues once the new gate passes.",
"goalProcess.decision.effect.retire": "Drop this task. The goal moves on without it.",
"goalProcess.decision.effect.retry": "Send the task back for another attempt. Your note is written into its instructions.",
"goalProcess.decision.effect.retryAcceptance": "Run the goal-level acceptance again.",
+ "goalProcess.decision.effect.reviseBatch": "Revise the recipe from this failure, then re-probe this batch.",
"goalProcess.decision.submit": "Decide",
"goalProcess.decision.summary.agentQuestion": "While working on the goal, the main Agent hit a call only you can make. It lays out the options and its recommendation below.",
"goalProcess.decision.summary.goalAcceptance": "The goal-level acceptance did not pass. Decide whether to run it again, abandon it, or record the goal as failed.",
@@ -697,15 +782,24 @@
"goalProcess.frontier.emptyTitle": "Nothing to advance right now",
"goalProcess.frontier.needsYou": "{{count}} need you",
"goalProcess.frontier.title": "Current tasks",
+ "goalProcess.gate.batchCorrectionPlaceholder": "What to change in the recipe — required to revise it; it becomes the next version",
+ "goalProcess.gate.batchCorrectionRequired": "Write the correction before revising the recipe",
"goalProcess.gate.decisionPointLabel": "What needs your decision",
"goalProcess.gate.noteLabel": "Extra guidance",
"goalProcess.gate.notePlaceholder": "Optional — goes into the next attempt instructions",
"goalProcess.gate.option.assume": "Go with the assumption",
"goalProcess.gate.option.fail": "Fail goal",
"goalProcess.gate.option.fixedRetry": "I fixed it — retry",
+ "goalProcess.gate.option.newClassBatch": "Fork a fresh recipe",
"goalProcess.gate.option.retire": "Retire work",
"goalProcess.gate.option.retry": "Retry work",
+ "goalProcess.gate.option.reviseBatch": "Revise the recipe and re-probe",
"goalProcess.gate.reason.attemptBudgetExhausted": "The attempt budget for this work is used up",
+ "goalProcess.gate.reason.batchBroken": "{{count}} unit(s) did not succeed",
+ "goalProcess.gate.reason.batchOpenDecision": "a human decision is still open in this batch",
+ "goalProcess.gate.reason.batchTemplateIncomplete": "the batch template is incomplete",
+ "goalProcess.gate.reason.batchUnsettled": "{{count}} unit(s) have not settled",
+ "goalProcess.gate.reason.batchUntestedAxes": "untested axes: {{axes}}",
"goalProcess.gate.reason.costBudgetExhausted": "The goal cost budget is used up",
"goalProcess.gate.reason.deviceStayedOffline": "The device this task runs on stayed offline through every automatic retry",
"goalProcess.gate.reason.goalAcceptanceFailed": "Goal-level acceptance did not pass",
@@ -723,6 +817,7 @@
"goalProcess.gate.reason.verifyInternalError": "Verification could not run (internal error); this delivery was not evaluated",
"goalProcess.gate.recommended": "recommended",
"goalProcess.gate.title.agentQuestion": "Answer the main Agent's question",
+ "goalProcess.gate.title.batchPatternBreak": "Decide how the failed batch proceeds",
"goalProcess.gate.title.clarifyGoal": "Clarify the goal before work starts",
"goalProcess.gate.title.fixSetup": "Fix the setup, then retry",
"goalProcess.gate.title.goalAcceptance": "Decide the goal acceptance outcome",
@@ -738,6 +833,7 @@
"goalProcess.graph.title": "Exploration map",
"goalProcess.graph.view.all": "Full map",
"goalProcess.graph.view.stage": "Current stage",
+ "goalProcess.kind.batch": "Batch",
"goalProcess.kind.decision": "Decision",
"goalProcess.kind.experiment": "Experiment",
"goalProcess.kind.finding": "Finding",
@@ -763,6 +859,7 @@
"goalProcess.lifecycle.action.work.input": "used as input",
"goalProcess.lifecycle.action.work.produced": "produced",
"goalProcess.lifecycle.action.work.supports": "added evidence",
+ "goalProcess.lifecycle.kind.batch": "batch",
"goalProcess.lifecycle.kind.decision": "decision",
"goalProcess.lifecycle.kind.experiment": "experiment",
"goalProcess.lifecycle.kind.finding": "finding",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 437a04cfb0b..68641e03a46 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -447,6 +447,89 @@
"goalAcceptance.removeConfirm.content": "“{{title}}” 将不再作为此目标最终接受的门槛。",
"goalAcceptance.removeConfirm.title": "移除这条标准?",
"goalAcceptance.title": "验收标准",
+ "goalBatch.cell.backlog": "暂未执行",
+ "goalBatch.cell.done": "执行完成",
+ "goalBatch.cell.human": "需要介入",
+ "goalBatch.cell.reopened": "已在 v{{revision}} 重开",
+ "goalBatch.cell.runIn": "在 v{{revision}} 中执行",
+ "goalBatch.cell.running": "执行中",
+ "goalBatch.cell.stale": "已废弃",
+ "goalBatch.cell.tooltip": "第 {{wave}} 批 · 第 {{index}} 项 · {{title}} · {{state}}",
+ "goalBatch.enter": "进入",
+ "goalBatch.gate.checkCount": "{{count}} 项检查",
+ "goalBatch.gate.hintTitle": "放行其余单元前逐项检查:",
+ "goalBatch.gate.status.checking": "判定中",
+ "goalBatch.gate.status.human": "需要你决定",
+ "goalBatch.gate.status.locked": "未判定",
+ "goalBatch.gate.status.passed": "已通过",
+ "goalBatch.gate.status.rejected": "已打回",
+ "goalBatch.gate.title": "放行闸门",
+ "goalBatch.gate.titleRound": "放行闸门 · v{{revision}}",
+ "goalBatch.gateCheck.axes_covered": "实验覆盖了每个变体取值",
+ "goalBatch.gateCheck.count": "{{count}} / {{total}}",
+ "goalBatch.gateCheck.no_open_decision": "批次内没有等人决定的事项",
+ "goalBatch.gateCheck.plan_written": "执行方案已成稿",
+ "goalBatch.gateCheck.uncovered": "未覆盖:{{values}}",
+ "goalBatch.gateCheck.units_settled": "本轮单元全部跑完",
+ "goalBatch.gateCheck.units_succeeded": "本轮单元全部自动跑通,没有失败或被打回的",
+ "goalBatch.gatePanel.checks": "检查项",
+ "goalBatch.gatePanel.checksAt": "第 {{index}} 次判定 · {{time}}",
+ "goalBatch.gatePanel.checksPlanned": "尚未判定,届时检查这些",
+ "goalBatch.gatePanel.history": "判定记录",
+ "goalBatch.gatePanel.history.blocked": "未通过:{{checks}}",
+ "goalBatch.gatePanel.history.empty": "还没有判定过",
+ "goalBatch.gatePanel.history.released": "放行第 {{wave}} 批({{count}} 项)",
+ "goalBatch.gatePanel.history.unit": "「{{title}}」未通过自身验收,批次当即被拦下",
+ "goalBatch.gatePanel.history.unrecorded": "这一轮的判定早于判定记录功能,没有明细",
+ "goalBatch.gatePanel.next.checking": "单元已全部跑完,协调器下一次推进时判定",
+ "goalBatch.gatePanel.next.human": "等你决定:修订方案重探,或为出问题的几项另起一份方案",
+ "goalBatch.gatePanel.next.locked": "本轮 {{count}} 个单元跑完后自动判定",
+ "goalBatch.gatePanel.next.passed": "已放行第 {{wave}} 批({{count}} 项),这一批跑完后再判一次",
+ "goalBatch.gatePanel.next.passedDone": "花名册已全部放行",
+ "goalBatch.gatePanel.next.rejected": "已按你的决定开出 v{{revision}}",
+ "goalBatch.gatePanel.question": "修订方案重探,还是为出问题的几项另起一份方案?",
+ "goalBatch.gatePanel.verdict": "结论",
+ "goalBatch.overviewCount": "共 {{count}} 个批次 · {{nodes}} 个节点",
+ "goalBatch.planPanel.compare": "对比",
+ "goalBatch.planPanel.diff": "v{{base}} → v{{revision}} 的变化",
+ "goalBatch.planPanel.first": "这是第一版方案,没有可对比的上一版",
+ "goalBatch.planPanel.forked": "另起的方案:不沿用上一版的修订,从批次最初的方案出发",
+ "goalBatch.planPanel.full": "v{{revision}} 全文",
+ "goalBatch.planPanel.same": "与 v{{base}} 相同",
+ "goalBatch.planPanel.version": "版本",
+ "goalBatch.probes.cell.backlog": "未开始",
+ "goalBatch.probes.cell.done": "已完成",
+ "goalBatch.probes.cell.human": "需要介入",
+ "goalBatch.probes.cell.running": "进行中",
+ "goalBatch.probes.cell.stale": "已废弃",
+ "goalBatch.probes.hint": "先跑 {{count}} 个代表单元:覆盖差异最大的与最难的。它们全部自动跑通后,其余单元才会放行。",
+ "goalBatch.probes.rowLabel": "实验",
+ "goalBatch.probes.status.done": "探索完成",
+ "goalBatch.probes.status.pending": "待探索",
+ "goalBatch.probes.status.running": "探索中",
+ "goalBatch.probes.title": "冷启动 · 实验",
+ "goalBatch.redispatch.foot": "{{count}} 项 · 按 v{{revision}}",
+ "goalBatch.redispatch.fromProbe": "由实验第 {{index}} 项重开",
+ "goalBatch.redispatch.fromRound": "由 v{{revision}} 重开",
+ "goalBatch.redispatch.fromWave": "由第 {{wave}} 批第 {{index}} 项重开",
+ "goalBatch.redispatch.labelRound": "v{{revision}}",
+ "goalBatch.redispatch.reopenedRow": "重开",
+ "goalBatch.redispatch.title": "分批执行 · v{{revision}}",
+ "goalBatch.round.foot": "{{count}} 项",
+ "goalBatch.round.reviseEdge": "打回 · 修订",
+ "goalBatch.round.title": "第 {{revision}} 轮",
+ "goalBatch.status.done": "全部完成",
+ "goalBatch.status.human": "{{count}} 项需要介入",
+ "goalBatch.status.pending": "待开始",
+ "goalBatch.status.running": "进行中",
+ "goalBatch.status.stale": "{{count}} 项已废弃",
+ "goalBatch.template.forked": "执行方案 v{{revision}} · 新类型",
+ "goalBatch.template.title": "执行方案 v{{revision}}",
+ "goalBatch.templatePlain": "执行方案",
+ "goalBatch.title": "批次执行",
+ "goalBatch.waves.foot": "{{count}} 项 / {{waves}} 批",
+ "goalBatch.waves.row": "第{{number}}批",
+ "goalBatch.waves.title": "分批执行",
"goalChat.newTopic": "新对话",
"goalChat.noTopics": "还没有对话",
"goalChat.title": "问问进展",
@@ -662,9 +745,11 @@
"goalProcess.decision.effect.abandonAcceptance": "停止验收,目标结束但不下结论",
"goalProcess.decision.effect.fail": "结束目标,记为未达成",
"goalProcess.decision.effect.fixedRetry": "确认环境修好后重新执行这项任务",
+ "goalProcess.decision.effect.newClassBatch": "为失败的单元另起一份配方;新闸门通过后,这一批的其余单元继续推进",
"goalProcess.decision.effect.retire": "放弃这项任务,目标在没有它的情况下继续推进",
"goalProcess.decision.effect.retry": "把任务退回重做,补充说明会写进下一次执行的指令",
"goalProcess.decision.effect.retryAcceptance": "重新跑一次目标验收",
+ "goalProcess.decision.effect.reviseBatch": "根据这次失败修订配方,然后重探这一批",
"goalProcess.decision.submit": "确定",
"goalProcess.decision.summary.agentQuestion": "主 Agent 在推进目标时遇到一个只有你能拍板的问题,下面是它给出的选项和推荐。",
"goalProcess.decision.summary.goalAcceptance": "目标的整体验收没有通过,需要你决定重新验收、放弃验收,还是判定目标失败。",
@@ -697,15 +782,24 @@
"goalProcess.frontier.emptyTitle": "当前没有可推进的任务",
"goalProcess.frontier.needsYou": "{{count}} 项需要你",
"goalProcess.frontier.title": "当前任务",
+ "goalProcess.gate.batchCorrectionPlaceholder": "要怎么改这份方案——修订时必填,会成为下一版",
+ "goalProcess.gate.batchCorrectionRequired": "修订方案前先写下要改什么",
"goalProcess.gate.decisionPointLabel": "需要你决定什么",
"goalProcess.gate.noteLabel": "补充说明",
"goalProcess.gate.notePlaceholder": "可选,会写进下一次尝试的指令",
"goalProcess.gate.option.assume": "按 Agent 的假设来",
"goalProcess.gate.option.fail": "判定目标失败",
"goalProcess.gate.option.fixedRetry": "已修好,重试",
+ "goalProcess.gate.option.newClassBatch": "另起一份配方",
"goalProcess.gate.option.retire": "放弃这项任务",
"goalProcess.gate.option.retry": "重试这项任务",
+ "goalProcess.gate.option.reviseBatch": "修订配方并重探",
"goalProcess.gate.reason.attemptBudgetExhausted": "这项任务的尝试次数已用完",
+ "goalProcess.gate.reason.batchBroken": "有 {{count}} 个单元未能成功",
+ "goalProcess.gate.reason.batchOpenDecision": "这一批里仍有待人工决定的问题",
+ "goalProcess.gate.reason.batchTemplateIncomplete": "批次配方还不完整",
+ "goalProcess.gate.reason.batchUnsettled": "还有 {{count}} 个单元尚未完成",
+ "goalProcess.gate.reason.batchUntestedAxes": "还有变化维度未覆盖:{{axes}}",
"goalProcess.gate.reason.costBudgetExhausted": "目标的成本预算已用完",
"goalProcess.gate.reason.deviceStayedOffline": "任务所在的设备在所有自动重试期间一直离线",
"goalProcess.gate.reason.goalAcceptanceFailed": "目标整体验收未通过",
@@ -723,6 +817,7 @@
"goalProcess.gate.reason.verifyInternalError": "验证未能运行(内部错误),这次交付没有被评估",
"goalProcess.gate.recommended": "推荐",
"goalProcess.gate.title.agentQuestion": "回答主 Agent 的问题",
+ "goalProcess.gate.title.batchPatternBreak": "决定这一批接下来怎么走",
"goalProcess.gate.title.clarifyGoal": "开工前先确认目标",
"goalProcess.gate.title.fixSetup": "修好运行环境后重试",
"goalProcess.gate.title.goalAcceptance": "决定目标验收的去向",
@@ -738,6 +833,7 @@
"goalProcess.graph.title": "探索图",
"goalProcess.graph.view.all": "全图",
"goalProcess.graph.view.stage": "当前阶段",
+ "goalProcess.kind.batch": "批次",
"goalProcess.kind.decision": "决策",
"goalProcess.kind.experiment": "实验",
"goalProcess.kind.finding": "结论",
@@ -763,6 +859,7 @@
"goalProcess.lifecycle.action.work.input": "引用输入",
"goalProcess.lifecycle.action.work.produced": "产出交付物",
"goalProcess.lifecycle.action.work.supports": "补充证据",
+ "goalProcess.lifecycle.kind.batch": "批次",
"goalProcess.lifecycle.kind.decision": "决策",
"goalProcess.lifecycle.kind.experiment": "实验",
"goalProcess.lifecycle.kind.finding": "结论",
diff --git a/packages/agent-tracing/src/goal/types.ts b/packages/agent-tracing/src/goal/types.ts
index 761641b4bfe..ecc413473ba 100644
--- a/packages/agent-tracing/src/goal/types.ts
+++ b/packages/agent-tracing/src/goal/types.ts
@@ -67,7 +67,11 @@ export type GoalTickBranch =
/** Budget stopped the goal before this task could be dispatched. */
| 'budget_exhausted'
/** Start a run for the chosen task. */
- | 'dispatch_task';
+ | 'dispatch_task'
+ /** A repeated batch's gate passed; the coordinator releases the next wave. */
+ | 'rollout_gate'
+ /** A repeated batch's gate is blocked; the coordinator hands it to a person. */
+ | 'pattern_break';
export type GoalTickOutcome =
'advanced' | 'achieved' | 'waiting_human' | 'waiting_external' | 'no_progress' | 'failed';
diff --git a/packages/const/src/goal.test.ts b/packages/const/src/goal.test.ts
index ddca9bdc70c..38e77f1307c 100644
--- a/packages/const/src/goal.test.ts
+++ b/packages/const/src/goal.test.ts
@@ -1,19 +1,22 @@
import type {
+ GoalRolloutTrigger as GoalRolloutTriggerType,
GoalStatus as GoalStatusType,
GoalSubjectType as GoalSubjectTypeType,
} from '@lobechat/types';
import { describe, expect, expectTypeOf, it } from 'vitest';
-import { goalStatuses, goalSubjectTypes } from './goal';
+import { goalRolloutTriggers, goalStatuses, goalSubjectTypes } from './goal';
describe('goal consts', () => {
it('stays in sync with the @lobechat/types unions', () => {
expectTypeOf<(typeof goalStatuses)[number]>().toEqualTypeOf<GoalStatusType>();
expectTypeOf<(typeof goalSubjectTypes)[number]>().toEqualTypeOf<GoalSubjectTypeType>();
+ expectTypeOf<(typeof goalRolloutTriggers)[number]>().toEqualTypeOf<GoalRolloutTriggerType>();
});
it('keeps terminal states last-ish sanity', () => {
expect(goalStatuses).toContain('achieved');
expect(goalSubjectTypes).toContain('task');
+ expect(goalRolloutTriggers).toContain('canary');
});
});
diff --git a/packages/const/src/goal.ts b/packages/const/src/goal.ts
index b5d2e6195c0..aad79a18198 100644
--- a/packages/const/src/goal.ts
+++ b/packages/const/src/goal.ts
@@ -163,3 +163,76 @@ export const ACCEPTANCE_REVIEW_ERRORED_ERROR =
* Goal's status — the coordinator ignores it when choosing its next move.
*/
export const GOAL_REPORT_TASK_TITLE = 'Write the Goal report';
+
+// ============================================
+// Batch rollout (STAMP) — one repeated mould, delivered as a class
+// ============================================
+
+/**
+ * Rollout trigger vocabulary. Kept in sync with the `GoalRolloutTrigger` union
+ * in `@lobechat/types` (type-tested here), mirroring the `goalStatuses`
+ * convention. `off` is explicit opt-out; an absent policy means the same thing.
+ */
+export const goalRolloutTriggers = ['canary', 'full', 'off'] as const;
+
+/**
+ * Fixed title of the `batch` container node that holds a repeated mould's
+ * probe, gate and waves. Stored in English as data; clients recognize it for
+ * localized copy, the same way as the acceptance and clarification titles.
+ */
+export const GOAL_BATCH_TITLE = 'Deliver the repeated batch';
+
+/**
+ * Graph features a client declares it can render, sent with the graph read.
+ * The server keeps newer node kinds from clients that do not declare them —
+ * a cached web bundle or an installed desktop app predates them — and returns
+ * a shape they already understand instead.
+ */
+export const GOAL_GRAPH_CAPABILITY = {
+ /** The `batch` node kind (repeated-mould rollouts). */
+ batch: 'batch',
+} as const;
+
+/**
+ * Fixed title of the Assay (gate) decision node inside a batch. The coordinator
+ * opens it to answer one question a person may have to settle: can this whole
+ * class run automatically?
+ */
+export const GOAL_BATCH_ASSAY_TITLE = 'Prove the batch runs automatically';
+
+/** Fixed title of the Template (recipe) finding node a batch distills. */
+export const GOAL_BATCH_TEMPLATE_TITLE = 'Batch recipe';
+
+/** Default probe size K — representative units that run before the gate. */
+export const ROLLOUT_CANARY_SIZE_DEFAULT = 5;
+/** Default mass wave size M — units released per wave after the gate passes. */
+export const ROLLOUT_WAVE_SIZE_DEFAULT = 5;
+/**
+ * Below this many structurally identical units the batch ceremony costs more
+ * than it saves, so the planner decomposes per unit instead.
+ */
+export const ROLLOUT_MIN_HOMOGENEOUS_UNITS = 10;
+/** Probes never exceed the planner's per-turn task cap. */
+export const ROLLOUT_MAX_CANARY_SIZE = 5;
+/**
+ * Prefix of the reason recorded when a batch hits a pattern break and the
+ * coordinator hands the choice to a person (revise the recipe vs. new class).
+ */
+export const PATTERN_BREAK_PAUSE_REASON = 'Batch pattern break needs a decision';
+
+/**
+ * The batch pattern-break gate's option ids. Shared by the server that opens the
+ * gate and the client that localizes it, the same way `GOAL_CLARIFICATION_OPTION`
+ * is; the human-facing labels live in the locale files, never in the payload.
+ */
+export const GOAL_BATCH_BREAK_OPTION = {
+ newClass: 'new_class',
+ revise: 'revise',
+} as const;
+
+/**
+ * The batch pattern-break question's fixed English tail. The client strips it to
+ * reach the coordinator's dynamic reason, then renders the tail in the reader's
+ * language — mirroring the other coordinator question tails.
+ */
+export const GOAL_BATCH_BREAK_QUESTION_TAIL = 'How should this batch proceed?';
diff --git a/packages/database/src/models/__tests__/goal.test.ts b/packages/database/src/models/__tests__/goal.test.ts
index abead024974..52d914bb11a 100644
--- a/packages/database/src/models/__tests__/goal.test.ts
+++ b/packages/database/src/models/__tests__/goal.test.ts
@@ -65,6 +65,42 @@ describe('GoalModel', () => {
});
});
+ describe('update', () => {
+ it('keeps the batch recipe the coordinator revised when a stale config is saved', async () => {
+ const goal = await goalModel.create({
+ config: { rollout: { canarySize: 3, trigger: 'canary' } },
+ title: 'Batch',
+ });
+ // A budget editor reads the goal before the break revises the recipe…
+ const stale = (await goalModel.findById(goal.id))!.config!;
+ await goalModel.updateRolloutPolicy(goal.id, {
+ ...stale.rollout,
+ spec: { recipeOutline: 'v1\n\n### v2\nfix', repeatable: true },
+ });
+ // …and saves after it, with a new canary size of its own.
+ await goalModel.update(goal.id, {
+ config: { ...stale, rollout: { ...stale.rollout, canarySize: 4 }, maxConcurrentTasks: 2 },
+ });
+
+ const config = (await goalModel.findById(goal.id))!.config!;
+ expect(config.rollout?.spec?.recipeOutline).toBe('v1\n\n### v2\nfix');
+ expect(config.rollout?.canarySize).toBe(4);
+ expect(config.maxConcurrentTasks).toBe(2);
+ });
+
+ it('keeps the rollout policy when an edit leaves it out', async () => {
+ const goal = await goalModel.create({
+ config: { rollout: { canarySize: 3, trigger: 'canary' } },
+ title: 'Batch',
+ });
+ await goalModel.update(goal.id, { config: { maxConcurrentTasks: 2 } });
+ expect((await goalModel.findById(goal.id))!.config?.rollout).toMatchObject({
+ canarySize: 3,
+ trigger: 'canary',
+ });
+ });
+ });
+
describe('create', () => {
it('creates a goal with defaults', async () => {
const result = await goalModel.create({
diff --git a/packages/database/src/models/goal.ts b/packages/database/src/models/goal.ts
index 226ba40b0c4..8d5bb1f4c15 100644
--- a/packages/database/src/models/goal.ts
+++ b/packages/database/src/models/goal.ts
@@ -4,6 +4,8 @@ import { GOAL_CLARIFICATION_TITLE, type GoalStatus } from '@lobechat/const/goal'
import type {
GoalDecisionOption,
GoalNodeStatus,
+ GoalRolloutPolicy,
+ GoalRolloutState,
GoalSupervisionState,
GoalUnderstanding,
} from '@lobechat/types';
@@ -188,6 +190,35 @@ export class GoalModel {
.where(and(eq(goals.id, id), this.ownership()));
};
+ /**
+ * Patch only `config.rolloutState`, for the same reason as
+ * `updateUnderstanding`: the coordinator writes batch progress while the user
+ * may be editing budget on the same column. Passing `null` clears the batch.
+ */
+ updateRolloutState = async (id: string, state: GoalRolloutState | null): Promise<void> => {
+ await this.db
+ .update(goals)
+ .set({
+ config:
+ state === null
+ ? sql`COALESCE(${goals.config}, '{}'::jsonb) - 'rolloutState'`
+ : sql`jsonb_set(COALESCE(${goals.config}, '{}'::jsonb), '{rolloutState}', ${JSON.stringify(state)}::jsonb)`,
+ updatedAt: new Date(),
+ })
+ .where(and(eq(goals.id, id), this.ownership()));
+ };
+
+ /** Patch only `config.rollout`, so auto-detection can persist the policy. */
+ updateRolloutPolicy = async (id: string, policy: GoalRolloutPolicy): Promise<void> => {
+ await this.db
+ .update(goals)
+ .set({
+ config: sql`jsonb_set(COALESCE(${goals.config}, '{}'::jsonb), '{rollout}', ${JSON.stringify(policy)}::jsonb)`,
+ updatedAt: new Date(),
+ })
+ .where(and(eq(goals.id, id), this.ownership()));
+ };
+
/** Compare-and-swap only the supervisor namespace; concurrent budget edits survive. */
updateSupervisorState = async (
id: string,
@@ -213,24 +244,36 @@ export class GoalModel {
};
update = async (id: string, value: Partial<Omit<GoalItem, 'id' | 'userId'>>) => {
+ // Policy editors may carry a pre-claim or pre-release snapshot. Runtime
+ // ownership always comes from the current row, never that snapshot, and
+ // policy edits cannot replace the concurrently written incident ledger.
+ const merged = sql`(COALESCE(${JSON.stringify(value.config ?? {})}::jsonb, '{}'::jsonb) - 'planningCheckpoint' - 'planningProtocol' - 'supervisorState' - 'managerState' - 'understanding' - 'quotaRetryWakeAt' - 'rolloutState')
+ || jsonb_strip_nulls(jsonb_build_object(
+ 'planningCheckpoint', ${goals.config}->'planningCheckpoint',
+ 'planningProtocol', ${goals.config}->'planningProtocol',
+ 'supervisorState', ${goals.config}->'supervisorState',
+ 'managerState', ${goals.config}->'managerState',
+ 'understanding', ${goals.config}->'understanding',
+ 'quotaRetryWakeAt', ${goals.config}->'quotaRetryWakeAt',
+ 'rolloutState', ${goals.config}->'rolloutState'
+ ))`;
const [row] = await this.db
.update(goals)
.set({
...value,
- // Policy editors may carry a pre-claim or pre-release snapshot. Runtime
- // ownership always comes from the current row, never that snapshot, and
- // policy edits cannot replace the concurrently written incident ledger.
+ // The batch recipe (`rollout.spec`) is the coordinator's too: a pattern
+ // break rewrites it, and a stale snapshot must not put back the recipe
+ // that just failed. The person's own rollout settings still come from
+ // the edit; a policy the edit leaves out stays as it is.
...(value.config !== undefined
? {
- config: sql`(COALESCE(${JSON.stringify(value.config ?? {})}::jsonb, '{}'::jsonb) - 'planningCheckpoint' - 'planningProtocol' - 'supervisorState' - 'managerState' - 'understanding' - 'quotaRetryWakeAt')
- || jsonb_strip_nulls(jsonb_build_object(
- 'planningCheckpoint', ${goals.config}->'planningCheckpoint',
- 'planningProtocol', ${goals.config}->'planningProtocol',
- 'supervisorState', ${goals.config}->'supervisorState',
- 'managerState', ${goals.config}->'managerState',
- 'understanding', ${goals.config}->'understanding',
- 'quotaRetryWakeAt', ${goals.config}->'quotaRetryWakeAt'
- ))`,
+ config: sql`CASE WHEN NOT COALESCE(jsonb_exists(${goals.config}, 'rollout'), false) THEN ${merged}
+ ELSE jsonb_set(
+ ${merged},
+ '{rollout}',
+ COALESCE(${merged}->'rollout', ${goals.config}->'rollout')
+ || jsonb_strip_nulls(jsonb_build_object('spec', ${goals.config}->'rollout'->'spec'))
+ ) END`,
}
: {}),
updatedAt: new Date(),
diff --git a/packages/database/src/models/goalGraph.ts b/packages/database/src/models/goalGraph.ts
index 8d892c99f9c..7cc82fa4626 100644
--- a/packages/database/src/models/goalGraph.ts
+++ b/packages/database/src/models/goalGraph.ts
@@ -653,8 +653,14 @@ export class GoalGraphModel {
const target = nodes.find((node) => node.id === targetNodeId);
if (!source || !target || source.id === target.id)
throw new Error('Invalid experiment relationship');
- if (source.kind !== 'experiment')
- throw new Error('Only an experiment can contain nodes or answer a question');
+ // Two kinds are containers: an `experiment` (a candidate answer under
+ // test) and a `batch` (one repeated mould delivered as a class). The
+ // single-owner and cycle rules below are about containment itself, so
+ // they hold for both; only the question-scope rules are experiment-only.
+ if (source.kind !== 'experiment' && source.kind !== 'batch')
+ throw new Error('Only a container can contain nodes or answer a question');
+ if (kind === 'answers' && source.kind !== 'experiment')
+ throw new Error('Only an experiment can answer a question');
if (kind === 'contains') {
const owner = experimentOwner(graph, target.id);
if (owner && owner !== source.id)
@@ -665,6 +671,7 @@ export class GoalGraphModel {
(edge) => edge.kind === 'answers' && edge.sourceNodeId === target.id,
)?.targetNodeId;
if (
+ source.kind === 'experiment' &&
edges.some(
(edge) =>
edge.kind === 'answers' &&
@@ -673,7 +680,11 @@ export class GoalGraphModel {
)
)
throw new Error('A question must share its answer scope');
- if (questionId && experimentOwner(graph, questionId) !== source.id)
+ if (
+ source.kind === 'experiment' &&
+ questionId &&
+ experimentOwner(graph, questionId) !== source.id
+ )
throw new Error('An answer must share its question scope');
} else {
if (target.kind !== 'problem') throw new Error('An experiment must answer a question');
diff --git a/packages/database/src/schemas/goalGraph.ts b/packages/database/src/schemas/goalGraph.ts
index 7a08b60bb6b..eb01892648a 100644
--- a/packages/database/src/schemas/goalGraph.ts
+++ b/packages/database/src/schemas/goalGraph.ts
@@ -44,6 +44,11 @@ export const goalNodes = pgTable(
goalId: text('goal_id')
.references(() => goals.id, { onDelete: 'cascade' })
.notNull(),
+ /**
+ * Node role. Deliberately `text` + TS union, never a pgEnum: the vocabulary
+ * moves (`work` → `task`, and now `batch`), and a CHECK would pin it into
+ * DDL and cost an ALTER on every rename.
+ */
kind: text('kind').$type<GoalNodeKind>().notNull(),
status: text('status').$type<GoalNodeStatus>().default('proposed').notNull(),
title: text('title').notNull(),
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index ec872bd614e..d480b24adab 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -32,6 +32,99 @@ export default {
'response.contentSafetyNotice':
'This reply was limited for content safety reasons. If this happens often, you may temporarily lose access to this model.',
+ 'goalBatch.cell.backlog': 'Not run',
+ 'goalBatch.cell.done': 'Done',
+ 'goalBatch.cell.human': 'Needs you',
+ 'goalBatch.cell.reopened': 'Reopened in v{{revision}}',
+ 'goalBatch.cell.runIn': 'Runs in v{{revision}}',
+ 'goalBatch.cell.running': 'Running',
+ 'goalBatch.cell.stale': 'Superseded',
+ 'goalBatch.cell.tooltip': 'Wave {{wave}} · item {{index}} · {{title}} · {{state}}',
+ 'goalBatch.enter': 'Open',
+ 'goalBatch.planPanel.compare': 'Compare with',
+ 'goalBatch.planPanel.diff': 'What changed from v{{base}} to v{{revision}}',
+ 'goalBatch.planPanel.first': 'The first version — nothing earlier to compare with',
+ 'goalBatch.planPanel.forked':
+ 'A forked plan: it starts again from the batch’s original outline instead of revising the previous version',
+ 'goalBatch.planPanel.full': 'v{{revision}} in full',
+ 'goalBatch.planPanel.same': 'Same as v{{base}}',
+ 'goalBatch.planPanel.version': 'Version',
+ 'goalBatch.probes.cell.backlog': 'Not started',
+ 'goalBatch.probes.cell.done': 'Done',
+ 'goalBatch.probes.cell.human': 'Needs you',
+ 'goalBatch.probes.cell.running': 'In progress',
+ 'goalBatch.probes.cell.stale': 'Superseded',
+ 'goalBatch.gateCheck.axes_covered': 'The trials covered every declared variant',
+ 'goalBatch.gateCheck.count': '{{count}} / {{total}}',
+ '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.units_settled': 'Every unit this round finished',
+ 'goalBatch.gateCheck.units_succeeded':
+ 'Every unit this round ran through on its own — none failed or was sent back',
+ 'goalBatch.gatePanel.checks': 'Checks',
+ 'goalBatch.gatePanel.checksAt': 'Verdict {{index}} · {{time}}',
+ 'goalBatch.gatePanel.checksPlanned': 'Not judged yet — these will be checked',
+ 'goalBatch.gatePanel.question':
+ 'Revise the plan and re-probe, or fork a fresh one for the units that broke?',
+ 'goalBatch.gatePanel.history': 'Verdicts',
+ 'goalBatch.gatePanel.history.blocked': 'Held: {{checks}}',
+ 'goalBatch.gatePanel.history.empty': 'No verdict yet',
+ 'goalBatch.gatePanel.history.released': 'Released wave {{wave}} ({{count}} units)',
+ 'goalBatch.gatePanel.history.unrecorded': 'Judged before verdicts were recorded — no detail kept',
+ 'goalBatch.gatePanel.history.unit':
+ '“{{title}}” failed its own check — the batch was held at once',
+ 'goalBatch.gatePanel.next.checking':
+ 'Every unit finished — judged on the coordinator’s next step',
+ 'goalBatch.gatePanel.next.human':
+ 'Waiting on you: revise the plan, or fork a fresh one for the units that broke',
+ 'goalBatch.gatePanel.next.locked':
+ 'Judged automatically once this round’s {{count}} units finish',
+ '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.rejected': 'Reopened as v{{revision}} on your decision',
+ 'goalBatch.gatePanel.verdict': 'Verdict',
+ 'goalBatch.gate.checkCount': '{{count}} checks',
+ 'goalBatch.gate.hintTitle': 'Checked before the rest are released:',
+ 'goalBatch.gate.status.checking': 'Judging',
+ 'goalBatch.gate.status.human': 'Needs your decision',
+ 'goalBatch.gate.status.locked': 'Not judged',
+ 'goalBatch.gate.status.passed': 'Passed',
+ 'goalBatch.gate.status.rejected': 'Sent back',
+ 'goalBatch.gate.title': 'Release gate',
+ 'goalBatch.gate.titleRound': 'Release gate · v{{revision}}',
+ 'goalBatch.overviewCount': 'Total: {{count}} batches · {{nodes}} nodes',
+ 'goalBatch.probes.hint':
+ '{{count}} representative units run first — the most different ones and the hardest. The rest are released only once every one of them runs through automatically.',
+ 'goalBatch.probes.status.done': 'Trials done',
+ 'goalBatch.probes.status.pending': 'Not started',
+ 'goalBatch.probes.status.running': 'Trials running',
+ 'goalBatch.probes.title': 'Cold start · trials',
+ 'goalBatch.probes.rowLabel': 'Trials',
+ 'goalBatch.redispatch.foot': '{{count}} units · on v{{revision}}',
+ 'goalBatch.redispatch.fromProbe': 'Reopened from trial {{index}}',
+ 'goalBatch.redispatch.fromRound': 'Reopened from v{{revision}}',
+ 'goalBatch.redispatch.fromWave': 'Reopened from wave {{wave}}, item {{index}}',
+ 'goalBatch.redispatch.title': 'Waves · v{{revision}}',
+ 'goalBatch.redispatch.labelRound': 'v{{revision}}',
+ 'goalBatch.redispatch.reopenedRow': 'Reopened',
+ 'goalBatch.round.foot': '{{count}} units',
+ 'goalBatch.round.reviseEdge': 'Sent back · revise',
+ 'goalBatch.round.title': 'Round {{revision}}',
+ 'goalBatch.status.done': 'All done',
+ 'goalBatch.status.human': '{{count}} need you',
+ 'goalBatch.status.pending': 'Not started',
+ 'goalBatch.status.running': 'In progress',
+ 'goalBatch.status.stale': '{{count}} superseded',
+ 'goalBatch.template.forked': 'Plan v{{revision}} · new class',
+ 'goalBatch.template.title': 'Plan v{{revision}}',
+ 'goalBatch.templatePlain': 'Batch plan',
+ 'goalBatch.title': 'Repeated batch',
+ 'goalBatch.waves.foot': '{{count}} units / {{waves}} waves',
+ 'goalBatch.waves.row': 'W{{number}}',
+ 'goalBatch.waves.title': 'Waves',
+
'goalExperiment.continuedFrom': 'Continued exploration',
'goalExperiment.drill': 'Explore inside',
'goalExperiment.drillNamed': 'Explore inside: {{title}}',
@@ -2239,6 +2332,7 @@ export default {
'goalProcess.gate.title.recoverTask': 'Decide what happens to the failed task',
'goalProcess.gate.title.goalAcceptance': 'Decide the goal acceptance outcome',
'goalProcess.gate.title.fixSetup': 'Fix the setup, then retry',
+ 'goalProcess.gate.title.batchPatternBreak': 'Decide how the failed batch proceeds',
'goalProcess.clarify.title': 'Clarify the goal before work starts',
'goalProcess.clarify.description':
'Answer these once and the agent plans with them. Skip to let it proceed on its own assumptions.',
@@ -2273,14 +2367,24 @@ export default {
'goalProcess.gate.reason.transientRetriesSpent':
'The run failed the same way {{count}} times over {{duration}} ({{error}}). Check the device, its network and the agent gateway.',
'goalProcess.gate.reason.runError': 'The run stopped with an error ({{code}})',
+ 'goalProcess.gate.reason.batchUnsettled': '{{count}} unit(s) have not settled',
+ 'goalProcess.gate.reason.batchBroken': '{{count}} unit(s) did not succeed',
+ 'goalProcess.gate.reason.batchOpenDecision': 'a human decision is still open in this batch',
+ 'goalProcess.gate.reason.batchTemplateIncomplete': 'the batch template is incomplete',
+ 'goalProcess.gate.reason.batchUntestedAxes': 'untested axes: {{axes}}',
'goalProcess.gate.recommended': 'recommended',
'goalProcess.gate.noteLabel': 'Extra guidance',
+ 'goalProcess.gate.batchCorrectionPlaceholder':
+ 'What to change in the recipe — required to revise it; it becomes the next version',
+ 'goalProcess.gate.batchCorrectionRequired': 'Write the correction before revising the recipe',
'goalProcess.gate.notePlaceholder': 'Optional — goes into the next attempt instructions',
'goalProcess.gate.option.retry': 'Retry work',
'goalProcess.gate.option.fixedRetry': 'I fixed it — retry',
'goalProcess.gate.option.retire': 'Retire work',
'goalProcess.gate.option.fail': 'Fail goal',
'goalProcess.gate.option.assume': 'Go with the assumption',
+ 'goalProcess.gate.option.reviseBatch': 'Revise the recipe and re-probe',
+ 'goalProcess.gate.option.newClassBatch': 'Fork a fresh recipe',
'goalProcess.decision.effect.fixedRetry': 'Run the task again once the setup is fixed.',
'goalProcess.decision.asks.judgment': 'needs your review on a stuck task',
'goalProcess.decision.asks.goalAcceptance': 'needs your review on the goal acceptance',
@@ -2309,6 +2413,10 @@ export default {
'goalProcess.decision.effect.retryAcceptance': 'Run the goal-level acceptance again.',
'goalProcess.decision.effect.abandonAcceptance':
'Stop acceptance and end the goal without a verdict.',
+ 'goalProcess.decision.effect.reviseBatch':
+ 'Revise the recipe from this failure, then re-probe this batch.',
+ 'goalProcess.decision.effect.newClassBatch':
+ 'Fork a fresh recipe for the units that broke; the rest of the batch continues once the new gate passes.',
'goalProcess.signOff.islandSubtitle': 'is done and waiting for your sign-off',
'goalProcess.signOff.question': 'Do you accept what this goal delivered?',
'goalProcess.signOff.description': 'Goal-level acceptance passed. Your sign-off closes the goal.',
@@ -2476,6 +2584,7 @@ export default {
'goalProcess.kind.experiment': 'Experiment',
'goalProcess.kind.finding': 'Finding',
'goalProcess.kind.decision': 'Decision',
+ 'goalProcess.kind.batch': 'Batch',
'goalProcess.node.running': 'Running',
'goalProcess.node.stopped': 'Stopped',
'goalProcess.node.done': 'Done',
@@ -2508,6 +2617,7 @@ export default {
'goalProcess.lifecycle.action.work.produced': 'produced',
'goalProcess.lifecycle.action.work.supports': 'added evidence',
'goalProcess.lifecycle.kind.decision': 'decision',
+ 'goalProcess.lifecycle.kind.batch': 'batch',
'goalProcess.lifecycle.kind.experiment': 'experiment',
'goalProcess.lifecycle.kind.finding': 'finding',
'goalProcess.lifecycle.kind.goal': 'goal',
diff --git a/packages/prompts/src/chains/goal.test.ts b/packages/prompts/src/chains/goal.test.ts
index c3a37f3e3c5..fe8efb1c37c 100644
--- a/packages/prompts/src/chains/goal.test.ts
+++ b/packages/prompts/src/chains/goal.test.ts
@@ -5,6 +5,7 @@ import {
chainGoalDecompose,
GOAL_CRITERIA_DRAFT_JSON_SCHEMA,
GOAL_CRITERIA_DRAFT_PROMPT_VERSION,
+ GOAL_DECOMPOSE_JSON_SCHEMA,
GOAL_DECOMPOSE_PROMPT_VERSION,
} from './goal';
@@ -43,7 +44,7 @@ describe('chainGoalDecompose', () => {
const { messages } = chainGoalDecompose({ requirement });
const prompt = messages[0].content;
- expect(GOAL_DECOMPOSE_PROMPT_VERSION).toBe('v6');
+ expect(GOAL_DECOMPOSE_PROMPT_VERSION).toBe('v8');
expect(messages[1].content).toContain(requirement);
expect(prompt).toContain('a request to build, fix, or upgrade requires implementation');
expect(prompt).toContain('It may pass when it proves a capability is missing');
@@ -55,6 +56,23 @@ describe('chainGoalDecompose', () => {
expect(prompt).toContain('an investigation-only goal must not become an implementation task');
});
+ it('flags one repeated mould with a probe spec and a full roster', () => {
+ const { messages } = chainGoalDecompose({ requirement: '迁移 50 个同构的 store' });
+ const prompt = messages[0].content;
+
+ // R2: the homogeneity filter the planner must apply before claiming a batch.
+ expect(prompt).toContain('after replacing the concrete file / module / symbol names');
+ // Probe-only tasks plus the full roster the coordinator promotes from.
+ expect(prompt).toContain('3–5 probes');
+ expect(prompt).toContain('full roster of every homogeneous unit');
+ expect(prompt).toContain('leave rollout null');
+
+ const rollout = (GOAL_DECOMPOSE_JSON_SCHEMA.schema.properties as any).rollout;
+ expect(rollout).toBeDefined();
+ expect(rollout.properties.units).toBeDefined();
+ expect(rollout.properties.repeatable).toBeDefined();
+ });
+
it('reports what it cannot determine and plans on answered clarifications', () => {
const plain = chainGoalDecompose({ requirement: '写一份发布说明' });
expect(plain.messages[0].content).toContain(
diff --git a/packages/prompts/src/chains/goal.ts b/packages/prompts/src/chains/goal.ts
index 56fd4922ff8..3469f748ba9 100644
--- a/packages/prompts/src/chains/goal.ts
+++ b/packages/prompts/src/chains/goal.ts
@@ -65,7 +65,7 @@ export const GOAL_CRITERIA_DRAFT_JSON_SCHEMA = {
};
/** Bump when the goal decomposition planning prompt meaningfully changes. */
-export const GOAL_DECOMPOSE_PROMPT_VERSION = 'v6';
+export const GOAL_DECOMPOSE_PROMPT_VERSION = 'v8';
export const GOAL_DECOMPOSE_JSON_SCHEMA = {
name: 'goal_decomposition',
@@ -74,6 +74,37 @@ export const GOAL_DECOMPOSE_JSON_SCHEMA = {
properties: {
assumptions: { items: { maxLength: 280, type: 'string' }, maxItems: 5, type: 'array' },
problemStatement: { maxLength: 280, minLength: 1, type: 'string' },
+ /**
+ * Set only for one repeated mould — many structurally identical units
+ * sharing a single reusable transformation. Null for every ordinary goal.
+ */
+ rollout: {
+ additionalProperties: false,
+ properties: {
+ recipeOutline: { maxLength: 280, type: 'string' },
+ repeatable: { type: 'boolean' },
+ /** Honest count of the homogeneous units in the whole goal. */
+ unitCount: { minimum: 1, type: 'integer' },
+ /** Roster of every homogeneous unit, probes first, in delivery order. */
+ units: { items: { maxLength: 120, type: 'string' }, maxItems: 60, type: 'array' },
+ /** Axes the units vary along, so a probe can cover them. */
+ variants: {
+ items: {
+ additionalProperties: false,
+ properties: {
+ axis: { maxLength: 80, minLength: 1, type: 'string' },
+ values: { items: { maxLength: 80, type: 'string' }, maxItems: 8, type: 'array' },
+ },
+ required: ['axis', 'values'],
+ type: 'object',
+ },
+ maxItems: 4,
+ type: 'array',
+ },
+ },
+ required: ['repeatable', 'unitCount', 'recipeOutline', 'variants', 'units'],
+ type: ['object', 'null'],
+ },
questions: {
items: {
additionalProperties: false,
@@ -107,7 +138,7 @@ export const GOAL_DECOMPOSE_JSON_SCHEMA = {
type: 'array',
},
},
- required: ['problemStatement', 'questions', 'assumptions', 'tasks'],
+ required: ['problemStatement', 'questions', 'assumptions', 'tasks', 'rollout'],
type: 'object' as const,
},
strict: true,
@@ -158,6 +189,11 @@ export const chainGoalDecompose = ({
'- Set blocking when the goal leaves open something that defines the deliverable itself and no default is safe: who it is for, what exactly is to be analyzed or changed, what outcome a change must achieve, or which of incompatible directions to take. A guess there produces a different deliverable, not merely a weaker one. Formats, details, and preferences with a sensible default are never blocking.',
'- The user is asked once, before any work starts, and every blocking question goes into that single round — there is no later chance to ask, so list them all now rather than holding one back. Keep to what truly decides the deliverable. A goal that already states these things returns no blocking question.',
'- assumptions lists the non-obvious readings the plan relies on that the user may want to correct; skip the obvious. Write every assumption and every answered clarification into the instructions of the tasks it affects.',
+ '- rollout is how you flag ONE repeated mould: many structurally identical units that share a single reusable transformation — for example migrating fifty sibling stores the same way, or applying one cross-cutting change to many files. If the requirement applies the same transformation to many structurally identical sibling units (a cross-cutting change to N files or modules), you MUST set rollout instead of collapsing it into a single "apply to all" task plus a verification pipeline. Leave it null for every ordinary goal that is not such a repeated mould — one whose directions differ, or a genuine sequence of different steps. Setting it is a claim you must be able to defend, not a way to list more tasks.',
+ "- When you set rollout, repeatable must be true only if, after replacing the concrete file / module / symbol names with placeholders, every unit's transformation steps are still the same. If they differ, it is not one batch: leave rollout null and decompose the directions normally.",
+ '- rollout.unitCount is your honest count of the homogeneous units in the WHOLE goal (it will usually exceed the few tasks you list). recipeOutline names that single reusable transformation in one sentence. variants lists the axes the units vary along (e.g. axis "cold-start" with values ["yes","no"]); name an axis only if some unit actually takes each value you list.',
+ '- rollout.units is the full roster of every homogeneous unit as short titles, probes first and in delivery order (list all of them, up to 60). The coordinator promotes the units after the probes from this roster one wave at a time; a unit missing here will never be delivered.',
+ '- When rollout is set, tasks lists only the few REPRESENTATIVE units to run first — 3–5 probes, not every unit. Choose probes that cover the declared variant axes and MUST include the hardest unit. The coordinator releases the remaining units in waves once the probes prove the class runs fully automatically; do not enumerate them here.',
'- Write all fields in the language used by the goal.',
].join('\n'),
role: 'system',
diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.ts
index abcad0e2cb1..9d1256a290a 100644
--- a/packages/types/src/goal.ts
+++ b/packages/types/src/goal.ts
@@ -110,6 +110,8 @@ export type GoalPauseReason =
| 'exploration_limit'
/** The planner asked for a correction after its allowance was already spent. */
| 'exploration_revision_limit'
+ /** A repeated batch hit a pattern break and is waiting on a person's choice. */
+ | 'pattern_break'
| 'user';
export interface GoalExplorationDecision {
@@ -418,6 +420,163 @@ export interface GoalUnderstanding {
updatedAt: string;
}
+/**
+ * Batch rollout trigger. `off`/absent keeps the ordinary decomposition: a goal
+ * that is not one repeated mould never grows a batch node, and the coordinator
+ * reads none of the rollout code paths. `canary` probes first, proves the class
+ * is fully automatic at a gate, then releases the rest in waves; `full` skips
+ * the probe and delivers every unit as one wave.
+ */
+export type GoalRolloutTrigger = 'canary' | 'full' | 'off';
+
+/**
+ * One axis the repeated units vary along. Recorded so the gate can refuse a
+ * green whose coverage never took a value on some axis — the half the probe
+ * happened to miss (a `cold-start` value discovered only later).
+ */
+export interface GoalRolloutVariantAxis {
+ /** Axis name, e.g. "cold-start", "auth-boundary". */
+ axis: string;
+ /** Concrete values the repeated units take on this axis. */
+ values: string[];
+}
+
+/**
+ * Batch rollout policy. Lives on the JSONB `config` column like the other goal
+ * policies — the graph's own vocabulary (`goal_nodes.kind`) carries the shape,
+ * so nothing here needs a schema of its own.
+ */
+export interface GoalRolloutPolicy {
+ /** Probe size K — how many representative units run before the gate. */
+ canarySize?: number;
+ /**
+ * How many structurally identical units make one batch worth gating. Below it
+ * the ordinary per-unit decomposition is cheaper than the ceremony.
+ */
+ minHomogeneousUnits?: number;
+ /** Why the planner judged this batch homogeneous; kept for the gate report. */
+ spec?: {
+ /** R2 condition: after masking concrete names, is the transform still one? */
+ repeatable: boolean;
+ /** The reusable transformation, in the planner's words. */
+ recipeOutline?: string;
+ variantAxes?: GoalRolloutVariantAxis[];
+ };
+ trigger: GoalRolloutTrigger;
+ /**
+ * Roster of every homogeneous unit in the goal, probes included and in
+ * delivery order. Probes are the first, fully-briefed units; the coordinator
+ * materializes the rest from here one wave at a time, so the graph never
+ * shows the whole fan-out at build time.
+ */
+ units?: string[];
+ /** Mass wave size M — how many units are released per wave after the gate. */
+ waveSize?: number;
+}
+
+/**
+ * One condition the release gate judged. Mirrors `evaluateRolloutGate`: the
+ * same keys, in the same order, with what each one found — so the person can see
+ * 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';
+
+export interface GoalRolloutGateCheck {
+ /** For a count check: how many of `total` held, e.g. 5 of 5 units ran through. */
+ count?: number;
+ /** Free-form specifics, such as an uncovered `axis=value`. */
+ details?: string[];
+ key: GoalRolloutGateCheckKey;
+ /** The nodes the check is about — the units that failed, the open decision. */
+ nodeIds?: string[];
+ passed: boolean;
+ total?: number;
+}
+
+/**
+ * One gate verdict and what the coordinator did with it. Appended on every
+ * release and every hold, so the gate keeps its own record instead of the
+ * decision's prose being the only trace.
+ */
+export interface GoalRolloutGateEvaluation {
+ /** ISO time of the verdict. */
+ at: string;
+ /** What the gate judged; empty when a unit's own check held the batch (R6). */
+ checks: GoalRolloutGateCheck[];
+ /** The coordinator's English summary, kept for the trace. */
+ message?: string;
+ /** The unit whose own check held the batch, when `trigger` is `unit`. */
+ nodeId?: string;
+ outcome: 'blocked' | 'released';
+ /** Units the release put into the next wave. */
+ releasedCount?: number;
+ /** The recipe revision (round) this verdict belongs to. */
+ revision: number;
+ /**
+ * 1-based ordinal of this verdict within its round. Written by the
+ * coordinator so it keeps counting after older verdicts were dropped.
+ */
+ seq?: number;
+ /** `gate`: the gate judged a settled wave. `unit`: one unit failed its own check. */
+ trigger: 'gate' | 'unit';
+ /**
+ * The roster wave a release put out, counted across every round. Written by
+ * the coordinator because the log is capped — counting the kept entries would
+ * renumber the history once the oldest fall off.
+ */
+ wave?: number;
+ /** Waves released in this round when the verdict was taken (after a release). */
+ waveIndex: number;
+}
+
+/** Where a batch rollout currently stands. */
+export type GoalRolloutPhase = 'probe' | 'assay' | 'mass' | 'pattern_break' | 'done';
+
+/**
+ * Coordinator-owned rollout progress. Written by decomposition and by the
+ * coordinator's own gate moves, never by a policy edit — the same rule that
+ * keeps `managerState` server-owned.
+ */
+export interface GoalRolloutState {
+ /** The gate (Assay) decision node, once decomposition created it. */
+ assayNodeId?: string;
+ /** The `batch` container node. */
+ batchNodeId: 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.
+ */
+ gateLog?: GoalRolloutGateEvaluation[];
+ /**
+ * Node ids of the mass tasks the current round released, oldest wave first.
+ * A restarted canary starts a new round and clears it.
+ */
+ massNodeIds?: string[];
+ /** Phase the rollout is in; the coordinator reads this to pick its move. */
+ phase: GoalRolloutPhase;
+ /** Node ids of the probe tasks that must run before the gate passes. */
+ probeNodeIds: string[];
+ /** How many roster entries have been materialized (probes + released waves). */
+ releasedCount?: number;
+ /** Node id of the current Template (finding) node. */
+ templateNodeId?: string;
+ /** Current Template revision; incremented each time the recipe is revised. */
+ templateRevision: number;
+ /**
+ * The class still to deliver, in delivery order; probes come first. Starts as
+ * the full roster. A pattern break re-cuts it to what is still owed — the
+ * re-opened probes, the broken units past the canary size, then whatever was
+ * never released — so waves deliver only the remainder and units already
+ * delivered under the old recipe drop out.
+ */
+ unitTitles?: string[];
+ /** How many mass waves have been released. */
+ waveIndex: number;
+ /** Roster waves released so far across every round; `waveIndex` restarts per round. */
+ wavesReleased?: number;
+}
+
export interface GoalConfig {
acceptance?: GoalAcceptancePolicy;
/**
@@ -450,6 +609,13 @@ export interface GoalConfig {
recovery?: GoalRecoveryPolicy;
/** Coordinator-owned receipt of the latest wrap-up report dispatch. */
report?: GoalReportDispatch;
+ /**
+ * Batch rollout, when this goal is one repeated mould. Absent on every goal
+ * that is not — which is what keeps the mechanism off the ordinary path.
+ */
+ rollout?: GoalRolloutPolicy;
+ /** Coordinator-owned batch progress; never accepted as client configuration. */
+ rolloutState?: GoalRolloutState;
schedule?: GoalSchedulePolicy;
supervision?: GoalSupervisionPolicy;
/** Durable supervisor topic and bounded incident ledger. */
@@ -467,7 +633,7 @@ export interface GoalConfig {
/** Creation accepts planning options, never a runtime receipt. */
export type GoalCreateConfig = Omit<
GoalConfig,
- 'managerState' | 'report' | 'supervisorState' | 'understanding'
+ 'managerState' | 'report' | 'rolloutState' | 'supervisorState' | 'understanding'
>;
/**
@@ -502,8 +668,16 @@ export interface GoalItem {
// Goal Graph — durable long-horizon reasoning structure
// ============================================
-/** Coarse-grained semantic role of a node in a Goal Graph. */
-export type GoalNodeKind = 'problem' | 'experiment' | 'task' | 'finding' | 'decision';
+/**
+ * Coarse-grained semantic role of a node in a Goal Graph.
+ *
+ * `batch` is the container for one repeated mould: a set of structurally
+ * identical units delivered as a single class (probe → gate → waves) instead of
+ * N flat sibling tasks. It is deliberately its own kind rather than a reuse of
+ * `experiment`: an experiment is a candidate answer under test, a batch is one
+ * reusable transformation applied many times.
+ */
+export type GoalNodeKind = 'problem' | 'experiment' | 'task' | 'finding' | 'decision' | 'batch';
/** Semantic lifecycle of a node; independent from the execution status of its Task. */
export type GoalNodeStatus =
diff --git a/packages/utils/src/goalCopy.test.ts b/packages/utils/src/goalCopy.test.ts
index 4ef531d15a0..62d86ee45a1 100644
--- a/packages/utils/src/goalCopy.test.ts
+++ b/packages/utils/src/goalCopy.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { coordinatorGateReason, coordinatorReasonCopy } from './goalCopy';
+import { coordinatorGateReason, coordinatorReasonCopies, coordinatorReasonCopy } from './goalCopy';
/**
* The machine gate's question is English data written on the server; without a
@@ -38,3 +38,35 @@ describe('machine gate reasons', () => {
);
});
});
+
+/**
+ * A batch pattern break lists every blocker it hit at once, joined by `; `. The
+ * sentence reached a Chinese reader verbatim, so each blocker is localized on
+ * its own and the parts rejoin.
+ */
+describe('batch gate reasons', () => {
+ const reasonOf = (question: string) => coordinatorReasonCopies(coordinatorGateReason(question));
+
+ it('localizes each blocker a pattern break lists', () => {
+ expect(
+ reasonOf(
+ '3 unit(s) did not succeed; the batch template is incomplete\n\nHow should this batch proceed?',
+ ),
+ ).toEqual([
+ { key: 'goalProcess.gate.reason.batchBroken', params: { count: '3' } },
+ { key: 'goalProcess.gate.reason.batchTemplateIncomplete' },
+ ]);
+ });
+
+ it('reads a lone blocker', () => {
+ expect(reasonOf('1 unit(s) did not succeed\n\nHow should this batch proceed?')).toEqual([
+ { key: 'goalProcess.gate.reason.batchBroken', params: { count: '1' } },
+ ]);
+ });
+
+ it('keeps a half-known sentence verbatim rather than half-translating it', () => {
+ expect(
+ reasonOf('1 unit(s) did not succeed; something new\n\nHow should this batch proceed?'),
+ ).toBeUndefined();
+ });
+});
diff --git a/packages/utils/src/goalCopy.ts b/packages/utils/src/goalCopy.ts
index b62ceaeebd5..d2bac834a58 100644
--- a/packages/utils/src/goalCopy.ts
+++ b/packages/utils/src/goalCopy.ts
@@ -18,6 +18,8 @@ const QUESTION_TAILS = [
/\.?\s*Fix it, then retry or retire this task node\?$/,
/\.?\s*Retry Goal acceptance or fail this Goal\?$/,
/\.?\s*Retry Goal acceptance, abandon it, or fail this Goal\?$/,
+ // The batch pattern-break gate (see `GoalService.openPatternBreakGate`).
+ /\.?\s*How should this batch proceed\?$/,
];
export const coordinatorGateReason = (question?: string | null): string | undefined => {
@@ -120,10 +122,47 @@ const REASON_PATTERNS: Array<{
},
];
-export const coordinatorReasonCopy = (reason?: string | null): LocalizedCopyRef | undefined => {
- if (!reason) return undefined;
- const trimmed = reason.trim();
- for (const { key, param, params, pattern } of REASON_PATTERNS) {
+/**
+ * The batch gate's blockers — the finite sentences `evaluateRolloutGate`
+ * withholds a wave for. A pattern break joins every blocker it hit with `; `,
+ * so each is mapped on its own and the parts rejoin.
+ */
+const BATCH_BLOCKER_PATTERNS: ReasonPattern[] = [
+ {
+ key: 'goalProcess.gate.reason.batchUnsettled',
+ params: ['count'],
+ pattern: /^(\d+) unit\(s\) have not settled$/,
+ },
+ {
+ key: 'goalProcess.gate.reason.batchBroken',
+ params: ['count'],
+ pattern: /^(\d+) unit\(s\) did not succeed$/,
+ },
+ {
+ key: 'goalProcess.gate.reason.batchOpenDecision',
+ pattern: /^a human decision is still open in this batch$/,
+ },
+ {
+ key: 'goalProcess.gate.reason.batchTemplateIncomplete',
+ pattern: /^the batch template is incomplete$/,
+ },
+ {
+ key: 'goalProcess.gate.reason.batchUntestedAxes',
+ params: ['axes'],
+ pattern: /^untested axes: (.+)$/,
+ },
+];
+
+interface ReasonPattern {
+ key: string;
+ param?: string;
+ /** Names for several capture groups, in order; `param` names just the first. */
+ params?: string[];
+ pattern: RegExp;
+}
+
+const matchReason = (patterns: ReasonPattern[], trimmed: string): LocalizedCopyRef | undefined => {
+ for (const { key, param, params, pattern } of patterns) {
const match = pattern.exec(trimmed);
if (!match) continue;
const names = params ?? (param ? [param] : []);
@@ -134,3 +173,28 @@ export const coordinatorReasonCopy = (reason?: string | null): LocalizedCopyRef
}
return undefined;
};
+
+export const coordinatorReasonCopy = (reason?: string | null): LocalizedCopyRef | undefined => {
+ if (!reason) return undefined;
+ const trimmed = reason.trim();
+ return matchReason(REASON_PATTERNS, trimmed) ?? matchReason(BATCH_BLOCKER_PATTERNS, trimmed);
+};
+
+/**
+ * Every coordinator reason in a stored gate question, in order. A batch gate
+ * lists each blocker it hit at once, joined by `; ` (see `evaluateRolloutGate`),
+ * so they are localized one by one and the parts rejoin — the reader sees no
+ * English left in the sentence. All-or-nothing: one unrecognized sentence means
+ * the question is not (fully) coordinator-authored, or an error message happened
+ * to contain `; `, so the stored copy is kept rather than half-translated.
+ */
+export const coordinatorReasonCopies = (reason?: string | null): LocalizedCopyRef[] | undefined => {
+ if (!reason) return undefined;
+ const trimmed = reason.trim();
+ const single = coordinatorReasonCopy(trimmed);
+ if (single) return [single];
+ const segments = trimmed.split(/;\s+/).filter(Boolean);
+ if (segments.length < 2) return undefined;
+ const refs = segments.map((segment) => coordinatorReasonCopy(segment));
+ return refs.every((ref): ref is LocalizedCopyRef => !!ref) ? refs : undefined;
+};
diff --git a/src/features/AgentGoals/Experiments/model.ts b/src/features/AgentGoals/Experiments/model.ts
index fa0d15f9709..04907e1748f 100644
--- a/src/features/AgentGoals/Experiments/model.ts
+++ b/src/features/AgentGoals/Experiments/model.ts
@@ -6,6 +6,16 @@ import type { GoalGraphView, GoalNodeView } from '../ProcessControl/goalGraphVie
export const isExperiment = (_graph: GoalGraphView, view: GoalNodeView) =>
view.node.kind === 'experiment';
+/**
+ * Container kinds fold their members and stand in for them when collapsed: an
+ * `experiment` (a candidate answer under test) and a `batch` (one repeated
+ * mould delivered as a class). Both are containment, not a second graph.
+ */
+export const isContainerKind = (kind: GoalNodeKind) => kind === 'experiment' || kind === 'batch';
+
+export const isContainer = (_graph: GoalGraphView, view: GoalNodeView) =>
+ isContainerKind(view.node.kind);
+
/** Provenance is independent of execution dependencies and retry attempts. */
export const experimentRelations = (graph: GoalGraphView, nodeId: string) => {
const parents = new Set<string>();
diff --git a/src/features/AgentGoals/GoalDecision/index.tsx b/src/features/AgentGoals/GoalDecision/index.tsx
index 4e0efec594f..93bcac0ad6e 100644
--- a/src/features/AgentGoals/GoalDecision/index.tsx
+++ b/src/features/AgentGoals/GoalDecision/index.tsx
@@ -1,8 +1,9 @@
'use client';
+import { GOAL_BATCH_BREAK_OPTION } from '@lobechat/const/goal';
import type { GoalDecisionOption } from '@lobechat/types';
import { Center, Flexbox, Icon } from '@lobehub/ui';
-import { Avatar, Text } from '@lobehub/ui/base-ui';
+import { Avatar, Text, toast } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
import { MonitorCog } from 'lucide-react';
import { type ReactNode, useCallback, useMemo, useState } from 'react';
@@ -15,10 +16,11 @@ import ClarificationQuestions, {
import {
coordinatorGateReason,
- coordinatorReasonCopy,
gateOptionLabelKey,
+ localizedCoordinatorReason,
} from '../ProcessControl/coordinatorCopy';
import {
+ gateAnswerProblem,
type GoalGateCategory,
type GoalGateDecision,
toGateAnswer,
@@ -119,6 +121,15 @@ export const useGateOptionCopy = () => {
case 'fail': {
return t('goalProcess.decision.effect.fail');
}
+ // A batch pattern break keeps only its option ids on the payload; the
+ // consequences are written here, in the reader's language, rather than
+ // persisted as English copy the server cannot translate.
+ case GOAL_BATCH_BREAK_OPTION.revise: {
+ return t('goalProcess.decision.effect.reviseBatch');
+ }
+ case GOAL_BATCH_BREAK_OPTION.newClass: {
+ return t('goalProcess.decision.effect.newClassBatch');
+ }
default: {
return undefined;
}
@@ -289,8 +300,8 @@ const GoalDecisionCase = ({
// The coordinator's English reason renders in the reader's language when
// recognized; an Agent's question is already in the goal's language.
const rawReason = coordinatorGateReason(decision.question) ?? decision.question;
- const reasonCopy = coordinatorReasonCopy(rawReason);
- const questionText = reasonCopy ? t(reasonCopy.key as any, reasonCopy.params) : rawReason;
+ // Every blocker of a compound batch reason, not just a single one.
+ const questionText = localizedCoordinatorReason(rawReason, t as any);
const basisText = basis && basis.trim() !== rawReason.trim() ? basis.trim() : undefined;
const questions = useMemo(
@@ -305,13 +316,23 @@ const GoalDecisionCase = ({
[basisText, category, decision, optionCopy, questionText],
);
+ // A batch break revises the recipe with the correction written here; without
+ // one the "revision" would re-run the plan that just failed.
+ const batchBreak = !!decision.options?.some(
+ (option) => option.id === GOAL_BATCH_BREAK_OPTION.revise,
+ );
+
const handleSubmit = useCallback(
async (answers: ClarificationAnswer[]) => {
const answer = toGateAnswer(decision, answers);
if (!answer) return;
+ if (gateAnswerProblem(answer) === 'correctionRequired') {
+ toast.error(t('goalProcess.gate.batchCorrectionRequired'));
+ return;
+ }
await onDecide(answer.optionId, answer.resolution?.trim() || undefined);
},
- [decision, onDecide],
+ [decision, onDecide, t],
);
// With links to lay beside it, the card owns the submit row: links on the
@@ -331,7 +352,11 @@ const GoalDecisionCase = ({
key={decision.id}
questions={questions}
submitLabel={t('goalProcess.decision.submit')}
- supplementPlaceholder={t('goalProcess.gate.notePlaceholder')}
+ supplementPlaceholder={t(
+ batchBreak
+ ? 'goalProcess.gate.batchCorrectionPlaceholder'
+ : 'goalProcess.gate.notePlaceholder',
+ )}
onSubmit={handleSubmit}
/>
) : (
diff --git a/src/features/AgentGoals/GoalDecision/mapping.test.ts b/src/features/AgentGoals/GoalDecision/mapping.test.ts
index b310ca05743..41661b1420e 100644
--- a/src/features/AgentGoals/GoalDecision/mapping.test.ts
+++ b/src/features/AgentGoals/GoalDecision/mapping.test.ts
@@ -5,7 +5,7 @@ import {
} from '@lobechat/const/goal';
import { describe, expect, it } from 'vitest';
-import { goalGateCategory, toGateAnswer, toGateQuestion } from './mapping';
+import { gateAnswerProblem, goalGateCategory, toGateAnswer, toGateQuestion } from './mapping';
const recover = [
{ id: 'retry', label: 'Retry task' },
@@ -117,3 +117,16 @@ describe('toGateAnswer', () => {
).toEqual({ optionId: 'all', resolution: 'Both, desktop first' });
});
});
+
+describe('gateAnswerProblem', () => {
+ it('requires a correction to revise a batch recipe', () => {
+ expect(gateAnswerProblem({ optionId: 'revise' })).toBe('correctionRequired');
+ expect(gateAnswerProblem({ optionId: 'revise', resolution: ' ' })).toBe('correctionRequired');
+ expect(gateAnswerProblem({ optionId: 'revise', resolution: '补上冷启动' })).toBeUndefined();
+ });
+
+ it('leaves every other answer alone', () => {
+ expect(gateAnswerProblem({ optionId: 'new_class' })).toBeUndefined();
+ expect(gateAnswerProblem({ optionId: 'retry' })).toBeUndefined();
+ });
+});
diff --git a/src/features/AgentGoals/GoalDecision/mapping.ts b/src/features/AgentGoals/GoalDecision/mapping.ts
index 2f000a2876c..60ba50b4413 100644
--- a/src/features/AgentGoals/GoalDecision/mapping.ts
+++ b/src/features/AgentGoals/GoalDecision/mapping.ts
@@ -1,4 +1,5 @@
import {
+ GOAL_BATCH_BREAK_OPTION,
GOAL_CLARIFICATION_OPTION,
GOAL_CLARIFICATION_TITLE,
GOAL_MACHINE_GATE_TITLE,
@@ -102,3 +103,16 @@ export const toGateAnswer = (
const option = optionForWrittenAnswer(decision.options ?? [], decision.recommendedOptionId);
return option ? { optionId: option.id, resolution: answer.text } : undefined;
};
+
+/**
+ * An answer the gate cannot take as is. Revising a batch recipe without saying
+ * what to change would re-run the plan that just failed under a new version,
+ * so the correction is required there (the server refuses it too).
+ */
+export const gateAnswerProblem = (answer: {
+ optionId: string;
+ resolution?: string;
+}): 'correctionRequired' | undefined =>
+ answer.optionId === GOAL_BATCH_BREAK_OPTION.revise && !answer.resolution?.trim()
+ ? 'correctionRequired'
+ : undefined;
diff --git a/src/features/AgentGoals/ProcessControl/BatchGate/GateDetail.tsx b/src/features/AgentGoals/ProcessControl/BatchGate/GateDetail.tsx
new file mode 100644
index 00000000000..cd35cf5349b
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/BatchGate/GateDetail.tsx
@@ -0,0 +1,345 @@
+import { Flexbox, Icon } from '@lobehub/ui';
+import { Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import dayjs from 'dayjs';
+import { CircleCheck, CircleDashed, CircleX } from 'lucide-react';
+import { memo, type ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import GoalDecisionCase from '../../GoalDecision';
+import type { GoalGraphView } from '../goalGraphViewModel';
+import { CELL_VISUAL } from '../Graph/BatchGroups';
+import {
+ batchCellState,
+ type BatchGateState,
+ type BatchModel,
+ type BatchRound,
+ verdictChecks,
+} from '../Graph/batchModel';
+import { KIND_COLOR, KIND_ICON } from '../shared';
+import { activateProps } from './activateProps';
+import { type GateCheckLike, useGateCheckCopy } from './useGateCheckCopy';
+
+/**
+ * What a release gate actually decided, for the panel that opens on it.
+ *
+ * The gate is not a person's decision: the coordinator judges it on its own
+ * each time a round's units settle. So the panel leads with the verdict and
+ * what happens next, then the checks of the latest verdict with the units
+ * behind any that failed, then every verdict this round took.
+ */
+
+const styles = createStaticStyles(({ css }) => ({
+ check: css`
+ padding-block: 6px;
+
+ & + & {
+ border-block-start: 1px dashed ${cssVar.colorBorderSecondary};
+ }
+ `,
+ label: css`
+ font-size: 12px;
+ font-weight: 600;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ /* A unit behind a failed check, as the card it is on the map — not a line of text. */
+ unitCard: css`
+ cursor: pointer;
+
+ padding-block: 8px;
+ padding-inline: 10px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+
+ background: ${cssVar.colorBgContainer};
+
+ transition: border-color 0.15s;
+
+ &:hover {
+ border-color: ${cssVar.colorBorder};
+ }
+ `,
+ unitGlyph: css`
+ display: flex;
+ flex: none;
+ align-items: center;
+ justify-content: center;
+
+ width: 26px;
+ height: 26px;
+ border-radius: 6px;
+ `,
+ mono: css`
+ font-family: ${cssVar.fontFamilyCode};
+ font-variant-numeric: tabular-nums;
+ `,
+}));
+
+const GATE_VISUAL: Record<BatchGateState, (typeof CELL_VISUAL)[keyof typeof CELL_VISUAL]> = {
+ checking: CELL_VISUAL.running,
+ human: CELL_VISUAL.human,
+ locked: CELL_VISUAL.backlog,
+ passed: CELL_VISUAL.done,
+ rejected: CELL_VISUAL.stale,
+};
+
+const Section = memo<{ children: ReactNode; extra?: ReactNode; title: string }>(
+ ({ children, extra, title }) => (
+ <Flexbox gap={6}>
+ <Flexbox horizontal align={'baseline'} gap={8} justify={'space-between'}>
+ <span className={styles.label}>{title}</span>
+ {extra}
+ </Flexbox>
+ {children}
+ </Flexbox>
+ ),
+);
+
+Section.displayName = 'GoalGateDetailSection';
+
+interface GateDetailProps {
+ /** Answer the gate's open decision; absent where the reader cannot answer. */
+ decide?: (decisionId: string, optionId: string, resolution?: string) => Promise<unknown>;
+ graph: GoalGraphView;
+ model: BatchModel;
+ onOpenNode: (nodeId: string) => void;
+ round: BatchRound;
+}
+
+const GateDetail = memo<GateDetailProps>(({ decide, graph, model, onOpenNode, round }) => {
+ const { t } = useTranslation('chat');
+ const copy = useGateCheckCopy();
+ const visual = GATE_VISUAL[round.gate];
+ const evaluations = round.evaluations;
+ const latest = evaluations.at(-1);
+ const lastRelease = evaluations.findLast((item) => item.outcome === 'released');
+ const isCurrent = model.rounds.at(-1) === round;
+
+ const next = (() => {
+ switch (round.gate) {
+ case 'locked': {
+ return t('goalBatch.gatePanel.next.locked', { count: round.probes.length });
+ }
+ case 'checking': {
+ return t('goalBatch.gatePanel.next.checking');
+ }
+ case 'human': {
+ return t('goalBatch.gatePanel.next.human');
+ }
+ case 'rejected': {
+ return t('goalBatch.gatePanel.next.rejected', { revision: round.revision + 1 });
+ }
+ default: {
+ if (isCurrent && model.phase === 'done') return t('goalBatch.gatePanel.next.passedDone');
+ return lastRelease
+ ? t('goalBatch.gatePanel.next.passed', {
+ count: lastRelease.releasedCount ?? 0,
+ wave: lastRelease.wave ?? lastRelease.waveIndex,
+ })
+ : undefined;
+ }
+ }
+ })();
+
+ // A gate that visibly judged but left no record decided before verdicts were
+ // kept — say so, rather than presenting it as never judged.
+ const unrecorded = !latest && round.gate !== 'locked' && round.gate !== 'checking';
+ // The latest verdict's checks, or — before any — the ones it will run.
+ const checks: GateCheckLike[] = latest
+ ? verdictChecks(latest)
+ : unrecorded
+ ? []
+ : model.gateChecks;
+
+ const superseded = new Set(
+ graph.edges.filter((edge) => edge.kind === 'derived_from').map((edge) => edge.targetNodeId),
+ );
+ const unitCard = (nodeId: string) => {
+ const view = graph.byId[nodeId];
+ if (!view) return null;
+ const kind = view.node.kind === 'decision' ? 'decision' : 'task';
+ // Same reading as the squares: a unit a later round re-opened is superseded.
+ const state = superseded.has(nodeId) ? 'stale' : batchCellState(view, new Set());
+ const status = CELL_VISUAL[state];
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.unitCard}
+ data-unit={nodeId}
+ gap={8}
+ key={nodeId}
+ {...activateProps(() => onOpenNode(nodeId))}
+ onClick={() => onOpenNode(nodeId)}
+ >
+ <span
+ className={styles.unitGlyph}
+ style={{ background: KIND_COLOR[kind].soft, color: KIND_COLOR[kind].line }}
+ >
+ <Icon icon={KIND_ICON[kind]} size={14} />
+ </span>
+ <Text ellipsis fontSize={13} style={{ flex: 1, minWidth: 0 }} weight={500}>
+ {view.node.title}
+ </Text>
+ {kind === 'task' && (
+ <Flexbox horizontal align={'center'} gap={4} style={{ flex: 'none' }}>
+ <Icon color={status.color} icon={status.icon} size={13} />
+ <Text fontSize={12} style={{ color: status.color }}>
+ {t(`goalBatch.cell.${state}` as const)}
+ </Text>
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+ };
+
+ // The gate is waiting on a person: answer it here, beside what it found.
+ const pending = round.assayId ? graph.byId[round.assayId]?.decision : undefined;
+
+ return (
+ <Flexbox data-gate-detail gap={16}>
+ {/* Waiting on a person, the question itself leads: no verdict line and no
+ section label repeating "needs your decision" above it. */}
+ {pending && decide ? (
+ <GoalDecisionCase
+ hideAsker
+ category={'judgment'}
+ decision={{ ...pending, question: t('goalBatch.gatePanel.question') }}
+ onDecide={(optionId, resolution) => decide(pending.id, optionId, resolution)}
+ />
+ ) : (
+ <Section title={t('goalBatch.gatePanel.verdict')}>
+ <Flexbox horizontal align={'center'} gap={6}>
+ <Icon color={visual.color} icon={visual.icon} size={14} />
+ <Text fontSize={13} style={{ color: visual.color }}>
+ {t(`goalBatch.gate.status.${round.gate}` as const)}
+ </Text>
+ </Flexbox>
+ {next && (
+ <Text fontSize={13} type={'secondary'}>
+ {next}
+ </Text>
+ )}
+ </Section>
+ )}
+
+ <Section
+ title={t('goalBatch.gatePanel.checks')}
+ extra={
+ <Text className={styles.mono} fontSize={11} type={'secondary'}>
+ {latest
+ ? latest.seq
+ ? t('goalBatch.gatePanel.checksAt', {
+ index: latest.seq,
+ time: dayjs(latest.at).format('MM-DD HH:mm'),
+ })
+ : dayjs(latest.at).format('MM-DD HH:mm')
+ : unrecorded
+ ? undefined
+ : t('goalBatch.gatePanel.checksPlanned')}
+ </Text>
+ }
+ >
+ {unrecorded && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('goalBatch.gatePanel.history.unrecorded')}
+ </Text>
+ )}
+ <Flexbox gap={0}>
+ {checks.map((check, index) => {
+ const { detail, label } = copy(check);
+ const state = check.passed === undefined ? 'planned' : check.passed ? 'pass' : 'fail';
+ const icon = state === 'pass' ? CircleCheck : state === 'fail' ? CircleX : CircleDashed;
+ const color =
+ state === 'pass'
+ ? CELL_VISUAL.done.color
+ : state === 'fail'
+ ? cssVar.colorError
+ : cssVar.colorTextQuaternary;
+ return (
+ <Flexbox
+ className={styles.check}
+ data-check={check.key}
+ data-state={state}
+ gap={4}
+ key={index}
+ >
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Icon color={color} icon={icon} size={14} />
+ <Text fontSize={13} style={{ flex: 1, minWidth: 0 }}>
+ {label}
+ </Text>
+ {detail && (
+ <Text className={styles.mono} fontSize={12} type={'secondary'}>
+ {detail}
+ </Text>
+ )}
+ </Flexbox>
+ {!check.passed && check.nodeIds?.length ? (
+ <Flexbox gap={6} paddingInline={'22px 0'}>
+ {check.nodeIds.map(unitCard)}
+ </Flexbox>
+ ) : null}
+ </Flexbox>
+ );
+ })}
+ </Flexbox>
+ </Section>
+
+ {/* An unrecorded gate already said so under its checks. */}
+ {!unrecorded && (
+ <Section title={t('goalBatch.gatePanel.history')}>
+ {evaluations.length === 0 ? (
+ <Text fontSize={12} type={'secondary'}>
+ {t('goalBatch.gatePanel.history.empty')}
+ </Text>
+ ) : (
+ <Flexbox gap={6}>
+ {[...evaluations].reverse().map((evaluation) => {
+ const failed = verdictChecks(evaluation)
+ .filter((check) => !check.passed)
+ .map((check) => copy(check).label);
+ const text =
+ evaluation.outcome === 'released'
+ ? t('goalBatch.gatePanel.history.released', {
+ count: evaluation.releasedCount ?? 0,
+ wave: evaluation.wave ?? evaluation.waveIndex,
+ })
+ : evaluation.trigger === 'unit'
+ ? t('goalBatch.gatePanel.history.unit', {
+ title: graph.byId[evaluation.nodeId ?? '']?.node.title ?? '',
+ })
+ : t('goalBatch.gatePanel.history.blocked', { checks: failed.join(';') });
+ const passed = evaluation.outcome === 'released';
+ return (
+ <Flexbox horizontal align={'baseline'} gap={10} key={evaluation.at}>
+ <Icon
+ color={passed ? CELL_VISUAL.done.color : cssVar.colorError}
+ icon={passed ? CircleCheck : CircleX}
+ size={12}
+ />
+ <Text fontSize={12} style={{ flex: 1, minWidth: 0 }}>
+ {text}
+ </Text>
+ <Text
+ className={styles.mono}
+ fontSize={12}
+ style={{ flex: 'none' }}
+ type={'secondary'}
+ >
+ {dayjs(evaluation.at).format('MM-DD HH:mm')}
+ </Text>
+ </Flexbox>
+ );
+ })}
+ </Flexbox>
+ )}
+ </Section>
+ )}
+ </Flexbox>
+ );
+});
+
+GateDetail.displayName = 'GoalBatchGateDetail';
+
+export default GateDetail;
diff --git a/src/features/AgentGoals/ProcessControl/BatchGate/activateProps.test.ts b/src/features/AgentGoals/ProcessControl/BatchGate/activateProps.test.ts
new file mode 100644
index 00000000000..41f0a4ceb55
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/BatchGate/activateProps.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { activateProps } from './activateProps';
+
+const press = (key: string) => ({ key, preventDefault: vi.fn() });
+
+describe('activateProps', () => {
+ it('makes the card focusable and opens it on Enter or Space', () => {
+ const onActivate = vi.fn();
+ const props = activateProps(onActivate);
+ expect(props).toMatchObject({ role: 'button', tabIndex: 0 });
+
+ const enter = press('Enter');
+ props.onKeyDown(enter);
+ props.onKeyDown(press(' '));
+ expect(onActivate).toHaveBeenCalledTimes(2);
+ // Space must not also scroll the panel.
+ expect(enter.preventDefault).toHaveBeenCalled();
+ });
+
+ it('ignores other keys', () => {
+ const onActivate = vi.fn();
+ const tab = press('Tab');
+ activateProps(onActivate).onKeyDown(tab);
+ expect(onActivate).not.toHaveBeenCalled();
+ expect(tab.preventDefault).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/AgentGoals/ProcessControl/BatchGate/activateProps.ts b/src/features/AgentGoals/ProcessControl/BatchGate/activateProps.ts
new file mode 100644
index 00000000000..151b27e5dd0
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/BatchGate/activateProps.ts
@@ -0,0 +1,15 @@
+import type { KeyboardEvent } from 'react';
+
+/**
+ * What a non-native button needs to work from the keyboard: it takes focus, and
+ * Enter or Space activates it the way a click does.
+ */
+export const activateProps = (onActivate: () => void) => ({
+ onKeyDown: (event: Pick<KeyboardEvent, 'key' | 'preventDefault'>) => {
+ if (event.key !== 'Enter' && event.key !== ' ') return;
+ event.preventDefault();
+ onActivate();
+ },
+ role: 'button' as const,
+ tabIndex: 0,
+});
diff --git a/src/features/AgentGoals/ProcessControl/BatchGate/useGateCheckCopy.ts b/src/features/AgentGoals/ProcessControl/BatchGate/useGateCheckCopy.ts
new file mode 100644
index 00000000000..348bde5bd70
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/BatchGate/useGateCheckCopy.ts
@@ -0,0 +1,30 @@
+import type { GoalRolloutGateCheck, GoalRolloutGateCheckKey } from '@lobechat/types';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+/** A check as the gate will run it, or as a verdict recorded it. */
+export type GateCheckLike = Partial<Omit<GoalRolloutGateCheck, 'key'>> & {
+ key: GoalRolloutGateCheckKey;
+};
+
+/** What one gate check is called, and what it found when a verdict recorded it. */
+export const useGateCheckCopy = () => {
+ const { t } = useTranslation('chat');
+ return useCallback(
+ (check: GateCheckLike): { detail?: string; label: string } => {
+ const label = t(`goalBatch.gateCheck.${check.key}` as const);
+ if (check.key === 'axes_covered' && check.details?.length)
+ return {
+ detail: t('goalBatch.gateCheck.uncovered', { values: check.details.join('、') }),
+ label,
+ };
+ if (check.count !== undefined && check.total !== undefined)
+ return {
+ detail: t('goalBatch.gateCheck.count', { count: check.count, total: check.total }),
+ label,
+ };
+ return { label };
+ },
+ [t],
+ );
+};
diff --git a/src/features/AgentGoals/ProcessControl/BatchPlan/PlanDetail.tsx b/src/features/AgentGoals/ProcessControl/BatchPlan/PlanDetail.tsx
new file mode 100644
index 00000000000..1e18f814e11
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/BatchPlan/PlanDetail.tsx
@@ -0,0 +1,167 @@
+import { Flexbox, Markdown } from '@lobehub/ui';
+import { Segmented, Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { memo, type ReactNode, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { GoalGraphView } from '../goalGraphViewModel';
+import type { BatchModel, BatchRound } from '../Graph/batchModel';
+import { planDiff } from './planDiff';
+
+/**
+ * Every version of a batch's plan, for the panel that opens on one of them:
+ * pick a version, pick what to compare it with (the previous one by default),
+ * read the line diff, then the version in full.
+ */
+
+const styles = createStaticStyles(({ css }) => ({
+ diff: css`
+ overflow: hidden;
+
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 12px;
+ line-height: 1.7;
+ `,
+ line: css`
+ padding-inline: 10px;
+ white-space: pre-wrap;
+ `,
+ added: css`
+ color: ${cssVar.colorSuccessText};
+ background: ${cssVar.colorSuccessBg};
+ `,
+ removed: css`
+ color: ${cssVar.colorErrorText};
+ text-decoration: line-through;
+ background: ${cssVar.colorErrorBg};
+ `,
+ same: css`
+ color: ${cssVar.colorTextTertiary};
+ `,
+ label: css`
+ font-size: 12px;
+ font-weight: 600;
+ color: ${cssVar.colorTextSecondary};
+ `,
+}));
+
+const Section = memo<{ children: ReactNode; title: string }>(({ children, title }) => (
+ <Flexbox gap={6}>
+ <span className={styles.label}>{title}</span>
+ {children}
+ </Flexbox>
+));
+
+Section.displayName = 'GoalPlanDetailSection';
+
+const MARK = { added: '+ ', removed: '− ', same: ' ' } as const;
+
+interface PlanDetailProps {
+ graph: GoalGraphView;
+ model: BatchModel;
+ round: BatchRound;
+}
+
+const PlanDetail = memo<PlanDetailProps>(({ graph, model, round }) => {
+ const { t } = useTranslation('chat');
+ const versions = model.rounds.filter((item) => item.templateId);
+ const [selected, setSelected] = useState(round.revision);
+ const [base, setBase] = useState<number | undefined>(undefined);
+
+ const current = versions.find((item) => item.revision === selected) ?? round;
+ const earlier = versions.filter((item) => item.revision < current.revision);
+ // Compare with the previous version unless the reader picked another.
+ const against = earlier.find((item) => item.revision === base) ?? earlier.at(-1);
+ const textOf = (item?: BatchRound) =>
+ (item?.templateId && graph.byId[item.templateId]?.node.description) || '';
+
+ const lines = against ? planDiff(textOf(against), textOf(current)) : [];
+ const changed = lines.some((line) => line.kind !== 'same');
+
+ return (
+ <Flexbox data-plan-detail gap={16}>
+ {versions.length > 1 && (
+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>
+ <span className={styles.label}>{t('goalBatch.planPanel.version')}</span>
+ <Segmented
+ size={'small'}
+ value={String(current.revision)}
+ options={versions.map((item) => ({
+ label: `v${item.revision}`,
+ value: String(item.revision),
+ }))}
+ onChange={(value) => {
+ setSelected(Number(value));
+ setBase(undefined);
+ }}
+ />
+ {earlier.length > 1 && (
+ <>
+ <span className={styles.label}>{t('goalBatch.planPanel.compare')}</span>
+ <Segmented
+ size={'small'}
+ value={against ? String(against.revision) : undefined}
+ options={earlier.map((item) => ({
+ label: `v${item.revision}`,
+ value: String(item.revision),
+ }))}
+ onChange={(value) => setBase(Number(value))}
+ />
+ </>
+ )}
+ </Flexbox>
+ )}
+
+ {current.forked && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('goalBatch.planPanel.forked')}
+ </Text>
+ )}
+
+ {against ? (
+ <Section
+ title={t('goalBatch.planPanel.diff', {
+ base: against.revision,
+ revision: current.revision,
+ })}
+ >
+ {changed ? (
+ <div data-plan-diff className={styles.diff}>
+ {lines.map((line, index) => (
+ <div
+ className={cx(styles.line, styles[line.kind])}
+ data-diff={line.kind}
+ key={index}
+ >
+ {MARK[line.kind]}
+ {line.text}
+ </div>
+ ))}
+ </div>
+ ) : (
+ <Text fontSize={12} type={'secondary'}>
+ {t('goalBatch.planPanel.same', { base: against.revision })}
+ </Text>
+ )}
+ </Section>
+ ) : (
+ <Text fontSize={12} type={'secondary'}>
+ {t('goalBatch.planPanel.first')}
+ </Text>
+ )}
+
+ <Section title={t('goalBatch.planPanel.full', { revision: current.revision })}>
+ <Markdown fontSize={13} style={{ flexShrink: 0 }} variant={'chat'}>
+ {textOf(current)}
+ </Markdown>
+ </Section>
+ </Flexbox>
+ );
+});
+
+PlanDetail.displayName = 'GoalBatchPlanDetail';
+
+export default PlanDetail;
diff --git a/src/features/AgentGoals/ProcessControl/BatchPlan/planDiff.test.ts b/src/features/AgentGoals/ProcessControl/BatchPlan/planDiff.test.ts
new file mode 100644
index 00000000000..2da76b69de4
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/BatchPlan/planDiff.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from 'vitest';
+
+import { planDiff } from './planDiff';
+
+describe('planDiff', () => {
+ it('reads a revision as the previous plan unchanged plus its own section', () => {
+ expect(planDiff('Step one\nStep two', 'Step one\nStep two\n\n### v2\nSeed first')).toEqual([
+ { kind: 'same', text: 'Step one' },
+ { kind: 'same', text: 'Step two' },
+ { kind: 'added', text: '' },
+ { kind: 'added', text: '### v2' },
+ { kind: 'added', text: 'Seed first' },
+ ]);
+ });
+
+ it('marks a line the new version dropped as removed', () => {
+ expect(planDiff('Keep\nDrop', 'Keep')).toEqual([
+ { kind: 'same', text: 'Keep' },
+ { kind: 'removed', text: 'Drop' },
+ ]);
+ });
+});
diff --git a/src/features/AgentGoals/ProcessControl/BatchPlan/planDiff.ts b/src/features/AgentGoals/ProcessControl/BatchPlan/planDiff.ts
new file mode 100644
index 00000000000..0523c06a2ae
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/BatchPlan/planDiff.ts
@@ -0,0 +1,28 @@
+import { diffLines } from 'diff';
+
+export interface PlanDiffLine {
+ kind: 'added' | 'removed' | 'same';
+ text: string;
+}
+
+/**
+ * Line-level difference between two versions of a batch plan. A revision
+ * carries the previous plan forward and appends its own section, so the usual
+ * result is the earlier text unchanged and the new section added.
+ */
+export const planDiff = (before = '', after = ''): PlanDiffLine[] =>
+ // Both sides end with a newline, or a last line followed by new text would
+ // read as changed rather than kept.
+ diffLines(`${before.trim()}\n`, `${after.trim()}\n`).flatMap((part) =>
+ part.value
+ .replace(/\n$/, '')
+ .split('\n')
+ .map((text) => ({
+ kind: part.added
+ ? ('added' as const)
+ : part.removed
+ ? ('removed' as const)
+ : ('same' as const),
+ text,
+ })),
+ );
diff --git a/src/features/AgentGoals/ProcessControl/Frontier.tsx b/src/features/AgentGoals/ProcessControl/Frontier.tsx
index b26dea98b4c..aac33504031 100644
--- a/src/features/AgentGoals/ProcessControl/Frontier.tsx
+++ b/src/features/AgentGoals/ProcessControl/Frontier.tsx
@@ -24,7 +24,7 @@ import AssigneeProfileAvatar from './AssigneeProfileAvatar';
import {
coordinatorGateReason,
coordinatorNodeTitleKey,
- coordinatorReasonCopy,
+ coordinatorReasonCopies,
viewGateKind,
} from './coordinatorCopy';
import type { FrontierItem, GoalGraphView, GoalNodeView } from './goalGraphViewModel';
@@ -185,10 +185,10 @@ RowGlyph.displayName = 'GoalFrontierRowGlyph';
const AttemptReason = memo<{ reason?: string | null }>(({ reason }) => {
const { t } = useTranslation('chat');
- const copy = coordinatorReasonCopy(reason);
+ const copies = coordinatorReasonCopies(reason);
return (
<Text ellipsis fontSize={12} style={{ flex: 1, minWidth: 0 }} type={'secondary'}>
- {copy ? t(copy.key as any, copy.params) : (reason ?? '')}
+ {copies ? copies.map((copy) => t(copy.key as any, copy.params)).join('; ') : (reason ?? '')}
</Text>
);
});
@@ -453,9 +453,9 @@ const FrontierRow = memo<{
const coordinatorTitleKey = coordinatorNodeTitleKey(view);
const gateKind = item.kind === 'gate' ? viewGateKind(view) : undefined;
const rawGateReason = gateKind ? coordinatorGateReason(view.decision?.question) : undefined;
- const gateReasonCopy = coordinatorReasonCopy(rawGateReason);
- const gateReasonText = gateReasonCopy
- ? t(gateReasonCopy.key as any, gateReasonCopy.params)
+ const gateReasonCopies = coordinatorReasonCopies(rawGateReason);
+ const gateReasonText = gateReasonCopies
+ ? gateReasonCopies.map((copy) => t(copy.key as any, copy.params)).join('; ')
: rawGateReason;
// Gate rows carry no tag: the expanded card with its action buttons already
diff --git a/src/features/AgentGoals/ProcessControl/GoalResultFollowUps.tsx b/src/features/AgentGoals/ProcessControl/GoalResultFollowUps.tsx
index 242b1e2e650..db0a4c08310 100644
--- a/src/features/AgentGoals/ProcessControl/GoalResultFollowUps.tsx
+++ b/src/features/AgentGoals/ProcessControl/GoalResultFollowUps.tsx
@@ -14,8 +14,8 @@ import { createGoalModal } from '../CreateGoalModal';
import {
coordinatorGateKind,
coordinatorGateReason,
- coordinatorReasonCopy,
gateTitleKey,
+ localizedCoordinatorReason,
} from './coordinatorCopy';
import { pickFinalDeliverable } from './goalAcceptanceReport';
import type { GoalGraphView } from './goalGraphViewModel';
@@ -95,7 +95,6 @@ const useDecisionCopy = (graph: GoalGraphView) => {
const subjectId = graph.byId[decision.nodeId]?.gateSubjectId;
const subject = subjectId ? graph.byId[subjectId]?.node.title : undefined;
const rawReason = coordinatorGateReason(decision.question);
- const reasonCopy = coordinatorReasonCopy(rawReason);
const optionId = decision.resolvedOptionId;
const choice =
optionId === 'retry' || optionId === 'retire' || optionId === 'fail'
@@ -104,7 +103,7 @@ const useDecisionCopy = (graph: GoalGraphView) => {
return {
choice,
- detail: reasonCopy ? t(reasonCopy.key as any, reasonCopy.params) : rawReason,
+ detail: localizedCoordinatorReason(rawReason, t as any),
question: subject
? `${t(gateTitleKey(kind) as any)} · ${subject}`
: t(gateTitleKey(kind) as any),
diff --git a/src/features/AgentGoals/ProcessControl/Graph/BatchGroups.tsx b/src/features/AgentGoals/ProcessControl/Graph/BatchGroups.tsx
new file mode 100644
index 00000000000..eb5a91db8a9
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/Graph/BatchGroups.tsx
@@ -0,0 +1,763 @@
+'use client';
+
+import { Flexbox, Icon, Tooltip } from '@lobehub/ui';
+import { Button } from '@lobehub/ui/base-ui';
+import { Handle, type NodeProps, Position } from '@xyflow/react';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import {
+ CircleCheck,
+ CircleDashed,
+ CircleDot,
+ CircleSlash,
+ HandIcon,
+ Info,
+ type LucideIcon,
+ TestTubeDiagonal,
+ Waves,
+} from 'lucide-react';
+import { memo, type ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { TASK_STATUS_VISUALS } from '@/components/ExecutionStatus';
+
+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 {
+ type BatchCell,
+ type BatchCellState,
+ type BatchProbe,
+ type BatchUnitOrigin,
+ countCells,
+ reopenedRows,
+} from './batchModel';
+
+/**
+ * The expanded batch, drawn the way it is followed and with no frame of its
+ * own: the first round's trials (an experiment probe) as task cards, the roster as waves of squares, and a
+ * small re-dispatch group per re-opened round. Squares carry the canonical
+ * execution states — grey not run, amber running (breathing), blue needs a
+ * person, green done, faded superseded.
+ */
+
+/**
+ * Done is the design-system green at full strength: `green9` is `#379d4a` in
+ * light and `#62c473` in dark. `colorSuccess` turns lime on dark, and the
+ * softer `green10` the finding kind uses reads washed out on a small square.
+ */
+const DONE_COLOR = cssVar.green9;
+
+export const CELL_VISUAL: Record<BatchCellState, { color: string; icon: LucideIcon }> = {
+ backlog: { color: TASK_STATUS_VISUALS.backlog.color, icon: CircleDashed },
+ done: { color: DONE_COLOR, icon: CircleCheck },
+ human: { color: TASK_STATUS_VISUALS.paused.color, icon: HandIcon },
+ running: { color: TASK_STATUS_VISUALS.running.color, icon: CircleDot },
+ stale: { color: TASK_STATUS_VISUALS.backlog.color, icon: CircleSlash },
+};
+
+const styles = createStaticStyles(({ css }) => ({
+ breathe: css`
+ animation: goal-batch-breathe 1.6s ease-in-out infinite;
+
+ @keyframes goal-batch-breathe {
+ 0%,
+ 100% {
+ transform: scale(1);
+ opacity: 1;
+ }
+
+ 50% {
+ transform: scale(0.86);
+ opacity: 0.42;
+ }
+ }
+
+ @media (prefers-reduced-motion: reduce) {
+ animation: none;
+ }
+ `,
+ card: css`
+ cursor: pointer;
+
+ box-sizing: border-box;
+ width: 100%;
+ padding-block: 7px;
+ padding-inline: 9px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+
+ background: ${cssVar.colorBgContainer};
+
+ transition: border-color 0.15s;
+
+ &:hover {
+ border-color: ${cssVar.colorBorder};
+ }
+ `,
+ cardTitle: css`
+ overflow: hidden;
+
+ font-size: 12px;
+ font-weight: 500;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ foot: css`
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ align-items: center;
+
+ padding-block: 6px;
+ padding-inline: 10px;
+
+ font-size: 11px;
+ `,
+ glyph: css`
+ display: flex;
+ flex: none;
+ align-items: center;
+ justify-content: center;
+
+ width: 24px;
+ height: 24px;
+ border-radius: 6px;
+ `,
+ group: css`
+ box-sizing: border-box;
+ width: 100%;
+ border: 1px solid ${cssVar.colorBorder};
+ border-radius: 12px;
+
+ /* White on light like every card; the header rule separates it, not a grey fill. */
+ background: ${cssVar.colorBgContainer};
+ `,
+ /* A label row, not a title bar: no fill, no rule, the body carries the weight. */
+ groupHead: css`
+ display: flex;
+ gap: 8px;
+ align-items: center;
+ justify-content: space-between;
+
+ padding-block: 8px;
+ padding-inline: 10px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 12px 12px 0 0;
+
+ background: ${cssVar.colorBgContainer};
+ `,
+ groupTitle: css`
+ font-size: 13px;
+ font-weight: 600;
+ white-space: nowrap;
+ `,
+ /* Trials: one row of two cards, status above each card. */
+ probeGrid: css`
+ display: flex;
+ flex-wrap: wrap;
+ gap: 7px;
+
+ padding-block: 8px 4px;
+ padding-inline: 10px;
+ `,
+ probeCell: css`
+ display: flex;
+ flex: 1 1 calc(50% - 4px);
+ flex-direction: column;
+ gap: 4px;
+
+ min-width: 0;
+ `,
+ /* A round's frame: a quiet container, the cards inside carry the weight. */
+ frame: css`
+ box-sizing: border-box;
+ width: 100%;
+ height: 100%;
+ border: 1px dashed ${cssVar.colorBorder};
+ border-radius: 16px;
+
+ background: ${cssVar.colorFillQuaternary};
+ `,
+ frameHead: css`
+ display: flex;
+ align-items: center;
+
+ height: ${BATCH_FRAME_HEAD}px;
+ padding-inline: 14px;
+
+ font-size: 13px;
+ font-weight: 600;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ /* Waves: row gap equals square gap, so the roster reads as a grid. */
+ wavesBody: css`
+ display: flex;
+ flex-direction: column;
+ gap: ${BATCH_SQUARE_GAP}px;
+
+ padding-block: 8px 4px;
+ padding-inline: 10px;
+ `,
+ hint: css`
+ cursor: help;
+ display: inline-flex;
+ color: ${cssVar.colorTextTertiary};
+
+ &:hover {
+ color: ${cssVar.colorTextSecondary};
+ }
+ `,
+ handle: css`
+ width: 1px;
+ min-width: 0;
+ height: 1px;
+ min-height: 0;
+ border: none;
+
+ opacity: 0;
+ `,
+ muted: css`
+ font-size: 11px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ rowLabel: css`
+ flex: none;
+
+ width: ${BATCH_ROW_LABEL}px;
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 10px;
+ line-height: 1;
+ color: ${cssVar.colorTextTertiary};
+ white-space: nowrap;
+ `,
+ rowLabelHot: css`
+ font-weight: 700;
+ color: ${cssVar.colorWarning};
+ `,
+ square: css`
+ cursor: default;
+
+ display: inline-block;
+ flex: none;
+
+ width: ${BATCH_SQUARE}px;
+ height: ${BATCH_SQUARE}px;
+ padding: 0;
+ border: none;
+ border-radius: 3px;
+ `,
+ squareLink: css`
+ cursor: pointer;
+ `,
+ status: css`
+ display: inline-flex;
+ gap: 5px;
+ align-items: center;
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 11px;
+ `,
+}));
+
+const squareStyle = (state: BatchCellState) => {
+ switch (state) {
+ case 'human': {
+ return {
+ background: CELL_VISUAL.human.color,
+ boxShadow: `0 0 0 3px color-mix(in srgb, ${CELL_VISUAL.human.color} 22%, transparent)`,
+ };
+ }
+ case 'stale': {
+ return { background: cssVar.colorTextQuaternary, opacity: 0.38 };
+ }
+ default: {
+ return { background: CELL_VISUAL[state].color };
+ }
+ }
+};
+
+/**
+ * Stages sit top-aligned in one row but differ in height, so their side
+ * handles share one height from the top — the hand-off lines stay straight.
+ */
+const STAGE_HANDLE_TOP = 19;
+
+/**
+ * Groups link like any card on the map — in at the top, out at the bottom — and
+ * a waves group can also hand a re-opened round off to the side (`r`).
+ */
+const GroupHandles = () => (
+ <>
+ <Handle className={styles.handle} isConnectable={false} position={Position.Top} type="target" />
+ {/* Stages hand off left to right: in on the left, out on the right. */}
+ <Handle
+ className={styles.handle}
+ id="l"
+ isConnectable={false}
+ position={Position.Left}
+ style={{ top: STAGE_HANDLE_TOP }}
+ type="target"
+ />
+ {/* Bottom first: a link that names no handle takes the first source. */}
+ <Handle
+ className={styles.handle}
+ isConnectable={false}
+ position={Position.Bottom}
+ type="source"
+ />
+ <Handle
+ className={styles.handle}
+ id="r"
+ isConnectable={false}
+ position={Position.Right}
+ style={{ top: STAGE_HANDLE_TOP }}
+ type="source"
+ />
+ </>
+);
+
+interface GroupStatus {
+ color: string;
+ icon: LucideIcon;
+ text: string;
+}
+
+const StatusText = memo<GroupStatus & { breathe?: boolean }>(({ breathe, color, icon, text }) => (
+ <span className={cx(styles.status, breathe && styles.breathe)} style={{ color }}>
+ <Icon icon={icon} size={13} />
+ {text}
+ </span>
+));
+
+StatusText.displayName = 'GoalBatchStatusText';
+
+const GroupShell = memo<{
+ children: ReactNode;
+ foot?: string;
+ /** Detail behind an info icon beside the title. */
+ hint?: ReactNode;
+ icon: LucideIcon;
+ iconColor: string;
+ onEnter?: () => void;
+ status: GroupStatus;
+ title: string;
+}>(({ children, foot, hint, icon, iconColor, onEnter, status, title }) => {
+ const { t } = useTranslation('chat');
+ return (
+ <div className={styles.group}>
+ <GroupHandles />
+ <div className={styles.groupHead}>
+ <Flexbox horizontal align={'center'} gap={7} style={{ minWidth: 0 }}>
+ <Icon color={iconColor} icon={icon} size={14} />
+ <span className={styles.groupTitle}>{title}</span>
+ {hint && (
+ <Tooltip title={hint}>
+ <span data-hint className={cx('nodrag', styles.hint)} role="img">
+ <Icon icon={Info} size={13} />
+ </span>
+ </Tooltip>
+ )}
+ </Flexbox>
+ {onEnter && (
+ <Button
+ className={'nodrag'}
+ size={'small'}
+ onClick={(event) => {
+ event.stopPropagation();
+ onEnter();
+ }}
+ >
+ {t('goalBatch.enter')}
+ </Button>
+ )}
+ </div>
+ {children}
+ <div className={styles.foot}>
+ <StatusText {...status} />
+ {foot && <span className={styles.muted}>{foot}</span>}
+ </div>
+ </div>
+ );
+});
+
+GroupShell.displayName = 'GoalBatchGroupShell';
+
+export const Square = memo<{
+ onSelect?: (nodeId: string) => void;
+ nodeId?: string;
+ state: BatchCellState;
+ tooltip: string;
+}>(({ nodeId, onSelect, state, tooltip }) => (
+ <Tooltip title={tooltip}>
+ <button
+ aria-label={tooltip}
+ data-state={state}
+ style={squareStyle(state)}
+ type="button"
+ className={cx(
+ 'nodrag',
+ styles.square,
+ nodeId && onSelect && styles.squareLink,
+ state === 'running' && styles.breathe,
+ )}
+ onClick={(event) => {
+ event.stopPropagation();
+ if (nodeId) onSelect?.(nodeId);
+ }}
+ />
+ </Tooltip>
+));
+
+Square.displayName = 'GoalBatchSquare';
+
+const useCellLabel = () => {
+ const { t } = useTranslation('chat');
+ return (state: BatchCellState) => t(`goalBatch.cell.${state}` as const);
+};
+
+/** One group status from its units: a person first, then progress. */
+const useUnitsStatus = () => {
+ const { t } = useTranslation('chat');
+ return (
+ cells: { state: BatchCellState }[],
+ copy: { done: string; pending: string; running: string },
+ started: boolean,
+ ): GroupStatus & { breathe?: boolean } => {
+ const counts = countCells(cells);
+ if (counts.human)
+ return { ...CELL_VISUAL.human, text: t('goalBatch.status.human', { count: counts.human }) };
+ if (counts.stale && counts.stale + counts.done < cells.length)
+ return {
+ color: cssVar.colorWarning,
+ icon: CircleSlash,
+ text: t('goalBatch.status.stale', { count: counts.stale }),
+ };
+ if (cells.length > 0 && counts.done + counts.stale === cells.length)
+ return { ...CELL_VISUAL.done, text: copy.done };
+ if (!started && !counts.running) return { ...CELL_VISUAL.backlog, text: copy.pending };
+ return { ...CELL_VISUAL.running, text: copy.running };
+ };
+};
+
+/**
+ * What each square's colour means. It only matters where squares are drawn, so
+ * it lives behind the info icon of the groups that draw them.
+ */
+const SquareLegend = memo(() => {
+ const label = useCellLabel();
+ return (
+ <Flexbox gap={6}>
+ {(['backlog', 'running', 'human', 'done', 'stale'] as const).map((state) => (
+ <Flexbox horizontal align={'center'} gap={6} key={state}>
+ <span className={styles.square} style={squareStyle(state)} />
+ {label(state)}
+ </Flexbox>
+ ))}
+ </Flexbox>
+ );
+});
+
+SquareLegend.displayName = 'GoalBatchSquareLegend';
+
+// ─── Experiment probe (the first round's trials) ──────────────────────────────────────────────
+
+export interface BatchExperimentProbeData extends Record<string, unknown> {
+ /** Open the batch on its own, the way a person reviews one batch at a time. */
+ onEnter: () => void;
+ onSelect: (nodeId: string) => void;
+ probes: BatchProbe[];
+ started: boolean;
+ views: Record<string, GoalNodeView>;
+}
+
+const ProbeCell = memo<{ onSelect: (id: string) => void; probe: BatchProbe; view?: GoalNodeView }>(
+ ({ onSelect, probe, view }) => {
+ const { t } = useTranslation('chat');
+ const visual = CELL_VISUAL[probe.state];
+ const subtitle = view?.node.description?.split('\n')[0] ?? '';
+ return (
+ <div className={styles.probeCell} data-probe={probe.nodeId} data-state={probe.state}>
+ <StatusText
+ breathe={probe.state === 'running'}
+ color={visual.color}
+ icon={visual.icon}
+ text={t(`goalBatch.probes.cell.${probe.state}` as const)}
+ />
+ <div
+ className={cx('nodrag', styles.card)}
+ role="button"
+ style={probe.state === 'stale' ? { opacity: 0.5 } : undefined}
+ tabIndex={0}
+ onClick={(event) => {
+ event.stopPropagation();
+ onSelect(probe.nodeId);
+ }}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault();
+ onSelect(probe.nodeId);
+ }
+ }}
+ >
+ <Flexbox horizontal align={'center'} gap={7}>
+ <span
+ className={styles.glyph}
+ style={{ background: KIND_COLOR.task.soft, color: KIND_COLOR.task.line }}
+ >
+ <Icon icon={KIND_ICON.task} size={14} />
+ </span>
+ <Flexbox style={{ flex: 1, minWidth: 0 }}>
+ <span className={styles.cardTitle} title={probe.title}>
+ {probe.title}
+ </span>
+ {subtitle && (
+ <span className={cx(styles.cardTitle, styles.muted)} style={{ fontWeight: 400 }}>
+ {subtitle}
+ </span>
+ )}
+ </Flexbox>
+ </Flexbox>
+ </div>
+ </div>
+ );
+ },
+);
+
+ProbeCell.displayName = 'GoalBatchProbeCell';
+
+export const BatchExperimentProbeGroup = memo<NodeProps>(({ data }) => {
+ const { onEnter, onSelect, probes, started, views } = data as BatchExperimentProbeData;
+ const { t } = useTranslation('chat');
+ const status = useUnitsStatus()(
+ probes,
+ {
+ done: t('goalBatch.probes.status.done'),
+ pending: t('goalBatch.probes.status.pending'),
+ running: t('goalBatch.probes.status.running'),
+ },
+ started,
+ );
+ return (
+ <GroupShell
+ hint={t('goalBatch.probes.hint', { count: probes.length })}
+ icon={TestTubeDiagonal}
+ iconColor={KIND_COLOR.batch.line}
+ status={status}
+ title={t('goalBatch.probes.title')}
+ onEnter={onEnter}
+ >
+ <div className={styles.probeGrid}>
+ {probes.map((probe) => (
+ <ProbeCell
+ key={probe.nodeId}
+ probe={probe}
+ view={views[probe.nodeId]}
+ onSelect={onSelect}
+ />
+ ))}
+ </div>
+ </GroupShell>
+ );
+});
+
+BatchExperimentProbeGroup.displayName = 'GoalBatchExperimentProbeGroup';
+
+// ─── Waves (the roster) ───────────────────────────────────────────────────
+
+/** A roster wave as a row of squares; `wave` is its 0-based roster position. */
+export interface BatchWaveRow {
+ cells: BatchCell[];
+ 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>
+ </Flexbox>
+ );
+ })}
+ </>
+ );
+ },
+);
+
+WaveRows.displayName = 'GoalBatchWaveRows';
+
+// ─── A round: its waves, and the frame its nodes sit in ─────────────────
+
+const useOriginCopy = () => {
+ const { t } = useTranslation('chat');
+ return (from?: BatchUnitOrigin): string => {
+ switch (from?.kind) {
+ case 'wave': {
+ return t('goalBatch.redispatch.fromWave', { index: from.index + 1, wave: from.wave + 1 });
+ }
+ case 'probe': {
+ return t('goalBatch.redispatch.fromProbe', { index: from.index + 1 });
+ }
+ case 'round': {
+ return t('goalBatch.redispatch.fromRound', { revision: from.revision });
+ }
+ default: {
+ return '';
+ }
+ }
+ };
+};
+
+export interface BatchWavesData extends Record<string, unknown> {
+ /** Open the batch on its own, the way a person reviews one batch at a time. */
+ onEnter: () => void;
+ onSelect: (nodeId: string) => void;
+ /** The units this round re-opened — its own canary (rounds after the first). */
+ probes: BatchProbe[];
+ revision: number;
+ /** The roster waves this round released, or still holds as the latest round. */
+ rows: BatchWaveRow[];
+ started: boolean;
+ waveSize: number;
+}
+
+/** 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 { t } = useTranslation('chat');
+ const label = useCellLabel();
+ const originCopy = useOriginCopy();
+ const rowLabelOf = (from?: BatchUnitOrigin) =>
+ from?.kind === 'wave'
+ ? t('goalBatch.waves.row', { number: from.wave + 1 })
+ : from?.kind === 'probe'
+ ? t('goalBatch.probes.rowLabel')
+ : from?.kind === 'round'
+ ? t('goalBatch.redispatch.labelRound', { revision: from.revision })
+ : t('goalBatch.redispatch.reopenedRow');
+ const reopened = revision > 1 ? reopenedRows(probes, waveSize) : [];
+ const cells = [...(revision > 1 ? probes : []), ...rows.flatMap((row) => row.cells)];
+ const status = useUnitsStatus()(
+ cells,
+ {
+ done: t('goalBatch.status.done'),
+ pending: t('goalBatch.status.pending'),
+ running: t('goalBatch.status.running'),
+ },
+ started,
+ );
+ return (
+ <GroupShell
+ hint={<SquareLegend />}
+ icon={Waves}
+ iconColor={KIND_COLOR.task.line}
+ status={status}
+ foot={
+ revision > 1
+ ? t('goalBatch.redispatch.foot', { count: cells.length, revision })
+ : t('goalBatch.waves.foot', { count: cells.length, waves: rows.length })
+ }
+ title={
+ revision > 1 ? t('goalBatch.redispatch.title', { revision }) : t('goalBatch.waves.title')
+ }
+ onEnter={onEnter}
+ >
+ <div className={styles.wavesBody}>
+ {/* Re-opened units first — this round's own canary, named by the batch
+ they first ran in — then the roster waves the round owns. */}
+ {reopened.map((row, w) => (
+ <Flexbox horizontal align={'center'} data-reopened-row={w} gap={8} key={`reopened-${w}`}>
+ <span className={styles.rowLabel}>{rowLabelOf(row.from)}</span>
+ <Flexbox horizontal gap={BATCH_SQUARE_GAP}>
+ {row.probes.map((probe) => (
+ <Square
+ key={probe.nodeId}
+ nodeId={probe.nodeId}
+ state={probe.state}
+ tooltip={[probe.title, originCopy(probe.from), label(probe.state)]
+ .filter(Boolean)
+ .join(' · ')}
+ onSelect={onSelect}
+ />
+ ))}
+ </Flexbox>
+ </Flexbox>
+ ))}
+ <WaveRows rows={rows} onSelect={onSelect} />
+ </div>
+ </GroupShell>
+ );
+});
+
+BatchWavesGroup.displayName = 'GoalBatchWavesGroup';
+
+export interface BatchRoundFrameData extends Record<string, unknown> {
+ revision: number;
+}
+
+/**
+ * The frame one round's nodes sit in — its plan, its gate and its waves. It is
+ * only a container: no status and no entry of its own (the waves carry those).
+ * It sits behind the links between its nodes, and links round to round on its
+ * sides, level with its label.
+ */
+export const BatchRoundFrame = memo<NodeProps>(({ data }) => {
+ const { revision } = data as BatchRoundFrameData;
+ const { t } = useTranslation('chat');
+ return (
+ <div className={styles.frame}>
+ <Handle
+ className={styles.handle}
+ id="l"
+ isConnectable={false}
+ position={Position.Left}
+ style={{ top: BATCH_FRAME_HEAD / 2 }}
+ type="target"
+ />
+ <Handle
+ className={styles.handle}
+ id="r"
+ isConnectable={false}
+ position={Position.Right}
+ style={{ top: BATCH_FRAME_HEAD / 2 }}
+ type="source"
+ />
+ <div className={styles.frameHead}>{t('goalBatch.round.title', { revision })}</div>
+ </div>
+ );
+});
+
+BatchRoundFrame.displayName = 'GoalBatchRoundFrame';
diff --git a/src/features/AgentGoals/ProcessControl/Graph/ExperimentGroup.tsx b/src/features/AgentGoals/ProcessControl/Graph/ExperimentGroup.tsx
index 2df8b88d5ec..569672f0ba0 100644
--- a/src/features/AgentGoals/ProcessControl/Graph/ExperimentGroup.tsx
+++ b/src/features/AgentGoals/ProcessControl/Graph/ExperimentGroup.tsx
@@ -5,6 +5,7 @@ import { createStaticStyles, cssVar } from 'antd-style';
import { ChevronDown, FlaskConical } from 'lucide-react';
import { useTranslation } from 'react-i18next';
+import { KIND_ICON } from '../shared';
import { experimentStatusVisual } from './experimentStatus';
import type { GraphNodeData } from './GraphNode';
@@ -40,11 +41,17 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
-/** An expanded answer encloses its work without replacing the surrounding map. */
+/** An expanded container encloses its work without replacing the surrounding map. */
const ExperimentGroup = ({ data }: NodeProps) => {
- const { view, memberCount, onToggle, onInspect, onEnter } = data as ExperimentGroupData;
+ const { containerStatus, view, memberCount, onToggle, onInspect, onEnter, kind } =
+ data as ExperimentGroupData;
const { t } = useTranslation('chat');
- const status = experimentStatusVisual(view.node.status);
+ const nodeStatus = containerStatus ?? view.node.status;
+ const status = experimentStatusVisual(nodeStatus);
+ // A batch folds like an experiment but is not one: it wears its own icon and
+ // the batch label, so the two containers never read as the same thing.
+ const isBatch = kind === 'batch';
+ const ContainerIcon = KIND_ICON[kind ?? view.node.kind] ?? FlaskConical;
return (
<div className={styles.frame}>
<Handle position={Position.Top} type={'target'} />
@@ -68,9 +75,11 @@ const ExperimentGroup = ({ data }: NodeProps) => {
}}
>
<Icon icon={ChevronDown} size={14} />
- <Icon icon={FlaskConical} size={14} />
+ <Icon icon={ContainerIcon} size={14} />
<span className={styles.title}>
- {t('goalExperiment.number', { number: view.seq })} · {view.node.title}
+ {isBatch
+ ? `${t('goalProcess.kind.batch')} · ${view.node.title}`
+ : `${t('goalExperiment.number', { number: view.seq })} · ${view.node.title}`}
</span>
</Button>
<Flexbox horizontal gap={4} style={{ flexShrink: 0 }}>
@@ -101,7 +110,7 @@ const ExperimentGroup = ({ data }: NodeProps) => {
<Flexbox horizontal align={'center'} gap={5}>
<Icon color={status.color} icon={status.icon} size={13} />
<Text fontSize={12} style={{ color: status.color }}>
- {t(`goalExperiment.status.${view.node.status}`)}
+ {t(`goalExperiment.status.${nodeStatus}`)}
</Text>
</Flexbox>
<Text fontSize={12} type={'secondary'}>
diff --git a/src/features/AgentGoals/ProcessControl/Graph/ExplorationEdge.tsx b/src/features/AgentGoals/ProcessControl/Graph/ExplorationEdge.tsx
index 7dc30c0b930..5e204f12b46 100644
--- a/src/features/AgentGoals/ProcessControl/Graph/ExplorationEdge.tsx
+++ b/src/features/AgentGoals/ProcessControl/Graph/ExplorationEdge.tsx
@@ -1,6 +1,6 @@
-import { BaseEdge, type EdgeProps, useReactFlow } from '@xyflow/react';
+import { BaseEdge, type EdgeProps, Position, useReactFlow } from '@xyflow/react';
-import { edgeLabelPoint, routeEdge } from './edgeRouting';
+import { edgeLabelPoint, routeEdge, sideToSidePath } from './edgeRouting';
/** Measured card bounds, rather than estimated layout heights, keep paths out of text. */
const ExplorationEdge = (props: EdgeProps) => {
@@ -30,12 +30,17 @@ const ExplorationEdge = (props: EdgeProps) => {
: (n.measured?.height ?? n.height ?? n.initialHeight ?? 0),
};
});
- const points = routeEdge(
- { x: props.sourceX, y: props.sourceY },
- { x: props.targetX, y: props.targetY },
- boxes,
- typeof props.data?.lane === 'number' ? props.data.lane : 0,
- );
+ const source = { x: props.sourceX, y: props.sourceY };
+ const target = { x: props.targetX, y: props.targetY };
+ const points =
+ props.sourcePosition === Position.Right && props.targetPosition === Position.Left
+ ? sideToSidePath(source, target)
+ : routeEdge(
+ source,
+ target,
+ boxes,
+ typeof props.data?.lane === 'number' ? props.data.lane : 0,
+ );
const label = edgeLabelPoint(points);
return (
<BaseEdge
diff --git a/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx b/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx
index c6f7060fa17..6545a7dc479 100644
--- a/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx
+++ b/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx
@@ -1,10 +1,11 @@
'use client';
+import type { GoalNodeStatus } from '@lobechat/types';
import { Flexbox, Icon, Tooltip } from '@lobehub/ui';
import { Handle, type NodeProps, Position } from '@xyflow/react';
import { createStaticStyles, cssVar, cx } from 'antd-style';
-import { FileBox, type LucideIcon, Repeat2, ShieldCheck } from 'lucide-react';
-import { memo } from 'react';
+import { FileBox, Info, type LucideIcon, Repeat2, ShieldCheck } from 'lucide-react';
+import { memo, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { TASK_STATUS_VISUALS } from '@/components/ExecutionStatus';
@@ -27,6 +28,8 @@ import { experimentStatusVisual } from './experimentStatus';
*/
export interface GraphNodeData extends Record<string, unknown> {
+ /** A container's status when its node's own does not tell it — an open batch. */
+ containerStatus?: GoalNodeStatus;
dim: boolean;
/** Called out by the host — a detour on a report chapter's local map. */
highlighted?: boolean;
@@ -35,6 +38,22 @@ export interface GraphNodeData extends Record<string, unknown> {
/** On the path the wrap-up report marked as the one that led to the result. */
mainline?: boolean;
memberCount?: number;
+ /**
+ * Host-authored copy for a card whose role the node alone does not carry — a
+ * batch's plan revision or release gate. `chip: null` drops the state chip.
+ */
+ presentation?: {
+ chip?: StateChip | null;
+ /** Detail behind an info icon beside the title, e.g. what a gate checks. */
+ hint?: ReactNode;
+ icon?: LucideIcon;
+ /** Glyph colours when the card is not its kind — a release gate. */
+ palette?: { line: string; soft: string };
+ /** Put the state chip at the right of the title instead of a row above it. */
+ trailingChip?: boolean;
+ subtitle?: ReactNode;
+ title?: string;
+ };
running: boolean;
selected: boolean;
stale: boolean;
@@ -195,6 +214,16 @@ const styles = createStaticStyles(({ css }) => ({
text-overflow: ellipsis;
white-space: nowrap;
`,
+ hint: css`
+ cursor: help;
+
+ display: inline-flex;
+
+ margin-inline-start: 4px;
+
+ color: ${cssVar.colorTextTertiary};
+ vertical-align: -2px;
+ `,
title: css`
font-size: 13px;
font-weight: 500;
@@ -202,10 +231,13 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
-interface StateChip {
+export interface StateChip {
color: string;
- /** The task family's status glyph; running renders the animated ring instead. */
- icon?: LucideIcon;
+ /**
+ * The task family's status glyph; omitted, running renders the animated ring
+ * instead, and `null` renders the text alone.
+ */
+ icon?: LucideIcon | null;
text: string;
}
@@ -289,9 +321,11 @@ const GraphNodeView = memo<NodeProps>(({ data }) => {
const nodeData = data as GraphNodeData;
const { dim, highlighted, isGate, mainline, running, selected, stale, subtitle, view } = nodeData;
const { node } = view;
- const chip = useStateChip(nodeData);
+ const stateChip = useStateChip(nodeData);
+ const { presentation } = nodeData;
+ const chip = presentation && 'chip' in presentation ? presentation.chip : stateChip;
const kind = nodeData.kind ?? node.kind;
- const palette = KIND_COLOR[kind];
+ const palette = nodeData.presentation?.palette ?? KIND_COLOR[kind];
const isTask = node.kind === 'task';
const attempts = view.attempts.length;
// Coordinator-authored node titles are English; recognized ones localize.
@@ -305,6 +339,14 @@ const GraphNodeView = memo<NodeProps>(({ data }) => {
position={Position.Top}
type={'target'}
/>
+ {/* A later round's plan is fed from beside it, by the group the break surfaced in. */}
+ <Handle
+ className={styles.handle}
+ id={'l'}
+ isConnectable={false}
+ position={Position.Left}
+ type={'target'}
+ />
<div
data-mainline={mainline || undefined}
className={cx(
@@ -319,7 +361,7 @@ const GraphNodeView = memo<NodeProps>(({ data }) => {
>
{/* Status reads first: its own top row, left-aligned, with the running
clock riding right behind it (review: bottom placements read poorly). */}
- {(chip || highlighted || view.humanTouches.length > 0) && (
+ {!presentation?.trailingChip && (chip || highlighted || view.humanTouches.length > 0) && (
<div className={styles.statusRow}>
{highlighted && (
<span className={styles.chipText} style={{ color: cssVar.colorWarningText }}>
@@ -335,7 +377,7 @@ const GraphNodeView = memo<NodeProps>(({ data }) => {
<Flexbox horizontal align={'center'} gap={5}>
{chip.icon ? (
<Icon color={chip.color} icon={chip.icon} size={13} />
- ) : (
+ ) : chip.icon === null ? null : (
<RunningGlyph size={13} />
)}
<span className={styles.chipText} style={{ color: chip.color }}>
@@ -359,14 +401,32 @@ const GraphNodeView = memo<NodeProps>(({ data }) => {
)}
<div className={styles.head}>
<div className={styles.glyph} style={{ background: palette.soft, color: palette.line }}>
- <Icon icon={KIND_ICON[kind]} size={16} />
+ <Icon icon={presentation?.icon ?? KIND_ICON[kind]} size={16} />
</div>
<Flexbox gap={2} style={{ flex: 1, minWidth: 0 }}>
<span className={styles.title}>
- {coordinatorTitleKey ? t(coordinatorTitleKey as any) : node.title}
+ {presentation?.title ??
+ (coordinatorTitleKey ? t(coordinatorTitleKey as any) : node.title)}
+ {presentation?.hint && (
+ <Tooltip title={presentation.hint}>
+ <span data-hint className={cx('nodrag', styles.hint)} role="img">
+ <Icon icon={Info} size={13} />
+ </span>
+ </Tooltip>
+ )}
</span>
- {subtitle && <span className={styles.subtitle}>{subtitle}</span>}
+ {(presentation?.subtitle ?? subtitle) && (
+ <span className={styles.subtitle}>{presentation?.subtitle ?? subtitle}</span>
+ )}
</Flexbox>
+ {presentation?.trailingChip && chip && (
+ <Flexbox horizontal align={'center'} gap={5} style={{ flex: 'none' }}>
+ {chip.icon && <Icon color={chip.color} icon={chip.icon} size={13} />}
+ <span className={styles.chipText} style={{ color: chip.color }}>
+ {chip.text}
+ </span>
+ </Flexbox>
+ )}
</div>
{node.kind === 'experiment' && (
<div className={styles.metrics}>
diff --git a/src/features/AgentGoals/ProcessControl/Graph/batchLayout.ts b/src/features/AgentGoals/ProcessControl/Graph/batchLayout.ts
new file mode 100644
index 00000000000..ec6473fc0cc
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/Graph/batchLayout.ts
@@ -0,0 +1,230 @@
+import type { GoalGraphView } from '../goalGraphViewModel';
+import { type BatchModel, type BatchRound, reopenedRows } from './batchModel';
+import type { LayoutBox } from './layout';
+
+/**
+ * Fixed layout of an expanded batch, left to right:
+ *
+ * 冷启动 (the first round's trials as task cards)
+ * → ┆第 1 轮: 方案 v1 → 放行闸门 → 分批执行┆
+ * → ┆第 2 轮: 方案 v2 → 放行闸门 → 分批执行 · v2┆ → 第 3 轮 …
+ *
+ * Plan, gate and waves stay their own nodes — the plan and gate are the real
+ * graph nodes, the waves the group a person enters the batch through — and a
+ * round is a frame around the three, top to bottom. A break at a round's gate
+ * feeds the next round, which revises both the plan and the gate, so the
+ * frames repeat along one row. Other decisions inside the batch (a machine gate
+ * on one unit) sit under the frame their subject runs in.
+ *
+ * An open batch draws no frame of its own: these pieces sit on the map
+ * directly. Boxes are relative to the batch's slot, which the map reserves.
+ */
+
+/** Group chrome, as the prototype draws it: 8/10 header, 8·4 body, 6/10 foot. */
+export const BATCH_GROUP_HEAD = 38;
+export const BATCH_GROUP_FOOT = 30;
+export const BATCH_GROUP_PAD = 10;
+export const BATCH_PROBE_CARD_HEIGHT = 72;
+export const BATCH_PROBE_ROW_GAP = 7;
+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;
+
+/** A round frame's label row; its side links leave at half this height. */
+export const BATCH_FRAME_HEAD = 38;
+
+const GAP_Y = 48;
+const COLUMN_GAP = 120;
+const PROBES_WIDTH = 440;
+const FRAME_PAD = 16;
+/** Room between a round's stacked nodes for the link and its arrow. */
+const STACK_GAP = 40;
+const CARD = { height: 88, width: 250 };
+const DECISION = { height: 88, width: 250 };
+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.
+ */
+export type BatchGroupKind = 'experimentProbe' | 'round' | 'waves';
+
+export interface BatchGroupSpec {
+ box: LayoutBox;
+ id: string;
+ kind: BatchGroupKind;
+ /** The round the group belongs to (1-based). */
+ revision: number;
+}
+
+/** A link the batch draws between its pieces; it renders as an ordinary map edge. */
+export interface BatchEdgeSpec {
+ id: string;
+ /** `revise`: a round's gate sent the batch back and the next round revised it. */
+ label?: 'revise';
+ source: string;
+ /** `r` → `l`: one stage feeding the next along the row; none: down a round. */
+ sourceHandle?: 'r';
+ target: string;
+ targetHandle?: 'l';
+}
+
+export interface BatchLayout {
+ /** X of the column links into the batch land on, so the map can line it up under its parent. */
+ anchorX: number;
+ boxes: Record<string, LayoutBox>;
+ edges: BatchEdgeSpec[];
+ /** Where links into the batch land: its first piece, top of the column. */
+ entryId?: string;
+ groups: BatchGroupSpec[];
+ height: number;
+ /** Real graph nodes the layout places; every other batch member stays off the map. */
+ nodeIds: Set<string>;
+ width: number;
+}
+
+export const batchGroupId = (batchId: string, kind: BatchGroupKind, revision = 1) =>
+ kind === 'experimentProbe' ? `${batchId}::experiment-probe` : `${batchId}::${kind}-${revision}`;
+
+const groupHeight = (body: number) => BATCH_GROUP_HEAD + 8 + body + 4 + BATCH_GROUP_FOOT;
+
+const stack = (count: number, size: number, gap: number) =>
+ count > 0 ? count * size + (count - 1) * gap : 0;
+
+export const wavesWidth = (waveSize: number) =>
+ Math.max(
+ CARD.width,
+ BATCH_GROUP_PAD * 2 + BATCH_ROW_LABEL + 8 + stack(waveSize, BATCH_SQUARE, BATCH_SQUARE_GAP) + 2,
+ );
+
+/** How many square rows a round's waves draw: its re-opened rows, then its waves. */
+export const roundRows = (model: BatchModel, round: BatchRound) =>
+ (round.revision > 1 ? reopenedRows(round.probes, model.waveSize).length : 0) +
+ model.waveRounds.filter((owner) => owner === round.revision).length;
+
+export const layoutBatch = (graph: GoalGraphView, model: BatchModel): BatchLayout => {
+ const { batchId, rounds } = model;
+ const boxes: Record<string, LayoutBox> = {};
+ const groups: BatchGroupSpec[] = [];
+ const edges: BatchEdgeSpec[] = [];
+ const nodeIds = new Set<string>();
+ const addGroup = (kind: BatchGroupKind, revision: number, box: LayoutBox) => {
+ const id = batchGroupId(batchId, kind, revision);
+ groups.push({ box, id, kind, revision });
+ boxes[id] = box;
+ return id;
+ };
+
+ const [first] = rounds;
+ const innerW = Math.max(CARD.width, wavesWidth(model.waveSize));
+ const frameW = innerW + FRAME_PAD * 2;
+ let right = 0;
+ let previous: string | undefined;
+
+ // The cold start: the first round's trials, before any plan is proved.
+ let probesId: string | undefined;
+ if (first.probes.length) {
+ const rows = Math.ceil(first.probes.length / 2);
+ const height = groupHeight(stack(rows, BATCH_PROBE_CARD_HEIGHT, BATCH_PROBE_ROW_GAP));
+ probesId = addGroup('experimentProbe', 1, { height, width: PROBES_WIDTH, x: 0, y: 0 });
+ right = PROBES_WIDTH;
+ previous = probesId;
+ }
+
+ // One frame per round, left to right; inside, plan → gate → waves.
+ const wavesIds = new Map<number, string>();
+ const frameIds = new Map<number, string>();
+ for (const round of rounds) {
+ const x = right ? right + COLUMN_GAP : 0;
+ const left = x + FRAME_PAD;
+ let y = BATCH_FRAME_HEAD;
+ let above: string | undefined;
+ const place = (id: string, box: LayoutBox) => {
+ boxes[id] = box;
+ if (above) edges.push({ id: `${batchId}::e-${above}->${id}`, source: above, target: id });
+ above = id;
+ y = box.y + box.height + STACK_GAP;
+ };
+ for (const id of [round.templateId, round.assayId]) {
+ if (!id) continue;
+ nodeIds.add(id);
+ place(id, { ...CARD, x: left + (innerW - CARD.width) / 2, y });
+ }
+ const rows = roundRows(model, round);
+ const wavesBox = {
+ height: groupHeight(stack(rows, BATCH_SQUARE, BATCH_SQUARE_GAP)),
+ width: innerW,
+ x: left,
+ y,
+ };
+ const wavesId = batchGroupId(batchId, 'waves', round.revision);
+ place(wavesId, wavesBox);
+ groups.push({ box: wavesBox, id: wavesId, kind: 'waves', revision: round.revision });
+ wavesIds.set(round.revision, wavesId);
+
+ const frameId = addGroup('round', round.revision, {
+ height: wavesBox.y + wavesBox.height + FRAME_PAD,
+ width: frameW,
+ x,
+ y: 0,
+ });
+ frameIds.set(round.revision, frameId);
+ if (previous)
+ edges.push({
+ id: `${batchId}::e-round-${round.revision}`,
+ label: round.revision > 1 ? 'revise' : undefined,
+ source: previous,
+ sourceHandle: 'r',
+ target: frameId,
+ targetHandle: 'l',
+ });
+ previous = frameId;
+ right = x + frameW;
+ }
+
+ // Other decisions inside the batch, under the round their subject runs in.
+ // Revision 0 stands for the cold start.
+ const roundOfNode = new Map<string, number>();
+ if (probesId) for (const probe of first.probes) roundOfNode.set(probe.nodeId, 0);
+ for (const round of rounds.slice(1))
+ for (const probe of round.probes) roundOfNode.set(probe.nodeId, round.revision);
+ const rowBottom = Math.max(0, ...Object.values(boxes).map((box) => box.y + box.height));
+ const stacked = new Map<number, number>();
+ for (const id of model.decisionIds) {
+ if (nodeIds.has(id)) continue;
+ const subject = graph.byId[id]?.gateSubjectId;
+ const revision = (subject ? roundOfNode.get(subject) : undefined) ?? rounds.length;
+ const under = boxes[(revision ? frameIds.get(revision) : probesId) ?? ''];
+ // The link leaves the bottom of what the subject ran in: the trials, or the waves.
+ const source = revision ? wavesIds.get(revision) : probesId;
+ if (!under || !source) continue;
+ const count = stacked.get(revision) ?? 0;
+ stacked.set(revision, count + 1);
+ boxes[id] = {
+ ...DECISION,
+ x: under.x + (under.width - DECISION.width) / 2,
+ y: rowBottom + GAP_Y + count * (DECISION.height + DECISION_GAP),
+ };
+ nodeIds.add(id);
+ edges.push({ id: `${batchId}::e-aside-${id}`, source, target: id });
+ }
+
+ const bottom = Math.max(...Object.values(boxes).map((box) => box.y + box.height), 0);
+ const entry = boxes[probesId ?? frameIds.get(1) ?? ''];
+ return {
+ anchorX: entry ? entry.x + entry.width / 2 : 0,
+ boxes,
+ edges,
+ entryId: probesId ?? round1Entry(rounds, frameIds),
+ groups,
+ height: bottom,
+ nodeIds,
+ width: right,
+ };
+};
+
+/** Without trials, links into the batch land on its first round's first node. */
+const round1Entry = (rounds: BatchRound[], frameIds: Map<number, string>) =>
+ rounds[0].templateId ?? rounds[0].assayId ?? frameIds.get(1);
diff --git a/src/features/AgentGoals/ProcessControl/Graph/batchModel.test.ts b/src/features/AgentGoals/ProcessControl/Graph/batchModel.test.ts
new file mode 100644
index 00000000000..a12e2f811fc
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/Graph/batchModel.test.ts
@@ -0,0 +1,603 @@
+import { GOAL_BATCH_ASSAY_TITLE, GOAL_BATCH_TEMPLATE_TITLE } from '@lobechat/const/goal';
+import type {
+ GoalGraphDecision,
+ GoalGraphEdge,
+ GoalGraphNode,
+ GoalGraphSnapshot,
+ GoalRolloutState,
+} from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { buildGoalGraphView } from '../goalGraphViewModel';
+import { batchGroupId, layoutBatch } from './batchLayout';
+import {
+ buildBatchModel,
+ findBatchGate,
+ findBatchPlan,
+ reopenedRows,
+ verdictChecks,
+} from './batchModel';
+
+const T0 = new Date('2026-10-01T00:00:00Z');
+const at = (minutes: number) => new Date(T0.getTime() + minutes * 60_000);
+
+const node = (
+ id: string,
+ kind: GoalGraphNode['kind'],
+ minute: number,
+ overrides: Partial<GoalGraphNode> = {},
+): GoalGraphNode => ({
+ confidence: null,
+ createdAt: at(minute),
+ createdByAgentId: null,
+ createdByUserId: null,
+ description: null,
+ goalId: 'goal-1',
+ id,
+ kind,
+ priority: 0,
+ resolvedAt: null,
+ status: 'proposed',
+ taskId: null,
+ title: id,
+ updatedAt: at(minute),
+ ...overrides,
+});
+
+const edge = (source: string, target: string, kind: GoalGraphEdge['kind']): GoalGraphEdge => ({
+ createdAt: T0,
+ goalId: 'goal-1',
+ id: `${source}-${target}-${kind}`,
+ kind,
+ sourceNodeId: source,
+ targetNodeId: target,
+});
+
+const humanAnswer = (nodeId: string): GoalGraphDecision => ({
+ authority: 'user',
+ canceledAt: null,
+ createdAt: at(30),
+ id: `d-${nodeId}`,
+ nodeId,
+ options: [{ description: '', id: 'revise', label: 'revise' }],
+ question: 'Batch gate blocked',
+ recommendedOptionId: null,
+ requestedProjectRole: null,
+ requestedUserId: 'user-1',
+ resolution: null,
+ resolvedAt: at(31),
+ resolvedByAgentId: null,
+ resolvedByUserId: 'user-1',
+ resolvedOptionId: 'revise',
+ status: 'resolved',
+ updatedAt: at(31),
+});
+
+const ROSTER = ['U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'U7', 'U8', 'U9', 'U10'];
+
+/** Two probes (U1, U2), a recipe, a gate, and the rest of the roster in waves of four. */
+const batchSnapshot = ({
+ decisions = [],
+ extraEdges = [],
+ extraNodes = [],
+ state,
+}: {
+ decisions?: GoalGraphDecision[];
+ extraEdges?: GoalGraphEdge[];
+ extraNodes?: GoalGraphNode[];
+ state: Partial<GoalRolloutState>;
+}): GoalGraphSnapshot => {
+ const base = [
+ node('problem', 'problem', 0),
+ node('batch', 'batch', 1),
+ node('t1', 'finding', 2, { title: GOAL_BATCH_TEMPLATE_TITLE }),
+ node('a1', 'decision', 3, { title: GOAL_BATCH_ASSAY_TITLE }),
+ node('p1', 'task', 4, { status: 'resolved', title: 'U1' }),
+ node('p2', 'task', 5, { status: 'resolved', title: 'U2' }),
+ ];
+ const nodes = [...base, ...extraNodes];
+ const contained = nodes.filter((n) => n.id !== 'problem' && n.id !== 'batch');
+ return {
+ decisions,
+ edges: [
+ edge('problem', 'batch', 'decomposes'),
+ ...contained.map((n) => edge('batch', n.id, 'contains')),
+ edge('a1', 'p1', 'depends_on'),
+ edge('a1', 'p2', 'depends_on'),
+ ...extraEdges,
+ ],
+ events: [],
+ goal: {
+ agentId: 'agt',
+ completedAt: null,
+ config: {
+ rollout: { trigger: 'canary', units: ROSTER, waveSize: 4 },
+ rolloutState: {
+ assayNodeId: 'a1',
+ batchNodeId: 'batch',
+ phase: 'probe',
+ probeNodeIds: ['p1', 'p2'],
+ templateNodeId: 't1',
+ templateRevision: 1,
+ unitTitles: ROSTER,
+ waveIndex: 0,
+ ...state,
+ },
+ },
+ createdAt: T0,
+ id: 'goal-1',
+ maxRounds: null,
+ maxTotalCost: null,
+ projectId: null,
+ requirement: 'migrate ten units',
+ startedAt: T0,
+ status: 'running',
+ subjectId: null,
+ subjectType: 'standalone',
+ title: 'Batch',
+ updatedAt: T0,
+ userId: 'user-1',
+ workspaceId: null,
+ },
+ nodes,
+ workVersions: [],
+ };
+};
+
+const NOW = at(60).getTime();
+
+describe('buildBatchModel', () => {
+ it('lays the roster out as waves, not one card per unit', () => {
+ const graph = buildGoalGraphView(
+ batchSnapshot({
+ extraNodes: [
+ node('m3', 'task', 10, { status: 'resolved', title: 'U3' }),
+ node('m4', 'task', 10, { status: 'retired', title: 'U4' }),
+ node('m5', 'task', 10, { title: 'U5' }),
+ ],
+ state: { massNodeIds: ['m3', 'm4', 'm5'], phase: 'mass', waveIndex: 1 },
+ }),
+ NOW,
+ );
+ const model = buildBatchModel(graph, 'batch');
+
+ expect(model.rounds).toHaveLength(1);
+ expect(model.rounds[0].probes.map((probe) => probe.title)).toEqual(['U1', 'U2']);
+ expect(model.rounds[0].gate).toBe('passed');
+ // Eight units outside the probes, four to a wave.
+ expect(model.waves.map((wave) => wave.map((cell) => cell.title))).toEqual([
+ ['U3', 'U4', 'U5', 'U6'],
+ ['U7', 'U8', 'U9', 'U10'],
+ ]);
+ expect(model.waves[0].map((cell) => cell.state)).toEqual([
+ 'done',
+ 'stale',
+ 'backlog',
+ 'backlog',
+ ]);
+ expect(model.waves[1].every((cell) => cell.state === 'backlog' && !cell.nodeId)).toBe(true);
+ });
+
+ it('keeps the gate locked until every probe settled', () => {
+ const snapshot = batchSnapshot({ state: {} });
+ snapshot.nodes = snapshot.nodes.map((n) =>
+ n.id === 'p2' ? { ...n, status: 'active', updatedAt: at(59) } : n,
+ );
+ const model = buildBatchModel(buildGoalGraphView(snapshot, NOW), 'batch');
+
+ expect(model.rounds[0].gate).toBe('locked');
+ expect(model.rounds[0].probes.map((probe) => probe.state)).toEqual(['done', 'running']);
+ });
+
+ it('opens a v2 round for a unit re-opened after a person sent the gate back', () => {
+ const graph = buildGoalGraphView(
+ batchSnapshot({
+ decisions: [humanAnswer('a1')],
+ extraEdges: [
+ edge('t2', 't1', 'revises'),
+ edge('a2', 'p2b', 'depends_on'),
+ edge('p2b', 'p2', 'derived_from'),
+ ],
+ extraNodes: [
+ node('t2', 'finding', 40, { title: GOAL_BATCH_TEMPLATE_TITLE }),
+ node('a2', 'decision', 41, { title: GOAL_BATCH_ASSAY_TITLE }),
+ node('p2b', 'task', 42, { title: 'U2' }),
+ ],
+ state: { assayNodeId: 'a2', probeNodeIds: ['p2b'], templateNodeId: 't2' },
+ }),
+ NOW,
+ );
+ const model = buildBatchModel(graph, 'batch');
+
+ expect(model.rounds.map((round) => round.revision)).toEqual([1, 2]);
+ expect(model.rounds[0].gate).toBe('rejected');
+ const [, second] = model.rounds;
+ expect(second).toMatchObject({
+ assayId: 'a2',
+ forked: false,
+ gate: 'locked',
+ templateId: 't2',
+ });
+ expect(second.origin).toEqual({ kind: 'probes' });
+ expect(second.probes).toEqual([
+ expect.objectContaining({ from: { index: 1, kind: 'probe' }, nodeId: 'p2b', title: 'U2' }),
+ ]);
+ });
+
+ it('marks a wave unit superseded once a later round re-opened it', () => {
+ const graph = buildGoalGraphView(
+ batchSnapshot({
+ decisions: [humanAnswer('a1')],
+ extraEdges: [edge('a2', 'm4b', 'depends_on')],
+ extraNodes: [
+ node('m3', 'task', 10, { status: 'resolved', title: 'U3' }),
+ node('m4', 'task', 10, { status: 'retired', title: 'U4' }),
+ node('t2', 'finding', 40, { title: GOAL_BATCH_TEMPLATE_TITLE }),
+ node('a2', 'decision', 41, { title: GOAL_BATCH_ASSAY_TITLE }),
+ node('m4b', 'task', 42, { title: 'U4' }),
+ ],
+ state: { assayNodeId: 'a2', massNodeIds: ['m3', 'm4'], probeNodeIds: ['m4b'] },
+ }),
+ NOW,
+ );
+ const model = buildBatchModel(graph, 'batch');
+
+ expect(model.waves[0][1]).toMatchObject({ nodeId: 'm4', reopenedIn: 2, state: 'stale' });
+ // No `revises` edge: the person split it off as a new class.
+ expect(model.rounds[1].forked).toBe(true);
+ expect(model.rounds[1].origin).toEqual({ kind: 'waves', wave: 0 });
+ expect(model.rounds[1].probes[0].from).toEqual({ index: 1, kind: 'wave', wave: 0 });
+ });
+ it('lets a unit a later round first released follow that round, not read as superseded', () => {
+ const graph = buildGoalGraphView(
+ batchSnapshot({
+ decisions: [humanAnswer('a1')],
+ extraEdges: [edge('a2', 'f3', 'depends_on')],
+ extraNodes: [
+ node('t2', 'finding', 40, { title: GOAL_BATCH_TEMPLATE_TITLE }),
+ node('a2', 'decision', 41, { title: GOAL_BATCH_ASSAY_TITLE }),
+ node('f3', 'task', 42, { status: 'resolved', title: 'U3' }),
+ ],
+ state: { assayNodeId: 'a2', probeNodeIds: ['f3'] },
+ }),
+ NOW,
+ );
+ const [cell] = buildBatchModel(graph, 'batch').waves[0];
+
+ expect(cell).toMatchObject({ nodeId: 'f3', runIn: 2, state: 'done', title: 'U3' });
+ expect(cell.reopenedIn).toBeUndefined();
+ });
+});
+
+describe('unit states', () => {
+ it('reads a rejected unit as waiting on a person and only a retired one as superseded', () => {
+ const graph = buildGoalGraphView(
+ batchSnapshot({
+ extraNodes: [
+ node('m3', 'task', 10, { status: 'rejected', title: 'U3' }),
+ node('m4', 'task', 10, { status: 'retired', title: 'U4' }),
+ ],
+ state: { massNodeIds: ['m3', 'm4'], phase: 'pattern_break', waveIndex: 1 },
+ }),
+ NOW,
+ );
+ const [first] = buildBatchModel(graph, 'batch').waves;
+ expect(first.slice(0, 2).map((cell) => cell.state)).toEqual(['human', 'stale']);
+ });
+
+ it('reads the unit that held the batch as waiting on a person, though its node is active', () => {
+ const graph = buildGoalGraphView(
+ batchSnapshot({
+ extraNodes: [node('m3', 'task', 10, { status: 'active', title: 'U3', updatedAt: at(59) })],
+ state: {
+ gateLog: [
+ {
+ at: at(59).toISOString(),
+ checks: [],
+ nodeId: 'm3',
+ outcome: 'blocked',
+ revision: 1,
+ trigger: 'unit',
+ waveIndex: 1,
+ },
+ ],
+ massNodeIds: ['m3'],
+ phase: 'pattern_break',
+ waveIndex: 1,
+ },
+ }),
+ NOW,
+ );
+ expect(buildBatchModel(graph, 'batch').waves[0][0].state).toBe('human');
+ });
+});
+
+describe('superseded trials', () => {
+ it('reads a rejected trial a later round re-opened as superseded, not waiting on a person', () => {
+ const snapshot = batchSnapshot({
+ decisions: [humanAnswer('a1')],
+ extraEdges: [
+ edge('t2', 't1', 'revises'),
+ edge('a2', 'p2b', 'depends_on'),
+ edge('p2b', 'p2', 'derived_from'),
+ ],
+ extraNodes: [
+ node('t2', 'finding', 40, { title: GOAL_BATCH_TEMPLATE_TITLE }),
+ node('a2', 'decision', 41, { title: GOAL_BATCH_ASSAY_TITLE }),
+ node('p2b', 'task', 42, { title: 'U2' }),
+ ],
+ state: { assayNodeId: 'a2', probeNodeIds: ['p2b'], templateNodeId: 't2' },
+ });
+ snapshot.nodes = snapshot.nodes.map((n) => (n.id === 'p2' ? { ...n, status: 'rejected' } : n));
+ const model = buildBatchModel(buildGoalGraphView(snapshot, NOW), 'batch');
+ expect(model.rounds[0].probes.find((probe) => probe.nodeId === 'p2')?.state).toBe('stale');
+ });
+});
+
+describe('gate verdicts', () => {
+ it('keeps the wave the coordinator wrote, even once older verdicts were trimmed', () => {
+ const graph = buildGoalGraphView(
+ batchSnapshot({
+ state: {
+ gateLog: [
+ {
+ at: '2026-10-01T00:20:00.000Z',
+ checks: [],
+ outcome: 'released',
+ releasedCount: 1,
+ revision: 1,
+ trigger: 'gate',
+ wave: 31,
+ waveIndex: 31,
+ },
+ ],
+ },
+ }),
+ NOW,
+ );
+ expect(findBatchGate(graph, 'a1')?.round.evaluations[0].wave).toBe(31);
+ });
+
+ it('reads a unit hold as the one check it broke, naming the unit', () => {
+ expect(
+ verdictChecks({
+ at: '2026-10-01T00:30:00.000Z',
+ checks: [],
+ nodeId: 'm4',
+ outcome: 'blocked',
+ revision: 1,
+ trigger: 'unit',
+ waveIndex: 1,
+ }),
+ ).toEqual([{ key: 'units_succeeded', nodeIds: ['m4'], passed: false }]);
+ });
+
+ it('gives each round its own verdicts and finds the round from its gate', () => {
+ const released = {
+ at: '2026-10-01T00:20:00.000Z',
+ checks: [{ count: 2, key: 'units_succeeded' as const, passed: true, total: 2 }],
+ outcome: 'released' as const,
+ releasedCount: 4,
+ revision: 1,
+ trigger: 'gate' as const,
+ waveIndex: 1,
+ };
+ const held = {
+ at: '2026-10-01T00:30:00.000Z',
+ checks: [],
+ nodeId: 'm4',
+ outcome: 'blocked' as const,
+ revision: 1,
+ trigger: 'unit' as const,
+ waveIndex: 1,
+ };
+ const graph = buildGoalGraphView(
+ batchSnapshot({
+ decisions: [humanAnswer('a1')],
+ extraEdges: [edge('t2', 't1', 'revises'), edge('a2', 'm4b', 'depends_on')],
+ extraNodes: [
+ node('m4', 'task', 10, { status: 'retired', title: 'U4' }),
+ node('t2', 'finding', 40, { title: GOAL_BATCH_TEMPLATE_TITLE }),
+ node('a2', 'decision', 41, { title: GOAL_BATCH_ASSAY_TITLE }),
+ node('m4b', 'task', 42, { title: 'U4' }),
+ ],
+ state: {
+ assayNodeId: 'a2',
+ gateLog: [released, held, { ...released, at: '2026-10-01T00:50:00.000Z', revision: 2 }],
+ probeNodeIds: ['m4b'],
+ },
+ }),
+ NOW,
+ );
+
+ const first = findBatchGate(graph, 'a1');
+ expect(first?.round.revision).toBe(1);
+ expect(first?.round.evaluations).toEqual([{ ...released, wave: 1 }, held]);
+ // The round's own wave count restarts; the roster's does not — v2's first
+ // release puts out the roster's second wave.
+ const second = findBatchGate(graph, 'a2');
+ expect(second?.round.evaluations.map((entry) => entry.wave)).toEqual([2]);
+ // What a gate checks before its first verdict.
+ expect(second?.model.gateChecks.map((check) => check.key)).toEqual([
+ 'units_settled',
+ 'units_succeeded',
+ 'no_open_decision',
+ 'plan_written',
+ ]);
+ // Any other node is not a gate.
+ expect(findBatchGate(graph, 't1')).toBeUndefined();
+ });
+});
+
+describe('wave ownership', () => {
+ it('keeps a released wave with its plan and moves the waves not yet out to the latest round', () => {
+ const graph = buildGoalGraphView(
+ batchSnapshot({
+ decisions: [humanAnswer('a1')],
+ extraEdges: [edge('t2', 't1', 'revises'), edge('a2', 'm4b', 'depends_on')],
+ extraNodes: [
+ node('m3', 'task', 10, { status: 'resolved', title: 'U3' }),
+ node('m4', 'task', 10, { status: 'retired', title: 'U4' }),
+ node('t2', 'finding', 40, { title: GOAL_BATCH_TEMPLATE_TITLE }),
+ node('a2', 'decision', 41, { title: GOAL_BATCH_ASSAY_TITLE }),
+ node('m4b', 'task', 42, { title: 'U4' }),
+ ],
+ state: { assayNodeId: 'a2', massNodeIds: ['m3', 'm4'], probeNodeIds: ['m4b'] },
+ }),
+ NOW,
+ );
+ // Wave 1 (U3–U6) went out under v1; wave 2 (U7–U10) has not gone out — it
+ // waits under v2, the latest plan.
+ expect(buildBatchModel(graph, 'batch').waveRounds).toEqual([1, 2]);
+ });
+});
+
+describe('plans and re-opened rows', () => {
+ it('finds the round a plan version belongs to', () => {
+ const graph = buildGoalGraphView(
+ batchSnapshot({
+ decisions: [humanAnswer('a1')],
+ extraEdges: [edge('t2', 't1', 'revises')],
+ extraNodes: [
+ node('t2', 'finding', 40, { title: GOAL_BATCH_TEMPLATE_TITLE }),
+ node('a2', 'decision', 41, { title: GOAL_BATCH_ASSAY_TITLE }),
+ ],
+ state: { assayNodeId: 'a2', probeNodeIds: [], templateNodeId: 't2' },
+ }),
+ NOW,
+ );
+ expect(findBatchPlan(graph, 't2')?.round.revision).toBe(2);
+ expect(findBatchPlan(graph, 'a2')).toBeUndefined();
+ });
+
+ it('groups re-opened units by the batch they came from', () => {
+ const probe = (nodeId: string, wave: number) => ({
+ from: { index: 0, kind: 'wave' as const, wave },
+ nodeId,
+ state: 'backlog' as const,
+ title: nodeId,
+ });
+ const rows = reopenedRows([probe('a', 2), probe('b', 2), probe('c', 3)], 10);
+ expect(rows.map((row) => [row.from, row.probes.map((p) => p.nodeId)])).toEqual([
+ [{ index: 0, kind: 'wave', wave: 2 }, ['a', 'b']],
+ [{ index: 0, kind: 'wave', wave: 3 }, ['c']],
+ ]);
+ });
+});
+
+describe('layoutBatch', () => {
+ it('lays the cold start and each round left to right, each break feeding the next round', () => {
+ const graph = buildGoalGraphView(
+ batchSnapshot({
+ decisions: [humanAnswer('a1'), humanAnswer('a2')],
+ extraEdges: [
+ edge('t2', 't1', 'revises'),
+ edge('t3', 't2', 'revises'),
+ edge('a2', 'p2b', 'depends_on'),
+ edge('a3', 'm7b', 'depends_on'),
+ edge('p2b', 'p2', 'derived_from'),
+ edge('m7b', 'm7', 'derived_from'),
+ ],
+ extraNodes: [
+ node('m3', 'task', 10, { status: 'resolved', title: 'U3' }),
+ node('t2', 'finding', 40, { title: GOAL_BATCH_TEMPLATE_TITLE }),
+ node('a2', 'decision', 41, { title: GOAL_BATCH_ASSAY_TITLE }),
+ node('p2b', 'task', 42, { status: 'resolved', title: 'U2' }),
+ // U7 opens the roster's second wave, released under v2 — then broke.
+ node('m7', 'task', 50, { status: 'retired', title: 'U7' }),
+ node('t3', 'finding', 60, { title: GOAL_BATCH_TEMPLATE_TITLE }),
+ node('a3', 'decision', 61, { title: GOAL_BATCH_ASSAY_TITLE }),
+ node('m7b', 'task', 62, { title: 'U7' }),
+ ],
+ state: { assayNodeId: 'a3', massNodeIds: ['m3', 'm7'], probeNodeIds: ['m7b'] },
+ }),
+ NOW,
+ );
+ const model = buildBatchModel(graph, 'batch');
+ const layout = layoutBatch(graph, model);
+ const cold = layout.boxes[batchGroupId('batch', 'experimentProbe')];
+ const [r1, r2, r3] = [1, 2, 3].map((r) => layout.boxes[batchGroupId('batch', 'round', r)]);
+
+ // One row, left to right, top-aligned: cold start, then round 1, 2, 3.
+ expect([cold, r1, r2, r3].map((box) => box.y)).toEqual([0, 0, 0, 0]);
+ expect(cold.x + cold.width).toBeLessThan(r1.x);
+ expect(r1.x + r1.width).toBeLessThan(r2.x);
+ expect(r2.x + r2.width).toBeLessThan(r3.x);
+ // Each round feeds the next — the break at v2's gate revises into v3 —
+ // and only the hand-offs after a break carry the "revise" label.
+ const frame = (r: number) => batchGroupId('batch', 'round', r);
+ expect(
+ layout.edges.filter((e) => e.sourceHandle === 'r').map((e) => [e.source, e.target, e.label]),
+ ).toEqual([
+ [batchGroupId('batch', 'experimentProbe'), frame(1), undefined],
+ [frame(1), frame(2), 'revise'],
+ [frame(2), frame(3), 'revise'],
+ ]);
+ // Plan, gate and waves stay their own nodes, stacked top to bottom inside
+ // their round's frame and linked plan → gate → waves.
+ const rounds = [
+ ['t1', 'a1', 1, r1],
+ ['t2', 'a2', 2, r2],
+ ['t3', 'a3', 3, r3],
+ ] as const;
+ for (const [plan, gate, r, box] of rounds) {
+ const waves = batchGroupId('batch', 'waves', r);
+ const column = [plan, gate, waves].map((id) => layout.boxes[id]);
+ for (const inner of column) {
+ expect(inner.x).toBeGreaterThanOrEqual(box.x);
+ expect(inner.x + inner.width).toBeLessThanOrEqual(box.x + box.width);
+ expect(inner.y + inner.height).toBeLessThanOrEqual(box.y + box.height);
+ }
+ expect(column[0].y).toBeLessThan(column[1].y);
+ expect(column[1].y).toBeLessThan(column[2].y);
+ expect(
+ layout.edges
+ .filter((e) => !e.sourceHandle && [plan, gate].includes(e.source as never))
+ .map((e) => [e.source, e.target]),
+ ).toEqual([
+ [plan, gate],
+ [gate, waves],
+ ]);
+ expect(layout.nodeIds.has(plan) && layout.nodeIds.has(gate)).toBe(true);
+ }
+ // Links into the batch land on the cold start, lined up under the problem.
+ expect(layout.entryId).toBe(batchGroupId('batch', 'experimentProbe'));
+ expect(layout.anchorX).toBe(cold.x + cold.width / 2);
+ // The re-opened unit is named by the batch it first ran in.
+ expect(model.rounds[2].probes[0].from).toEqual({ index: 0, kind: 'wave', wave: 1 });
+ });
+});
+
+describe('buildBatchModel roster', () => {
+ it('keeps a delivered unit in the history after a restart re-cuts the owed roster', () => {
+ const graph = buildGoalGraphView(
+ batchSnapshot({
+ extraNodes: [node('m3', 'task', 10, { status: 'resolved', title: 'U3' })],
+ // The restart left only what is still owed; U3 was delivered.
+ state: { massNodeIds: ['m3'], unitTitles: ROSTER.filter((title) => title !== 'U3') },
+ }),
+ NOW,
+ );
+ const model = buildBatchModel(graph, 'batch');
+
+ expect(model.waves[0][0]).toMatchObject({ nodeId: 'm3', state: 'done', title: 'U3' });
+ });
+
+ it('follows a deferred unit to the wave that re-delivered it', () => {
+ const graph = buildGoalGraphView(
+ batchSnapshot({
+ extraNodes: [
+ // U3 broke in its wave and did not fit in the restarted canary…
+ node('m3', 'task', 10, { status: 'retired', title: 'U3' }),
+ // …so a later wave re-delivered it as a new task.
+ node('m3b', 'task', 20, { status: 'resolved', title: 'U3' }),
+ ],
+ state: { massNodeIds: ['m3b'] },
+ }),
+ NOW,
+ );
+ const model = buildBatchModel(graph, 'batch');
+
+ expect(model.waves[0][0]).toMatchObject({ nodeId: 'm3b', state: 'done', title: 'U3' });
+ });
+});
diff --git a/src/features/AgentGoals/ProcessControl/Graph/batchModel.ts b/src/features/AgentGoals/ProcessControl/Graph/batchModel.ts
new file mode 100644
index 00000000000..b3ea08269b1
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/Graph/batchModel.ts
@@ -0,0 +1,462 @@
+import {
+ GOAL_BATCH_ASSAY_TITLE,
+ GOAL_BATCH_TEMPLATE_TITLE,
+ ROLLOUT_WAVE_SIZE_DEFAULT,
+} from '@lobechat/const/goal';
+import type {
+ GoalRolloutGateCheck,
+ GoalRolloutGateCheckKey,
+ GoalRolloutGateEvaluation,
+ GoalRolloutPhase,
+} from '@lobechat/types';
+import { experimentMembers } from '@lobechat/utils/goalGraph';
+
+import { type GoalGraphView, type GoalNodeView, isRunningNode } from '../goalGraphViewModel';
+
+/**
+ * Read model for one expanded `batch` container (STAMP).
+ *
+ * The coordinator stores a batch as plain graph nodes — Templates, Assays and
+ * unit tasks inside one container — plus `rolloutState` on the goal. A flat
+ * layout of those nodes reads as N sibling cards, which is exactly the fan-out
+ * a batch exists to avoid. This model regroups them into what the person
+ * actually follows: the first round's probes, the recipe and its gate, the
+ * roster as waves of squares, and one column per re-opened round (v2, v3…).
+ */
+
+/** One square's state: not run / running / needs a person / done / superseded. */
+export type BatchCellState = 'backlog' | 'running' | 'human' | 'done' | 'stale';
+
+export interface BatchCell {
+ /** 0-based position inside its wave. */
+ index: number;
+ /** The node that delivers this unit on the main roster, once released. */
+ nodeId?: string;
+ /** The later round the unit was re-opened in (its square here is superseded). */
+ reopenedIn?: number;
+ /** A unit a later round first released: it never ran here, it runs there. */
+ runIn?: number;
+ state: BatchCellState;
+ title: string;
+ /** 0-based wave. */
+ wave: number;
+}
+
+/** Where a re-opened unit came from, for the "re-opened from …" label. */
+export type BatchUnitOrigin =
+ | { kind: 'probe'; index: number }
+ | { kind: 'round'; revision: number }
+ | { index: number; kind: 'wave'; wave: number };
+
+export interface BatchProbe {
+ from?: BatchUnitOrigin;
+ nodeId: string;
+ state: BatchCellState;
+ title: string;
+}
+
+/** `locked` until its probes settle, `checking` once they did, `rejected` when a person sent it back. */
+export type BatchGateState = 'locked' | 'checking' | 'passed' | 'human' | 'rejected';
+
+/**
+ * A gate verdict, plus which roster wave a release put out. The coordinator's
+ * `waveIndex` restarts with each round; the roster's waves do not, and every
+ * release puts out exactly the next one — so the wave is the release's ordinal.
+ */
+export interface BatchGateVerdict extends GoalRolloutGateEvaluation {
+ wave?: number;
+}
+
+export interface BatchRound {
+ assayId?: string;
+ /** This round's gate verdicts, oldest first — what the gate actually judged. */
+ evaluations: BatchGateVerdict[];
+ /** Answered as "a new class", not as a revision of the previous recipe. */
+ forked: boolean;
+ gate: BatchGateState;
+ /** Which group the break that opened this round surfaced in (rounds ≥ 2). */
+ origin?:
+ | { kind: 'probes' }
+ | { kind: 'round'; revision: number }
+ /** `wave`: the 0-based roster wave the re-opened units ran in. */
+ | { kind: 'waves'; wave: number };
+ probes: BatchProbe[];
+ /** 1-based recipe revision. */
+ revision: number;
+ templateId?: string;
+}
+
+/**
+ * One condition the release gate will check, before any verdict exists —
+ * mirroring the coordinator's `evaluateRolloutGate`: the same keys in the same
+ * order, and axis coverage when declared.
+ */
+export interface BatchGateCheck {
+ key: GoalRolloutGateCheckKey;
+}
+
+export interface BatchModel {
+ batchId: string;
+ /** Other decisions inside the batch — e.g. a machine gate on one unit. */
+ decisionIds: string[];
+ /** What the gate checks, for a round no verdict has reached yet. */
+ gateChecks: BatchGateCheck[];
+ phase?: GoalRolloutPhase;
+ rounds: BatchRound[];
+ /**
+ * 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
+ * latest round — so after v2 opens, the rest of the roster moves under v2.
+ */
+ waveRounds: number[];
+ /** The roster outside the first round's probes, chunked into waves. */
+ waves: BatchCell[][];
+ waveSize: number;
+}
+
+const byCreatedAt = (a: GoalNodeView, b: GoalNodeView) =>
+ new Date(a.node.createdAt).getTime() - new Date(b.node.createdAt).getTime();
+
+export const batchCellState = (
+ view: GoalNodeView | undefined,
+ waitingOn: ReadonlySet<string>,
+): BatchCellState => {
+ if (!view) return 'backlog';
+ const { status } = view.node;
+ // Retired is superseded; rejected is a unit that broke and waits on a person.
+ if (status === 'retired') return 'stale';
+ if (status === 'rejected') return 'human';
+ if (status === 'resolved') return 'done';
+ if (status === 'waiting' || view.decision || view.isStale || waitingOn.has(view.node.id))
+ return 'human';
+ if (isRunningNode(view)) return 'running';
+ return 'backlog';
+};
+
+export const buildBatchModel = (graph: GoalGraphView, batchId: string): BatchModel => {
+ const shape = { edges: graph.edges, nodes: graph.nodes.map((view) => view.node) };
+ const memberIds = experimentMembers(shape, batchId, false);
+ const members = graph.nodes.filter((view) => memberIds.has(view.node.id)).sort(byCreatedAt);
+ const config = graph.goal.config;
+ const state = config?.rolloutState?.batchNodeId === batchId ? config.rolloutState : undefined;
+ const waveSize = Math.max(1, config?.rollout?.waveSize ?? ROLLOUT_WAVE_SIZE_DEFAULT);
+
+ // A unit waits on a person when an open decision names it as its subject.
+ const waitingOn = new Set(
+ graph.nodes
+ .filter((view) => view.node.kind === 'decision' && view.node.status === 'waiting')
+ .map((view) => view.gateSubjectId)
+ .filter((id): id is string => !!id),
+ );
+ // A unit that failed its own check held the batch (R6): its node can still
+ // read active, but the batch is waiting on a person because of it.
+ const held = state?.phase === 'pattern_break' ? state.gateLog?.at(-1) : undefined;
+ if (held?.trigger === 'unit' && held.nodeId) waitingOn.add(held.nodeId);
+ // A unit a later round re-opened (`derived_from` it) is superseded, whatever
+ // state it ended in — a rejected trial must not read "needs you" forever.
+ const superseded = new Set(
+ graph.edges.filter((edge) => edge.kind === 'derived_from').map((edge) => edge.targetNodeId),
+ );
+ const cellOf = (id?: string): BatchCellState =>
+ id && superseded.has(id) ? 'stale' : batchCellState(id ? graph.byId[id] : undefined, waitingOn);
+
+ const templates = members.filter(
+ (view) => view.node.kind === 'finding' && view.node.title === GOAL_BATCH_TEMPLATE_TITLE,
+ );
+ const assays = members.filter(
+ (view) => view.node.kind === 'decision' && view.node.title === GOAL_BATCH_ASSAY_TITLE,
+ );
+ const tasks = members.filter((view) => view.node.kind === 'task');
+
+ // Each Assay gates exactly the probes of its own round.
+ const gatedBy = (assayId: string) =>
+ graph.edges
+ .filter((edge) => edge.kind === 'depends_on' && edge.sourceNodeId === assayId)
+ .map((edge) => edge.targetNodeId)
+ .filter((id) => memberIds.has(id));
+ const roundCount = Math.max(templates.length, assays.length, 1);
+ const probeIdsByRound = Array.from({ length: roundCount }, (_, r) => {
+ const assay = assays[r];
+ if (assay) return gatedBy(assay.node.id);
+ return r === roundCount - 1 && assays.length > 0 ? (state?.probeNodeIds ?? []) : [];
+ });
+ const roundOfProbe = new Map<string, number>();
+ probeIdsByRound.forEach((ids, r) => ids.forEach((id) => roundOfProbe.set(id, r)));
+
+ // The roster in delivery order; the first round's probes run as cards, the
+ // rest of the roster is what the waves deliver.
+ const firstProbeTitles = new Set(
+ probeIdsByRound[0].map((id) => graph.byId[id]?.node.title).filter(Boolean),
+ );
+ // History reads the full roster the batch was planned with: a restart re-cuts
+ // `unitTitles` to what is still owed, which would drop the units already
+ // delivered from the map. The state roster is the fallback for old batches.
+ const roster =
+ config?.rollout?.units ??
+ state?.unitTitles ??
+ tasks.filter((view) => !roundOfProbe.has(view.node.id)).map((view) => view.node.title);
+ const pending = roster.filter((title) => !firstProbeTitles.has(title));
+
+ const tasksByTitle = new Map<string, GoalNodeView[]>();
+ for (const view of tasks)
+ tasksByTitle.set(view.node.title, [...(tasksByTitle.get(view.node.title) ?? []), view]);
+
+ const waves: BatchCell[][] = [];
+ const waveOf = new Map<string, { index: number; wave: number }>();
+ pending.forEach((title, position) => {
+ const wave = Math.floor(position / waveSize);
+ const index = position % waveSize;
+ const nodes = tasksByTitle.get(title) ?? [];
+ // The newest delivery on the main roster: a broken unit that did not fit in
+ // the restarted canary is re-delivered by a later wave as a new task, and
+ // the cell must follow that one, not the original that broke.
+ const mainNodes = nodes.filter((view) => !roundOfProbe.has(view.node.id));
+ const main = mainNodes.at(-1);
+ // Every earlier slot still names where a re-opened unit first ran.
+ for (const earlier of mainNodes.slice(0, -1)) waveOf.set(earlier.node.id, { index, wave });
+ const later = nodes.find((view) => (roundOfProbe.get(view.node.id) ?? 0) > 0);
+ const laterRound = later ? roundOfProbe.get(later.node.id)! + 1 : undefined;
+ if (main) waveOf.set(main.node.id, { index, wave });
+ (waves[wave] ??= []).push(
+ main
+ ? {
+ index,
+ nodeId: main.node.id,
+ reopenedIn: laterRound,
+ // Re-opened in a later round: what ran here is superseded.
+ state: later ? 'stale' : cellOf(main.node.id),
+ title,
+ wave,
+ }
+ : {
+ index,
+ // Never released here: the square follows the round that runs it.
+ nodeId: later?.node.id,
+ runIn: laterRound,
+ state: cellOf(later?.node.id),
+ title,
+ wave,
+ },
+ );
+ });
+
+ // A released unit went out under the latest plan at the time it was created.
+ const roundAt = (view: GoalNodeView) => {
+ let round = 1;
+ templates.forEach((template, r) => {
+ if (byCreatedAt(template, view) <= 0) round = r + 1;
+ });
+ return round;
+ };
+ const waveRounds = waves.map((wave) => {
+ const released = wave.find((cell) => cell.nodeId && !cell.runIn);
+ if (released?.nodeId && graph.byId[released.nodeId])
+ return roundAt(graph.byId[released.nodeId]);
+ const runIn = wave.find((cell) => cell.runIn)?.runIn;
+ return runIn ?? roundCount;
+ });
+
+ // Where a re-opened unit ran before: the most recent earlier node with its title.
+ const originOf = (view: GoalNodeView): BatchUnitOrigin | undefined => {
+ const earlier = (tasksByTitle.get(view.node.title) ?? []).filter(
+ (other) => other !== view && byCreatedAt(other, view) < 0,
+ );
+ const previous = earlier.at(-1);
+ if (!previous) return undefined;
+ const round = roundOfProbe.get(previous.node.id);
+ if (round === 0) return { index: probeIdsByRound[0].indexOf(previous.node.id), kind: 'probe' };
+ // Re-opened again: follow it back to the batch it first ran in (第 3 批),
+ // naming the round only when there is no batch to name.
+ if (round !== undefined) return originOf(previous) ?? { kind: 'round', revision: round + 1 };
+ const slot = waveOf.get(previous.node.id);
+ return slot ? { ...slot, kind: 'wave' } : undefined;
+ };
+
+ // The coordinator writes each release's roster wave; a verdict from before it
+ // did falls back to counting the releases kept in the log.
+ let releases = 0;
+ const verdicts: BatchGateVerdict[] = (state?.gateLog ?? []).map((entry) => {
+ if (entry.outcome !== 'released') return entry;
+ releases = entry.wave ?? releases + 1;
+ return { ...entry, wave: releases };
+ });
+
+ const rounds: BatchRound[] = probeIdsByRound.map((ids, r) => {
+ const probes = ids
+ .map((id) => graph.byId[id])
+ .filter((view): view is GoalNodeView => !!view)
+ .sort(byCreatedAt)
+ .map((view) => ({
+ from: r > 0 ? originOf(view) : undefined,
+ nodeId: view.node.id,
+ state: cellOf(view.node.id),
+ title: view.node.title,
+ }));
+ const template = templates[r];
+ const assay = assays[r];
+ const previousTemplate = templates[r - 1];
+ const forked =
+ r > 0 &&
+ !!template &&
+ !!previousTemplate &&
+ !graph.edges.some(
+ (edge) =>
+ edge.kind === 'revises' &&
+ edge.sourceNodeId === template.node.id &&
+ edge.targetNodeId === previousTemplate.node.id,
+ );
+ return {
+ assayId: assay?.node.id,
+ evaluations: verdicts.filter((entry) => entry.revision === r + 1),
+ forked,
+ gate: gateState(assay, r === roundCount - 1, state?.phase, probes),
+ origin: r > 0 ? roundOrigin(probes, r) : undefined,
+ probes,
+ revision: r + 1,
+ templateId: template?.node.id,
+ };
+ });
+
+ const assayIds = new Set(assays.map((view) => view.node.id));
+ const decisionIds = members
+ .filter((view) => view.node.kind === 'decision' && !assayIds.has(view.node.id))
+ .map((view) => view.node.id);
+
+ const policy = config?.rollout;
+ const gateChecks: BatchGateCheck[] = [
+ { key: 'units_settled' },
+ { key: 'units_succeeded' },
+ { key: 'no_open_decision' },
+ { key: 'plan_written' },
+ ...(policy?.spec?.variantAxes?.length ? [{ key: 'axes_covered' as const }] : []),
+ ];
+
+ return {
+ batchId,
+ decisionIds,
+ gateChecks,
+ phase: state?.phase,
+ rounds,
+ waveRounds,
+ waves,
+ waveSize,
+ };
+};
+
+const gateState = (
+ assay: GoalNodeView | undefined,
+ current: boolean,
+ phase: GoalRolloutPhase | undefined,
+ probes: BatchProbe[],
+): BatchGateState => {
+ if (assay && (assay.decision || assay.node.status === 'waiting')) return 'human';
+ if (!current) return assay?.humanTouches.length ? 'rejected' : 'passed';
+ if (phase === 'mass' || phase === 'done') return 'passed';
+ if (phase === 'pattern_break') return 'human';
+ const settled = probes.length > 0 && probes.every((probe) => probe.state === 'done');
+ return settled ? 'checking' : 'locked';
+};
+
+/** A round re-opens units from where they broke; the first one names the source. */
+const roundOrigin = (probes: BatchProbe[], r: number): BatchRound['origin'] => {
+ const from = probes.find((probe) => probe.from)?.from;
+ if (from?.kind === 'wave') return { kind: 'waves', wave: from.wave };
+ if (from?.kind === 'round') return { kind: 'round', revision: from.revision };
+ if (from?.kind === 'probe' || r === 1) return { kind: 'probes' };
+ return { kind: 'round', revision: r };
+};
+
+export const countCells = (cells: { state: BatchCellState }[]) => {
+ const counts: Record<BatchCellState, number> = {
+ backlog: 0,
+ done: 0,
+ human: 0,
+ running: 0,
+ stale: 0,
+ };
+ for (const cell of cells) counts[cell.state] += 1;
+ return counts;
+};
+
+/**
+ * The batch and round a release gate belongs to, when `nodeId` is one — so a
+ * surface that opens the gate can show its verdicts rather than a bare decision.
+ */
+export const findBatchGate = (
+ graph: GoalGraphView,
+ nodeId: string,
+): { model: BatchModel; round: BatchRound } | undefined => {
+ const batchId = graph.edges.find(
+ (edge) =>
+ edge.kind === 'contains' &&
+ edge.targetNodeId === nodeId &&
+ graph.byId[edge.sourceNodeId]?.node.kind === 'batch',
+ )?.sourceNodeId;
+ if (!batchId) return undefined;
+ const model = buildBatchModel(graph, batchId);
+ const round = model.rounds.find((item) => item.assayId === nodeId);
+ return round ? { model, round } : undefined;
+};
+
+/**
+ * The checks a verdict stands on. A unit that failed its own check (R6) held
+ * the batch without the gate running, so it records none — it reads as the one
+ * check it broke, naming the unit.
+ */
+export const verdictChecks = (evaluation: GoalRolloutGateEvaluation): GoalRolloutGateCheck[] =>
+ evaluation.trigger === 'unit'
+ ? [
+ {
+ key: 'units_succeeded',
+ nodeIds: evaluation.nodeId ? [evaluation.nodeId] : undefined,
+ passed: false,
+ },
+ ]
+ : evaluation.checks;
+
+/**
+ * A round's re-opened units as rows, grouped by where they came from — so each
+ * row can say which batch it is (第 3 批) — and capped at the wave size.
+ */
+export const reopenedRows = (
+ probes: BatchProbe[],
+ waveSize: number,
+): { from?: BatchUnitOrigin; probes: BatchProbe[] }[] => {
+ const groups = new Map<string, BatchProbe[]>();
+ for (const probe of probes) {
+ const from = probe.from;
+ const key =
+ from?.kind === 'wave'
+ ? `wave:${from.wave}`
+ : from?.kind === 'round'
+ ? `round:${from.revision}`
+ : (from?.kind ?? 'none');
+ groups.set(key, [...(groups.get(key) ?? []), probe]);
+ }
+ return [...groups.values()].flatMap((group) =>
+ Array.from({ length: Math.ceil(group.length / waveSize) }, (_, i) => ({
+ from: group[0].from,
+ probes: group.slice(i * waveSize, (i + 1) * waveSize),
+ })),
+ );
+};
+
+/**
+ * The batch and round a plan version belongs to, when `nodeId` is one — so the
+ * panel that opens on it can show every version and what changed between them.
+ */
+export const findBatchPlan = (
+ graph: GoalGraphView,
+ nodeId: string,
+): { model: BatchModel; round: BatchRound } | undefined => {
+ const batchId = graph.edges.find(
+ (edge) =>
+ edge.kind === 'contains' &&
+ edge.targetNodeId === nodeId &&
+ graph.byId[edge.sourceNodeId]?.node.kind === 'batch',
+ )?.sourceNodeId;
+ if (!batchId) return undefined;
+ const model = buildBatchModel(graph, batchId);
+ const round = model.rounds.find((item) => item.templateId === nodeId);
+ return round ? { model, round } : undefined;
+};
diff --git a/src/features/AgentGoals/ProcessControl/Graph/edgeRouting.test.ts b/src/features/AgentGoals/ProcessControl/Graph/edgeRouting.test.ts
index d87a2dfa2e8..a570f4064a3 100644
--- a/src/features/AgentGoals/ProcessControl/Graph/edgeRouting.test.ts
+++ b/src/features/AgentGoals/ProcessControl/Graph/edgeRouting.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { edgeDirection, routeEdge, segmentHitsBox } from './edgeRouting';
+import { edgeDirection, routeEdge, segmentHitsBox, sideToSidePath } from './edgeRouting';
import { experimentStatusVisual } from './experimentStatus';
const boxes = [
@@ -43,6 +43,14 @@ describe('exploration relations and status', () => {
expect(first[0]).toEqual(second[0]);
expect(first.at(-1)).toEqual(second.at(-1));
});
+ it('runs a side-to-side link horizontally with its vertical centred between the two', () => {
+ expect(sideToSidePath({ x: 300, y: 700 }, { x: 500, y: 300 })).toEqual([
+ { x: 300, y: 700 },
+ { x: 400, y: 700 },
+ { x: 400, y: 300 },
+ { x: 500, y: 300 },
+ ]);
+ });
it('never uses the running-ring fallback for waiting, completed or unstarted experiments', () => {
const states = ['proposed', 'waiting', 'resolved'] as const;
expect(states.every((s) => experimentStatusVisual(s).icon)).toBe(true);
diff --git a/src/features/AgentGoals/ProcessControl/Graph/edgeRouting.ts b/src/features/AgentGoals/ProcessControl/Graph/edgeRouting.ts
index 8216c7289af..a79acf21fca 100644
--- a/src/features/AgentGoals/ProcessControl/Graph/edgeRouting.ts
+++ b/src/features/AgentGoals/ProcessControl/Graph/edgeRouting.ts
@@ -26,6 +26,15 @@ export const segmentHitsBox = (a: Point, b: Point, box: LayoutBox): boolean =>
Math.max(a.x, b.x) > box.x &&
Math.min(a.x, b.x) < box.x + box.width;
+/**
+ * A side-to-side link — out of the source's right, into the target's left:
+ * horizontal, then vertical exactly midway between the two, then horizontal.
+ */
+export const sideToSidePath = (source: Point, target: Point): Point[] => {
+ const midX = (source.x + target.x) / 2;
+ return [source, { x: midX, y: source.y }, { x: midX, y: target.y }, target];
+};
+
/** Route through free row/column gutters; frames are boundaries, leaf cards are obstacles. */
export const routeEdge = (
source: Point,
diff --git a/src/features/AgentGoals/ProcessControl/Graph/experimentStatus.test.ts b/src/features/AgentGoals/ProcessControl/Graph/experimentStatus.test.ts
new file mode 100644
index 00000000000..7a6421f7ddb
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/Graph/experimentStatus.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from 'vitest';
+
+import { batchContainerStatus } from './experimentStatus';
+
+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('pattern_break')).toBe('waiting');
+ expect(batchContainerStatus('done')).toBe('resolved');
+ });
+
+ it('leaves a batch with no rollout state to its node', () => {
+ expect(batchContainerStatus(undefined)).toBeUndefined();
+ });
+});
diff --git a/src/features/AgentGoals/ProcessControl/Graph/experimentStatus.ts b/src/features/AgentGoals/ProcessControl/Graph/experimentStatus.ts
index 02d17817756..e8f97cecbc0 100644
--- a/src/features/AgentGoals/ProcessControl/Graph/experimentStatus.ts
+++ b/src/features/AgentGoals/ProcessControl/Graph/experimentStatus.ts
@@ -1,4 +1,4 @@
-import type { GoalNodeStatus } from '@lobechat/types';
+import type { GoalNodeStatus, GoalRolloutPhase } from '@lobechat/types';
import { TASK_STATUS_VISUALS } from '@/components/ExecutionStatus';
@@ -14,3 +14,25 @@ export const experimentStatusVisual = (status: GoalNodeStatus) => {
};
return visuals[status];
};
+
+/**
+ * What an open batch is doing, from its rollout phase. The batch node itself
+ * is created `proposed` and never moves, so its own status says nothing.
+ */
+export const batchContainerStatus = (phase?: GoalRolloutPhase): GoalNodeStatus | undefined => {
+ switch (phase) {
+ case 'done': {
+ return 'resolved';
+ }
+ case 'pattern_break': {
+ return 'waiting';
+ }
+ case 'probe':
+ case 'mass': {
+ return 'active';
+ }
+ default: {
+ return undefined;
+ }
+ }
+};
diff --git a/src/features/AgentGoals/ProcessControl/Graph/explorationMap.ts b/src/features/AgentGoals/ProcessControl/Graph/explorationMap.ts
index a4af639403e..db006d0d8ba 100644
--- a/src/features/AgentGoals/ProcessControl/Graph/explorationMap.ts
+++ b/src/features/AgentGoals/ProcessControl/Graph/explorationMap.ts
@@ -2,6 +2,19 @@ import type { GoalGraphEdge, GoalGraphNode, GoalNodeKind } from '@lobechat/types
import { type LayoutBox, layoutGraph } from './layout';
+/**
+ * A container that lays out its own members (an expanded batch): the frame
+ * size, member boxes relative to the frame, and which members it shows.
+ */
+export interface ContainerLayout {
+ /** The column links into the container land on; it is lined up under the parent. */
+ anchorX?: number;
+ boxes: Record<string, LayoutBox>;
+ height: number;
+ nodeIds: ReadonlySet<string>;
+ width: number;
+}
+
export interface ExplorationEdge extends GoalGraphEdge {
originalSource: string;
originalTarget: string;
@@ -14,6 +27,7 @@ export const explorationMap = (
edges: GoalGraphEdge[],
collapsed: ReadonlySet<string>,
hiddenKinds: ReadonlySet<GoalNodeKind> = new Set(),
+ containerLayouts: ReadonlyMap<string, ContainerLayout> = new Map(),
) => {
const byId = new Map(nodes.map((node) => [node.id, node]));
const owner = new Map(
@@ -33,7 +47,16 @@ export const explorationMap = (
}
return result;
};
- const visible = nodes.filter((node) => representative(node.id) === node.id);
+ // A container with its own layout shows only the members it placed, and
+ // draws its own links between them.
+ const custom = (id: string) => {
+ const container = owner.get(id);
+ return container && !collapsed.has(container) ? containerLayouts.get(container) : undefined;
+ };
+ const visible = nodes.filter(
+ (node) =>
+ representative(node.id) === node.id && (custom(node.id)?.nodeIds.has(node.id) ?? true),
+ );
const visibleIds = new Set(visible.map((node) => node.id));
const parents = new Map<string, string>();
for (const node of visible) {
@@ -52,6 +75,7 @@ export const explorationMap = (
for (const edge of edges) {
if (edge.kind === 'contains' || !byId.has(edge.sourceNodeId) || !byId.has(edge.targetNodeId))
continue;
+ if (custom(edge.sourceNodeId) || custom(edge.targetNodeId)) continue;
const sourceNodeId = representative(edge.sourceNodeId);
const targetNodeId = representative(edge.targetNodeId);
if (!sourceNodeId || !targetNodeId || sourceNodeId === targetNodeId) continue;
@@ -81,7 +105,13 @@ export const explorationMap = (
const members = children(scope);
const sizes: Record<string, Pick<LayoutBox, 'width' | 'height'>> = {};
for (const node of members) {
- if (node.kind === 'experiment' && !collapsed.has(node.id)) {
+ const own = collapsed.has(node.id) ? undefined : containerLayouts.get(node.id);
+ if (own) {
+ sizes[node.id] = { height: own.height, width: own.width };
+ for (const id of own.nodeIds) if (own.boxes[id]) boxes[id] = own.boxes[id];
+ continue;
+ }
+ if ((node.kind === 'experiment' || node.kind === 'batch') && !collapsed.has(node.id)) {
const inner = measure(node.id);
const values = Object.values(inner);
const left = Math.min(0, ...values.map((box) => box.x));
@@ -102,7 +132,18 @@ export const explorationMap = (
? [{ ...edge, sourceNodeId, targetNodeId }]
: [];
});
- return layoutGraph(members, ranking, sizes, { column: 64, rank: 96 });
+ const placed = layoutGraph(members, ranking, sizes, { column: 64, rank: 96 });
+ // A container with its own layout lands its incoming link on one column,
+ // not its middle: slide it so that column sits under the parent and the
+ // link runs straight — unless that would push into a neighbour.
+ for (const node of members) {
+ const own = collapsed.has(node.id) ? undefined : containerLayouts.get(node.id);
+ const box = placed[node.id];
+ if (own?.anchorX === undefined || !box) continue;
+ const alone = !members.some((other) => other.id !== node.id && placed[other.id]?.y === box.y);
+ if (alone) box.x += box.width / 2 - own.anchorX;
+ }
+ return placed;
};
Object.assign(boxes, measure());
const visit = (parent?: string) => {
diff --git a/src/features/AgentGoals/ProcessControl/Graph/index.tsx b/src/features/AgentGoals/ProcessControl/Graph/index.tsx
index e439d024eaa..823bffd99b0 100644
--- a/src/features/AgentGoals/ProcessControl/Graph/index.tsx
+++ b/src/features/AgentGoals/ProcessControl/Graph/index.tsx
@@ -21,10 +21,11 @@ import {
useReactFlow,
} from '@xyflow/react';
import { createStaticStyles, cssVar, cx } from 'antd-style';
-import { ChevronRight, Maximize2, X } from 'lucide-react';
+import { ChevronRight, DoorOpen, HandIcon, Maximize2, X } from 'lucide-react';
import { memo, type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { TASK_STATUS_VISUALS } from '@/components/ExecutionStatus';
import { PortalContent } from '@/features/Portal/router';
import { usePortalPanelWidth } from '@/features/Portal/usePortalPanelWidth';
import RightPanel from '@/features/RightPanel';
@@ -32,20 +33,43 @@ import { useIsDark } from '@/hooks/useIsDark';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
-import { type GoalGraphNodeKind, graphNodeKind, graphNodeLabel } from '../../Experiments/model';
+import {
+ type GoalGraphNodeKind,
+ graphNodeKind,
+ graphNodeLabel,
+ isContainerKind,
+} from '../../Experiments/model';
+import { useGateCheckCopy } from '../BatchGate/useGateCheckCopy';
import {
type GoalGraphView,
type GoalNodeView,
isRunningNode,
scopeGraphView,
} from '../goalGraphViewModel';
-import { KindDot } from '../shared';
+import { GATE_COLOR, KindDot } from '../shared';
+import {
+ BatchExperimentProbeGroup,
+ BatchRoundFrame,
+ type BatchRoundFrameData,
+ type BatchWavesData,
+ BatchWavesGroup,
+ CELL_VISUAL,
+} from './BatchGroups';
+import { type BatchLayout, layoutBatch } from './batchLayout';
+import {
+ type BatchGateState,
+ type BatchModel,
+ type BatchRound,
+ buildBatchModel,
+ verdictChecks,
+} from './batchModel';
import { edgeDirection } from './edgeRouting';
import ExperimentGroup, { type ExperimentGroupData } from './ExperimentGroup';
+import { batchContainerStatus } from './experimentStatus';
import ExplorationEdge from './ExplorationEdge';
import { explorationMap } from './explorationMap';
-import GraphNodeView, { GhostNodeView, type GraphNodeData } from './GraphNode';
-import { type GraphBridge, hideKinds, layoutGraph, NODE_WIDTH } from './layout';
+import GraphNodeView, { GhostNodeView, type GraphNodeData, type StateChip } from './GraphNode';
+import { type GraphBridge, hideKinds, type LayoutBox, layoutGraph, NODE_WIDTH } from './layout';
import {
edgeMarkerColor,
type EdgeTone,
@@ -56,7 +80,7 @@ import {
nodeEmphasis,
resolveMainline,
} from './mainline';
-import { type MeasuredSizes, mergeMeasuredSizes } from './measuredSizes';
+import { flowNodeSize, type MeasuredSizes, mergeMeasuredSizes } from './measuredSizes';
import { revealCenter } from './revealNode';
import { useExplorationNavigation } from './useExplorationNavigation';
import { useFitViewOnResize } from './useFitViewOnResize';
@@ -343,12 +367,99 @@ const useEdgeLabel = () => {
const edgeTypes = { exploration: ExplorationEdge };
const nodeTypes = {
+ goalBatchExperimentProbe: BatchExperimentProbeGroup,
+ goalBatchRound: BatchRoundFrame,
+ goalBatchWaves: BatchWavesGroup,
goalExperiment: GraphNodeView,
goalExperimentGroup: ExperimentGroup,
goalGhost: GhostNodeView,
goalNode: GraphNodeView,
};
+/** Frames and groups a click passes through: their own buttons and cards act. */
+const PASSIVE_NODE_TYPES = new Set([
+ 'goalBatchExperimentProbe',
+ 'goalBatchRound',
+ 'goalBatchWaves',
+ 'goalExperimentGroup',
+ 'goalGhost',
+]);
+
+const GATE_CHIP: Record<BatchGateState, StateChip & { key: string }> = {
+ checking: { ...CELL_VISUAL.running, key: 'checking', text: '' },
+ human: { ...CELL_VISUAL.human, key: 'human', text: '' },
+ locked: { ...CELL_VISUAL.backlog, key: 'locked', text: '' },
+ passed: { ...CELL_VISUAL.done, key: 'passed', text: '' },
+ rejected: { ...CELL_VISUAL.stale, key: 'rejected', text: '' },
+};
+
+/** What a batch member card says about its role: plan vN, or the release gate. */
+type BatchRole = { kind: 'assay' | 'template'; model: BatchModel; round: BatchRound };
+
+const useBatchCopy = () => {
+ const { t } = useTranslation('chat');
+ const checkCopy = useGateCheckCopy();
+ return useMemo(
+ () => ({
+ gate: (round: BatchRound, model: BatchModel): GraphNodeData['presentation'] => {
+ const { key, ...chip } = GATE_CHIP[round.gate];
+ // The latest verdict's checks with their results — a unit hold included —
+ // and before any verdict, the plan.
+ const latest = round.evaluations.at(-1);
+ const judged = latest ? verdictChecks(latest) : [];
+ // What the latest verdict found, at a glance: "3 ✓ · 1 ✗". Before any
+ // verdict, how many checks it will run.
+ const passed = judged.filter((check) => check.passed).length;
+ const failed = judged.length - passed;
+ // Green what passed, red what did not — the tally is the whole subtitle.
+ const tally = latest ? (
+ <span data-gate-tally>
+ {passed > 0 && <span style={{ color: CELL_VISUAL.done.color }}>{`${passed} ✓`}</span>}
+ {passed > 0 && failed > 0 && ' · '}
+ {failed > 0 && <span style={{ color: cssVar.colorError }}>{`${failed} ✗`}</span>}
+ </span>
+ ) : (
+ 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>
+ ),
+ icon: DoorOpen,
+ palette: GATE_COLOR,
+ // Passed / sent back / waiting sits after the title, right-aligned.
+ trailingChip: true,
+ subtitle: tally,
+ title:
+ round.revision > 1
+ ? t('goalBatch.gate.titleRound', { revision: round.revision })
+ : t('goalBatch.gate.title'),
+ };
+ },
+ template: (round: BatchRound, view: GoalNodeView): GraphNodeData['presentation'] => ({
+ chip: null,
+ subtitle: view.node.description?.split('\n')[0] ?? '',
+ title: round.forked
+ ? t('goalBatch.template.forked', { revision: round.revision })
+ : t('goalBatch.template.title', { revision: round.revision }),
+ }),
+ }),
+ [t, checkCopy],
+ );
+};
+
const FIT_VIEW_OPTIONS = { duration: 200, maxZoom: 1, minZoom: 0.05, padding: 0.12 } as const;
/** Ghost placeholders rendered beneath the problem while planning runs. */
@@ -414,7 +525,40 @@ const Canvas = memo<
const edgeLabel = useEdgeLabel();
const isDarkMode = useIsDark();
- const hasExperiments = graph.nodes.some((item) => item.node.kind === 'experiment');
+ const hasContainers = graph.nodes.some((item) => isContainerKind(item.node.kind));
+ const batchCopy = useBatchCopy();
+ // Every batch gets its read model (the folded card summarizes it); only an
+ // open one lays its trials, gate and waves out on the map.
+ const batches = useMemo(() => {
+ const result = new Map<string, { layout?: BatchLayout; model: BatchModel }>();
+ for (const item of graph.nodes) {
+ if (item.node.kind !== 'batch') continue;
+ const model = buildBatchModel(graph, item.node.id);
+ const layout = collapsed.has(item.node.id) ? undefined : layoutBatch(graph, model);
+ result.set(item.node.id, { layout, model });
+ }
+ return result;
+ }, [graph, collapsed]);
+ const batchRoles = useMemo(() => {
+ const result = new Map<string, BatchRole>();
+ for (const { layout, model } of batches.values()) {
+ if (!layout) continue;
+ for (const round of model.rounds) {
+ if (round.templateId) result.set(round.templateId, { kind: 'template', model, round });
+ if (round.assayId) result.set(round.assayId, { kind: 'assay', model, round });
+ }
+ }
+ return result;
+ }, [batches]);
+ const containerLayouts = useMemo(
+ () =>
+ new Map(
+ [...batches].flatMap(([id, { layout }]) =>
+ layout ? [[id, layout] as [string, BatchLayout]] : [],
+ ),
+ ),
+ [batches],
+ );
const map = useMemo(
() =>
explorationMap(
@@ -422,10 +566,11 @@ const Canvas = memo<
graph.edges,
collapsed,
hiddenKinds,
+ containerLayouts,
),
- [graph, collapsed, hiddenKinds],
+ [graph, collapsed, hiddenKinds, containerLayouts],
);
- const baseNodes = hasExperiments
+ const baseNodes = hasContainers
? map.nodes
: graph.nodes
.map((item) => item.node)
@@ -446,7 +591,7 @@ const Canvas = memo<
const handleNodesChange = useCallback((changes: NodeChange[]) => {
setMeasuredSizes((previous) => mergeMeasuredSizes(previous, changes));
}, []);
- const positions = hasExperiments
+ const positions = hasContainers
? map.boxes
: layoutGraph(
baseNodes.filter((node) => visibleIds.has(node.id)),
@@ -482,8 +627,8 @@ const Canvas = memo<
...boxes.map((box) => box.y + box.height),
...ghosts.map((ghost) => ghost.y + GHOST_HEIGHT),
);
- return Math.min(hasExperiments ? 760 : 560, Math.max(216, bottom - top + 72));
- }, [positions, ghosts, hasExperiments]);
+ return Math.min(hasContainers ? 760 : 560, Math.max(216, bottom - top + 72));
+ }, [positions, ghosts, hasContainers]);
const ghostFlowNodes: FlowNode[] = useMemo(
() =>
@@ -505,32 +650,87 @@ const Canvas = memo<
if (!mainline) return result;
const shape = { nodes: graph.nodes.map((view) => view.node), edges: graph.edges };
for (const node of baseNodes) {
- const members = node.kind === 'experiment' ? experimentMembers(shape, node.id, false) : [];
+ const members = isContainerKind(node.kind) ? experimentMembers(shape, node.id, false) : [];
result.set(node.id, nodeEmphasis(mainline, node, members));
}
return result;
}, [mainline, graph, baseNodes]);
+ // An open batch draws no frame: its pieces sit on the map at the batch's
+ // own slot, under whatever holds the batch.
+ const openBatchIds = useMemo(
+ () => new Set([...batches].flatMap(([id, { layout }]) => (layout ? [id] : []))),
+ [batches],
+ );
+ const placeInMap = useCallback(
+ (id: string, box: LayoutBox | undefined, owner = map.parents.get(id)) => {
+ const x = box?.x ?? 0;
+ const y = box?.y ?? 0;
+ if (owner && openBatchIds.has(owner)) {
+ const slot = positions[owner];
+ return {
+ parentId: hasContainers ? map.parents.get(owner) : undefined,
+ position: { x: x + (slot?.x ?? 0), y: y + (slot?.y ?? 0) },
+ };
+ }
+ return { parentId: hasContainers ? owner : undefined, position: { x, y } };
+ },
+ [map.parents, openBatchIds, positions, hasContainers],
+ );
+
const flowNodes: FlowNode[] = useMemo(
() =>
baseNodes
- .filter((node) => visibleIds.has(node.id))
+ .filter((node) => visibleIds.has(node.id) && !openBatchIds.has(node.id))
.map((node) => {
const item = graph.byId[node.id];
const box = positions[item.node.id];
- const isGate = item.node.kind === 'decision' && item.node.status === 'waiting';
+ const batchRole = batchRoles.get(item.node.id);
+ const inBatch =
+ !!map.parents.get(item.node.id) && batches.has(map.parents.get(item.node.id)!);
+ const waiting = item.node.kind === 'decision' && item.node.status === 'waiting';
+ // Inside a batch a decision is a plain card: the hand glyph and a blue
+ // chip say a person is needed, without the orange gate frame.
+ const isGate = waiting && !inBatch;
const emphasis = emphasisById.get(item.node.id);
const highlighted = highlightedIds?.has(item.node.id) ?? false;
+ const rolloutState = graph.goal.config?.rolloutState;
const data: GraphNodeData = {
+ containerStatus:
+ item.node.kind === 'batch' && rolloutState?.batchNodeId === item.node.id
+ ? batchContainerStatus(rolloutState.phase)
+ : undefined,
// Not started and still blocked — it is context, not the story.
// Once the report marked a mainline, everything off it is context too.
- dim: isNodeDimmed({
- blocked: item.node.status === 'proposed' && item.blockers.length > 0,
- emphasis,
- highlighted,
- }),
+ // Inside a batch the gate's own chip says it is locked; a settled
+ // side decision steps back instead.
+ dim: inBatch
+ ? !batchRole && item.node.status === 'resolved'
+ : isNodeDimmed({
+ blocked: item.node.status === 'proposed' && item.blockers.length > 0,
+ emphasis,
+ highlighted,
+ }),
highlighted,
isGate,
+ presentation:
+ batchRole?.kind === 'template'
+ ? batchCopy.template(batchRole.round, item)
+ : batchRole?.kind === 'assay'
+ ? batchCopy.gate(batchRole.round, batchRole.model)
+ : inBatch && item.node.kind === 'decision'
+ ? {
+ icon: HandIcon,
+ ...(waiting
+ ? {
+ chip: {
+ ...TASK_STATUS_VISUALS.paused,
+ text: t('goalProcess.tag.needsDecision'),
+ },
+ }
+ : {}),
+ }
+ : undefined,
mainline: emphasis === 'mainline',
memberCount: experimentMembers(
{ nodes: graph.nodes.map((view) => view.node), edges: graph.edges },
@@ -544,13 +744,14 @@ const Canvas = memo<
subtitle: subtitleOf(item),
view: item,
};
- const expanded = item.node.kind === 'experiment' && !collapsed.has(item.node.id);
+ const expanded = isContainerKind(item.node.kind) && !collapsed.has(item.node.id);
const type = expanded
? 'goalExperimentGroup'
- : graphNodeKind(graph, item) === 'experiment'
+ : isContainerKind(graphNodeKind(graph, item))
? 'goalExperiment'
: 'goalNode';
const measured = measuredSizes[item.node.id];
+ const slot = placeInMap(item.node.id, box);
return {
data: expanded
? ({
@@ -562,9 +763,9 @@ const Canvas = memo<
: data,
draggable: false,
id: item.node.id,
- position: { x: box?.x ?? 0, y: box?.y ?? 0 },
+ position: slot.position,
type,
- parentId: hasExperiments ? map.parents.get(item.node.id) : undefined,
+ parentId: slot.parentId,
...(expanded ? { style: { width: box.width, height: box.height } } : {}),
ariaLabel: graphNodeLabel(
t(`goalProcess.kind.${graphNodeKind(graph, item)}`),
@@ -572,12 +773,7 @@ const Canvas = memo<
item.seq,
),
width: box?.width ?? NODE_WIDTH[item.node.kind],
- // A relayout hands React Flow a new node object, which it treats as
- // unmeasured: it pins the card to `initialHeight` (clipping a tall
- // title back to the estimate) and drops the handle positions edges
- // are drawn from. Handing the last measurement back keeps both, so
- // only a card that has never rendered gets the estimate.
- ...(type === 'goalNode' && measured ? { measured } : { initialHeight: box?.height }),
+ ...flowNodeSize(type, measured, box?.height),
} satisfies FlowNode;
}),
[
@@ -593,13 +789,82 @@ const Canvas = memo<
onInspect,
onEnter,
onSelect,
- hasExperiments,
map.parents,
measuredSizes,
emphasisById,
+ batches,
+ batchRoles,
+ batchCopy,
+ openBatchIds,
+ placeInMap,
],
);
+ // The synthetic groups an open batch is drawn with: its trials, each
+ // 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(batchId),
+ onSelect,
+ probes: first.probes,
+ started: first.probes.some((probe) => probe.state !== 'backlog'),
+ views: graph.byId,
+ }
+ : ({
+ onEnter: () => onEnter(batchId),
+ 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;
+ });
+ }),
+ [batches, visibleIds, graph.byId, onEnter, onSelect, placeInMap],
+ );
+
const flowEdges: FlowEdge[] = useMemo(() => {
const marker = {
color: edgeMarkerColor(undefined, isDarkMode),
@@ -615,10 +880,13 @@ const Canvas = memo<
const markerOf = (tone: EdgeTone) =>
tone === 'mainline' ? mainlineMarker : tone === 'detour' ? detourMarker : marker;
const lanes = new Map<string, number>();
- const direct = (hasExperiments ? map.edges : graph.edges)
+ const direct = (hasContainers ? map.edges : graph.edges)
.filter((edge) => visibleIds.has(edge.sourceNodeId) && visibleIds.has(edge.targetNodeId))
.map((edge) => {
- const [source, target] = edgeDirection(edge);
+ // An open batch has no card of its own: a link to it lands on its first piece.
+ const [rawSource, rawTarget] = edgeDirection(edge);
+ const source = batches.get(rawSource)?.layout?.entryId ?? rawSource;
+ const target = batches.get(rawTarget)?.layout?.entryId ?? rawTarget;
const pair = `${source}/${target}`;
const lane = lanes.get(pair) ?? 0;
lanes.set(pair, lane + 1);
@@ -642,7 +910,7 @@ const Canvas = memo<
markerEnd: markerOf(tone),
source,
target,
- type: hasExperiments ? 'exploration' : 'default',
+ type: hasContainers ? 'exploration' : 'default',
data: { lane },
} satisfies FlowEdge;
});
@@ -668,14 +936,39 @@ const Canvas = memo<
type: 'default',
} satisfies FlowEdge;
});
- return [...direct, ...bridged];
+ // An open batch's own chain, drawn as ordinary map links.
+ const placed = new Set(visibleIds);
+ for (const { layout } of batches.values())
+ for (const group of layout?.groups ?? []) placed.add(group.id);
+ const chained = [...batches.values()].flatMap(({ layout }) =>
+ (layout?.edges ?? [])
+ .filter((edge) => placed.has(edge.source) && placed.has(edge.target))
+ .map(
+ (edge) =>
+ ({
+ data: { lane: 0 },
+ id: edge.id,
+ ...(edge.label
+ ? { label: t('goalBatch.round.reviseEdge'), labelShowBg: true }
+ : {}),
+ markerEnd: marker,
+ source: edge.source,
+ sourceHandle: edge.sourceHandle,
+ target: edge.target,
+ targetHandle: edge.targetHandle,
+ type: 'exploration',
+ }) satisfies FlowEdge,
+ ),
+ );
+ return [...direct, ...bridged, ...chained];
}, [
+ batches,
graph,
visibleIds,
bridges,
selectedId,
edgeLabel,
- hasExperiments,
+ hasContainers,
map.edges,
t,
mainline,
@@ -698,7 +991,10 @@ const Canvas = memo<
[ghosts],
);
- const allNodes = useMemo(() => [...flowNodes, ...ghostFlowNodes], [flowNodes, ghostFlowNodes]);
+ const allNodes = useMemo(
+ () => [...flowNodes, ...batchFlowNodes, ...ghostFlowNodes],
+ [flowNodes, batchFlowNodes, ghostFlowNodes],
+ );
const allEdges = useMemo(() => [...flowEdges, ...ghostFlowEdges], [flowEdges, ghostFlowEdges]);
// The inline map is a framed overview, so keep it fitted to the space left by
@@ -775,7 +1071,7 @@ const Canvas = memo<
zoomOnScroll={false}
onNodesChange={handleNodesChange}
onNodeClick={(_, node) => {
- if (node.type !== 'goalGhost' && node.type !== 'goalExperimentGroup') onSelect(node.id);
+ if (!PASSIVE_NODE_TYPES.has(node.type ?? '')) onSelect(node.id);
}}
>
{navigation && (
@@ -798,7 +1094,7 @@ const Canvas = memo<
position={'bottom-left'}
style={{ background: cssVar.colorBgContainer }}
nodeColor={(node) =>
- node.type === 'goalExperimentGroup'
+ PASSIVE_NODE_TYPES.has(node.type ?? '')
? cssVar.colorFillTertiary
: cssVar.colorTextSecondary
}
@@ -828,7 +1124,10 @@ const Graph = memo<GraphProps>(({ extra, fullscreen = false, onFullscreenChange,
const [preferredView, setView] = useState<GraphViewMode>('stage');
const stageIsWholeMap = isStageWholeMap(props.graph);
const view: GraphViewMode = stageIsWholeMap ? 'all' : preferredView;
- const experiments = props.graph.nodes.filter((item) => item.node.kind === 'experiment');
+ const containers = props.graph.nodes.filter((item) => isContainerKind(item.node.kind));
+ const onlyBatches = containers.every((item) => item.node.kind === 'batch');
+ // A batch never folds, so expand/collapse all only means something with experiments.
+ const hasFoldable = !onlyBatches;
const [hiddenKinds, setHiddenKinds] = useState<ReadonlySet<GoalGraphNodeKind>>(() => new Set());
const showPortal = useChatStore(chatPortalSelectors.showPortal);
const currentViewType = useChatStore(chatPortalSelectors.currentViewType);
@@ -847,24 +1146,28 @@ const Graph = memo<GraphProps>(({ extra, fullscreen = false, onFullscreenChange,
}, []);
const selectNode = (nodeId: string) => {
- if (props.graph.byId[nodeId]?.node.kind === 'experiment') {
+ if (isContainerKind(props.graph.byId[nodeId]?.node.kind ?? ('task' as const))) {
navigation.toggle(nodeId);
} else props.onSelect(nodeId);
};
- const overview = experiments.length > 0 && (
+ const overview = containers.length > 0 && (
<Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>
<Text fontSize={12} type={'secondary'}>
- {t('goalExperiment.overviewCount', {
- count: experiments.length,
+ {t(onlyBatches ? 'goalBatch.overviewCount' : 'goalExperiment.overviewCount', {
+ count: containers.length,
nodes: props.graph.nodes.length,
})}
</Text>
- <Button size={'small'} onClick={() => navigation.expandAll(true)}>
- {t(scopeId ? 'goalExperiment.expandScope' : 'goalExperiment.expandAll')}
- </Button>
- <Button size={'small'} onClick={() => navigation.expandAll(false)}>
- {t(scopeId ? 'goalExperiment.collapseScope' : 'goalExperiment.collapseAll')}
- </Button>
+ {hasFoldable && (
+ <>
+ <Button size={'small'} onClick={() => navigation.expandAll(true)}>
+ {t(scopeId ? 'goalExperiment.expandScope' : 'goalExperiment.expandAll')}
+ </Button>
+ <Button size={'small'} onClick={() => navigation.expandAll(false)}>
+ {t(scopeId ? 'goalExperiment.collapseScope' : 'goalExperiment.collapseAll')}
+ </Button>
+ </>
+ )}
</Flexbox>
);
const breadcrumbs = scopeId && (
@@ -911,7 +1214,7 @@ const Graph = memo<GraphProps>(({ extra, fullscreen = false, onFullscreenChange,
<Text fontSize={16} weight={600}>
{t('goalProcess.graph.title')}
</Text>
- {experiments.length === 0 && !stageIsWholeMap && (
+ {containers.length === 0 && !stageIsWholeMap && (
<Segmented
size={'small'}
value={view}
@@ -948,9 +1251,10 @@ const Graph = memo<GraphProps>(({ extra, fullscreen = false, onFullscreenChange,
[
'problem',
'task',
- ...(props.graph.nodes.some((view) => view.node.kind === 'experiment')
+ ...(containers.some((view) => view.node.kind === 'experiment')
? ['experiment' as const]
: []),
+ ...(containers.some((view) => view.node.kind === 'batch') ? ['batch' as const] : []),
'finding',
'decision',
] as const
diff --git a/src/features/AgentGoals/ProcessControl/Graph/layout.ts b/src/features/AgentGoals/ProcessControl/Graph/layout.ts
index 2cd48612a3b..9a5ea6eeaa2 100644
--- a/src/features/AgentGoals/ProcessControl/Graph/layout.ts
+++ b/src/features/AgentGoals/ProcessControl/Graph/layout.ts
@@ -14,6 +14,7 @@ type LayoutNode = Omit<GoalGraphNode, 'kind'> & { kind: GoalGraphNodeKind };
*/
export const NODE_WIDTH = {
+ batch: 260,
decision: 250,
experiment: 260,
finding: 240,
@@ -21,6 +22,7 @@ export const NODE_WIDTH = {
task: 260,
} as const;
export const NODE_HEIGHT = {
+ batch: 112,
decision: 76,
experiment: 112,
finding: 76,
diff --git a/src/features/AgentGoals/ProcessControl/Graph/measuredSizes.test.ts b/src/features/AgentGoals/ProcessControl/Graph/measuredSizes.test.ts
index 152767a5eeb..5c34a2a2694 100644
--- a/src/features/AgentGoals/ProcessControl/Graph/measuredSizes.test.ts
+++ b/src/features/AgentGoals/ProcessControl/Graph/measuredSizes.test.ts
@@ -1,7 +1,7 @@
import type { NodeChange } from '@xyflow/react';
import { describe, expect, it } from 'vitest';
-import { mergeMeasuredSizes } from './measuredSizes';
+import { flowNodeSize, mergeMeasuredSizes } from './measuredSizes';
const resize = (id: string, width: number, height: number): NodeChange => ({
dimensions: { height, width },
@@ -44,3 +44,17 @@ describe('mergeMeasuredSizes', () => {
).toBe(previous);
});
});
+
+describe('flowNodeSize', () => {
+ const measured = { height: 64, width: 260 };
+
+ it('hands a folded container card its measurement back, so its edges keep their handles', () => {
+ expect(flowNodeSize('goalExperiment', measured, 112)).toEqual({ measured });
+ expect(flowNodeSize('goalNode', measured, 76)).toEqual({ measured });
+ });
+
+ it('estimates a card that never rendered and a frame the layout sizes', () => {
+ expect(flowNodeSize('goalNode', undefined, 76)).toEqual({ initialHeight: 76 });
+ expect(flowNodeSize('goalBatchFrame', measured, 600)).toEqual({ initialHeight: 600 });
+ });
+});
diff --git a/src/features/AgentGoals/ProcessControl/Graph/measuredSizes.ts b/src/features/AgentGoals/ProcessControl/Graph/measuredSizes.ts
index 28b2f2f5214..2652bc3fce4 100644
--- a/src/features/AgentGoals/ProcessControl/Graph/measuredSizes.ts
+++ b/src/features/AgentGoals/ProcessControl/Graph/measuredSizes.ts
@@ -35,3 +35,20 @@ export const mergeMeasuredSizes = (
}
return next ?? previous;
};
+
+/** Card node types: their height follows content, so a relayout hands the measurement back. */
+const CARD_NODE_TYPES = new Set(['goalNode', 'goalExperiment']);
+
+/**
+ * Size fields for one flow node on a relayout. A relayout hands React Flow a
+ * new node object, which it treats as unmeasured: it pins the card to
+ * `initialHeight` and drops the handle positions its edges are drawn from.
+ * Handing a card its last measurement back keeps both, so only a card that has
+ * never rendered — or a framed container sized by the layout — gets the estimate.
+ */
+export const flowNodeSize = (
+ type: string,
+ measured: MeasuredSize | undefined,
+ estimatedHeight: number | undefined,
+): { initialHeight?: number; measured?: MeasuredSize } =>
+ CARD_NODE_TYPES.has(type) && measured ? { measured } : { initialHeight: estimatedHeight };
diff --git a/src/features/AgentGoals/ProcessControl/Graph/useExplorationNavigation.test.ts b/src/features/AgentGoals/ProcessControl/Graph/useExplorationNavigation.test.ts
index 699a155e3c5..92007ecfb63 100644
--- a/src/features/AgentGoals/ProcessControl/Graph/useExplorationNavigation.test.ts
+++ b/src/features/AgentGoals/ProcessControl/Graph/useExplorationNavigation.test.ts
@@ -21,6 +21,22 @@ const edges = [
const graph = { nodes, edges };
describe('experiment navigation', () => {
+ it('never folds a batch — not on a click, not on collapse all', () => {
+ const batchNodes = [
+ { id: 'batch', kind: 'batch' },
+ { id: 'exp', kind: 'experiment' },
+ ] as GoalGraphNode[];
+ const { result } = renderHook(() =>
+ useExplorationNavigation('g', { edges: [], nodes: batchNodes }),
+ );
+ expect([...result.current.collapsed]).toEqual(['exp']);
+ act(() => result.current.toggle('batch'));
+ expect([...result.current.collapsed]).toEqual(['exp']);
+ act(() => result.current.expandAll(true));
+ expect([...result.current.collapsed]).toEqual([]);
+ act(() => result.current.expandAll(false));
+ expect([...result.current.collapsed]).toEqual(['exp']);
+ });
it('starts collapsed even after async data arrives, and new experiments do not reset manual expansion', () => {
const { result, rerender } = renderHook(
(nodes) => useExplorationNavigation('g', { nodes, edges }),
diff --git a/src/features/AgentGoals/ProcessControl/Graph/useExplorationNavigation.ts b/src/features/AgentGoals/ProcessControl/Graph/useExplorationNavigation.ts
index efc6da097e1..ab3ee5fa2f5 100644
--- a/src/features/AgentGoals/ProcessControl/Graph/useExplorationNavigation.ts
+++ b/src/features/AgentGoals/ProcessControl/Graph/useExplorationNavigation.ts
@@ -2,12 +2,22 @@ import type { GoalGraphSnapshot } from '@lobechat/types';
import { experimentMembers } from '@lobechat/utils/goalGraph';
import { useMemo, useState } from 'react';
+import { isContainerKind } from '../../Experiments/model';
+
type Graph = Pick<GoalGraphSnapshot, 'nodes' | 'edges'>;
-/** Expansion is presentation state; entering a group explicitly changes the viewing scope. */
+/**
+ * Expansion is presentation state; entering a group explicitly changes the viewing scope.
+ *
+ * An experiment folds — it is one candidate among several. A batch never does:
+ * its trials, gate and waves are the whole point of the view, and it has no
+ * frame to fold into. `toggled` records the experiments a person opened.
+ */
+const foldable = (node: Graph['nodes'][number]) => node.kind !== 'batch';
+
export const useExplorationNavigation = (goalId: string, graph: Graph) => {
- const [state, setState] = useState({ goalId, expanded: new Set<string>(), path: [] as string[] });
- if (state.goalId !== goalId) setState({ goalId, expanded: new Set(), path: [] });
+ const [state, setState] = useState({ goalId, path: [] as string[], toggled: new Set<string>() });
+ if (state.goalId !== goalId) setState({ goalId, path: [], toggled: new Set() });
const path = state.path.filter((id) => graph.nodes.some((n) => n.id === id));
const scopeId = path.at(-1);
@@ -17,12 +27,12 @@ export const useExplorationNavigation = (goalId: string, graph: Graph) => {
const edges = graph.edges.filter(
(edge) => ids.has(edge.sourceNodeId) && ids.has(edge.targetNodeId),
);
- const experiments = nodes.filter((node) => node.kind === 'experiment');
+ const containers = nodes.filter((node) => isContainerKind(node.kind));
// The canvas refits whenever `collapsed` changes identity, so it must only
// change when its contents do — a fresh Set per render refit the map on every
// node click and every graph poll.
- const collapsedKey = experiments
- .filter((n) => !state.expanded.has(n.id))
+ const collapsedKey = containers
+ .filter((n) => foldable(n) && !state.toggled.has(n.id))
.map((n) => n.id)
.join('\n');
const collapsed = useMemo(
@@ -37,26 +47,28 @@ export const useExplorationNavigation = (goalId: string, graph: Graph) => {
path,
scopeId,
enter: (id: string) => {
- if (!experiments.some((node) => node.id === id)) return;
+ if (!containers.some((node) => node.id === id)) return;
setState((previous) => ({ ...previous, path: [...path, id] }));
},
backTo: (depth: number) =>
setState((previous) => ({ ...previous, path: path.slice(0, depth) })),
toggle: (id: string) =>
setState((previous) => {
- const expanded = new Set(previous.expanded);
- if (expanded.has(id)) expanded.delete(id);
- else expanded.add(id);
- return { ...previous, expanded };
+ if (!containers.some((node) => node.id === id && foldable(node))) return previous;
+ const toggled = new Set(previous.toggled);
+ if (toggled.has(id)) toggled.delete(id);
+ else toggled.add(id);
+ return { ...previous, toggled };
}),
expandAll: (expand: boolean) =>
setState((previous) => {
- const expanded = new Set(previous.expanded);
- for (const node of experiments) {
- if (expand) expanded.add(node.id);
- else expanded.delete(node.id);
+ const toggled = new Set(previous.toggled);
+ for (const node of containers) {
+ if (!foldable(node)) continue;
+ if (expand) toggled.add(node.id);
+ else toggled.delete(node.id);
}
- return { ...previous, expanded };
+ return { ...previous, toggled };
}),
};
};
diff --git a/src/features/AgentGoals/ProcessControl/coordinatorCopy.test.ts b/src/features/AgentGoals/ProcessControl/coordinatorCopy.test.ts
index c1b295159b5..1979e152924 100644
--- a/src/features/AgentGoals/ProcessControl/coordinatorCopy.test.ts
+++ b/src/features/AgentGoals/ProcessControl/coordinatorCopy.test.ts
@@ -6,6 +6,7 @@ import {
coordinatorGateReason,
coordinatorReasonCopy,
gateOptionLabelKey,
+ localizedCoordinatorReason,
} from './coordinatorCopy';
const decision = (ids: string[]) => ({ options: ids.map((id) => ({ id, label: id })) }) as any;
@@ -143,3 +144,23 @@ describe('machine gate copy', () => {
});
});
});
+
+describe('localizedCoordinatorReason', () => {
+ const t = (key: string, params?: Record<string, unknown>) =>
+ `${key}${params?.count === undefined ? '' : `(${params.count})`}`;
+
+ it('localizes every blocker of a compound batch reason', () => {
+ expect(
+ localizedCoordinatorReason(
+ '1 unit(s) did not succeed; a human decision is still open in this batch',
+ t,
+ ),
+ ).toBe('goalProcess.gate.reason.batchBroken(1); goalProcess.gate.reason.batchOpenDecision');
+ });
+
+ it('keeps a reason it does not recognize as stored', () => {
+ expect(localizedCoordinatorReason('Something else went wrong', t)).toBe(
+ 'Something else went wrong',
+ );
+ });
+});
diff --git a/src/features/AgentGoals/ProcessControl/coordinatorCopy.ts b/src/features/AgentGoals/ProcessControl/coordinatorCopy.ts
index 774fd7545f7..a10addd2f82 100644
--- a/src/features/AgentGoals/ProcessControl/coordinatorCopy.ts
+++ b/src/features/AgentGoals/ProcessControl/coordinatorCopy.ts
@@ -1,15 +1,15 @@
import {
GOAL_ACCEPTANCE_TASK_TITLE,
+ GOAL_BATCH_ASSAY_TITLE,
+ GOAL_BATCH_BREAK_OPTION,
+ GOAL_BATCH_TEMPLATE_TITLE,
+ GOAL_BATCH_TITLE,
GOAL_CLARIFICATION_OPTION,
GOAL_MACHINE_GATE_TITLE,
GOAL_MANAGER_QUESTION_TITLE,
} from '@lobechat/const/goal';
import type { GoalDecisionOption, GoalGraphDecision } from '@lobechat/types';
-import {
- coordinatorGateReason,
- coordinatorReasonCopy,
- type LocalizedCopyRef,
-} from '@lobechat/utils/goalCopy';
+import { coordinatorReasonCopies } from '@lobechat/utils/goalCopy';
import type { GoalNodeView } from './goalGraphViewModel';
@@ -22,7 +22,12 @@ import type { GoalNodeView } from './goalGraphViewModel';
*/
export type CoordinatorGateKind =
- 'agentQuestion' | 'clarifyGoal' | 'fixSetup' | 'goalAcceptance' | 'recoverTask';
+ | 'agentQuestion'
+ | 'batchPatternBreak'
+ | 'clarifyGoal'
+ | 'fixSetup'
+ | 'goalAcceptance'
+ | 'recoverTask';
const idsOf = (decision?: GoalGraphDecision | null): Set<string> =>
new Set((decision?.options ?? []).map((option) => option.id));
@@ -40,6 +45,9 @@ export const coordinatorGateKind = (
return nodeTitle === GOAL_MACHINE_GATE_TITLE ? 'fixSetup' : 'recoverTask';
if (ids.has(GOAL_CLARIFICATION_OPTION.assume) && ids.has(GOAL_CLARIFICATION_OPTION.answer))
return 'clarifyGoal';
+ // A batch's pattern break: revise the recipe, or fork it as a new class.
+ if (ids.has(GOAL_BATCH_BREAK_OPTION.revise) && ids.has(GOAL_BATCH_BREAK_OPTION.newClass))
+ return 'batchPatternBreak';
return undefined;
};
@@ -70,6 +78,12 @@ export const gateOptionLabelKey = (
? 'goalProcess.gate.option.fixedRetry'
: 'goalProcess.gate.option.retry';
}
+ case GOAL_BATCH_BREAK_OPTION.revise: {
+ return 'goalProcess.gate.option.reviseBatch';
+ }
+ case GOAL_BATCH_BREAK_OPTION.newClass: {
+ return 'goalProcess.gate.option.newClassBatch';
+ }
default: {
return undefined;
}
@@ -87,6 +101,12 @@ export const isGoalAcceptanceTask = (view: GoalNodeView): boolean =>
export const coordinatorNodeTitleKey = (view: GoalNodeView): string | undefined => {
const { node } = view;
if (isGoalAcceptanceTask(view)) return 'goalProcess.node.terminalAcceptance';
+ // A batch's own nodes carry fixed English titles, like the gates below.
+ if (node.kind === 'batch' && node.title === GOAL_BATCH_TITLE) return 'goalBatch.title';
+ if (node.kind === 'finding' && node.title === GOAL_BATCH_TEMPLATE_TITLE)
+ return 'goalBatch.templatePlain';
+ if (node.kind === 'decision' && node.title === GOAL_BATCH_ASSAY_TITLE)
+ return 'goalBatch.gate.title';
if (node.kind === 'decision' && node.title === GOAL_MANAGER_QUESTION_TITLE)
return gateTitleKey('agentQuestion');
if (node.kind === 'decision') {
@@ -96,4 +116,22 @@ export const coordinatorNodeTitleKey = (view: GoalNodeView): string | undefined
return undefined;
};
-export { coordinatorGateReason, coordinatorReasonCopy, type LocalizedCopyRef };
+/**
+ * A stored coordinator reason in the reader's language: every blocker of a
+ * compound batch reason localized and rejoined, or the stored text when it is
+ * not (wholly) coordinator-authored.
+ */
+export const localizedCoordinatorReason = <R extends string | null | undefined>(
+ reason: R,
+ t: (key: string, params?: Record<string, unknown>) => string,
+): string | R => {
+ const copies = coordinatorReasonCopies(reason);
+ return copies ? copies.map((copy) => t(copy.key, copy.params)).join('; ') : reason;
+};
+
+export {
+ coordinatorGateReason,
+ coordinatorReasonCopies,
+ coordinatorReasonCopy,
+ type LocalizedCopyRef,
+} from '@lobechat/utils/goalCopy';
diff --git a/src/features/AgentGoals/ProcessControl/index.tsx b/src/features/AgentGoals/ProcessControl/index.tsx
index 0fee5e6e83b..8273cf04222 100644
--- a/src/features/AgentGoals/ProcessControl/index.tsx
+++ b/src/features/AgentGoals/ProcessControl/index.tsx
@@ -88,7 +88,9 @@ const ProcessControl = memo<ProcessControlProps>(
// advances entirely on its own — the only legitimate human control over its
// pace is pause/resume.
const canAct = canEdit && !isGoalClosed(graph);
- const hasExperiments = graph.nodes.some((view) => view.node.kind === 'experiment');
+ const hasContainers = graph.nodes.some(
+ (view) => view.node.kind === 'experiment' || view.node.kind === 'batch',
+ );
const map = (
<Graph
@@ -104,7 +106,7 @@ const ProcessControl = memo<ProcessControlProps>(
const process = (
<Flexbox gap={20}>
- {hasExperiments && map}
+ {hasContainers && map}
<Flexbox gap={12}>
<Frontier
actions={actions}
@@ -115,7 +117,7 @@ const ProcessControl = memo<ProcessControlProps>(
/>
</Flexbox>
- {!hasExperiments && map}
+ {!hasContainers && map}
<Accordion
defaultValue={['deliverables', 'findings', 'activity']}
diff --git a/src/features/AgentGoals/ProcessControl/shared.tsx b/src/features/AgentGoals/ProcessControl/shared.tsx
index 1e842b623ac..45b14229868 100644
--- a/src/features/AgentGoals/ProcessControl/shared.tsx
+++ b/src/features/AgentGoals/ProcessControl/shared.tsx
@@ -2,6 +2,7 @@ import { Icon } from '@lobehub/ui';
import { Text } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
import {
+ Boxes,
CircleHelp,
FlaskConical,
GitBranch,
@@ -24,6 +25,9 @@ export const KIND_COLOR: Record<GoalGraphNodeKind, { line: string; soft: string
// primary-strength band sits at x9–x10, and x6/x7 resolve to near-pastel
// tints (light-mode blue-7 is #93c8ff). x3/x10 gives the glyph a visible
// tinted tile with a saturated line in both themes.
+ // A batch is one repeated mould delivered as a class; geekblue keeps it
+ // distinct from the single `task` blue while sitting beside the experiment cyan.
+ batch: { line: cssVar.geekblue10, soft: cssVar.geekblue3 },
decision: { line: cssVar.orange10, soft: cssVar.orange3 },
experiment: { line: cssVar.cyan10, soft: cssVar.cyan3 },
finding: { line: cssVar.green10, soft: cssVar.green3 },
@@ -31,7 +35,15 @@ export const KIND_COLOR: Record<GoalGraphNodeKind, { line: string; soft: string
task: { line: cssVar.blue10, soft: cssVar.blue3 },
};
+/**
+ * A batch's release gate is where a person steps in when the batch breaks, so
+ * it wears the cyan the product uses for "a person decides here" — not the
+ * decision orange, and not a red that reads as an error.
+ */
+export const GATE_COLOR = { line: cssVar.cyan10, soft: cssVar.cyan3 };
+
export const KIND_ICON: Record<GoalGraphNodeKind, LucideIcon> = {
+ batch: Boxes,
decision: GitBranch,
experiment: FlaskConical,
finding: Lightbulb,
diff --git a/src/features/Portal/GoalNode/Body.tsx b/src/features/Portal/GoalNode/Body.tsx
index 93ab3487934..1b4ff2a9b33 100644
--- a/src/features/Portal/GoalNode/Body.tsx
+++ b/src/features/Portal/GoalNode/Body.tsx
@@ -8,16 +8,23 @@ import { useTranslation } from 'react-i18next';
import { ExperimentDetail } from '@/features/AgentGoals/Experiments/Detail';
import { isExperiment } from '@/features/AgentGoals/Experiments/model';
+import GateDetail from '@/features/AgentGoals/ProcessControl/BatchGate/GateDetail';
+import PlanDetail from '@/features/AgentGoals/ProcessControl/BatchPlan/PlanDetail';
import {
coordinatorGateReason,
- coordinatorReasonCopy,
+ coordinatorReasonCopies,
viewGateKind,
} from '@/features/AgentGoals/ProcessControl/coordinatorCopy';
import {
buildGoalGraphView,
type GoalNodeView,
} from '@/features/AgentGoals/ProcessControl/goalGraphViewModel';
+import {
+ findBatchGate,
+ findBatchPlan,
+} from '@/features/AgentGoals/ProcessControl/Graph/batchModel';
import { KindDot } from '@/features/AgentGoals/ProcessControl/shared';
+import { useFrontierActions } from '@/features/AgentGoals/ProcessControl/useGoalProcessActions';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
import { goalSelectors, useGoalStore } from '@/store/goal';
@@ -138,6 +145,7 @@ const Body = memo(() => {
const view = useChatStore(chatPortalSelectors.goalNodeView);
const openTaskDetail = useChatStore((s) => s.openTaskDetail);
const openGoalNode = useChatStore((s) => s.openGoalNode);
+ const { decide } = useFrontierActions(view?.goalId ?? '');
// Fetched here, not assumed from the goal page: the drill-down also opens
// from the conversation portal, where nothing else holds the snapshot.
const useFetchGoalGraph = useGoalStore((s) => s.useFetchGoalGraph);
@@ -157,26 +165,49 @@ const Body = memo(() => {
</ExperimentDetail>
);
const isFinding = node.kind === 'finding';
+ // A batch's release gate is judged by the coordinator, not asked of a person:
+ // its panel shows the verdicts and their checks instead of a bare decision.
+ const batchGate = node.kind === 'decision' ? findBatchGate(graph, node.id) : undefined;
+ // A batch's plan opens on its versions and what changed between them.
+ const batchPlan = node.kind === 'finding' ? findBatchPlan(graph, node.id) : undefined;
// Coordinator gates localize; arbitrary gates keep their stored copy.
const gateKind = node.kind === 'decision' ? viewGateKind(nodeView) : undefined;
const rawGateReason = gateKind ? coordinatorGateReason(nodeView.decision?.question) : undefined;
- const gateReasonCopy = coordinatorReasonCopy(rawGateReason);
- const gateReasonText = gateReasonCopy
- ? t(gateReasonCopy.key as any, gateReasonCopy.params)
+ const gateReasonCopies = coordinatorReasonCopies(rawGateReason);
+ const gateReasonText = gateReasonCopies
+ ? gateReasonCopies.map((copy) => t(copy.key as any, copy.params)).join('; ')
: rawGateReason;
return (
<Flexbox flex={1} gap={16} padding={16} style={{ minHeight: 0, overflowY: 'auto' }}>
- <Flexbox horizontal align={'center'} gap={8}>
- <Tag size={'small'}>{t(`goalProcess.kind.${node.kind}` as const)}</Tag>
- <Tag size={'small'}>{t(`goalProcess.nodeStatus.${node.status}` as const)}</Tag>
- {nodeView.humanTouches.length > 0 && (
- <Tag size={'small'}>{t('goalProcess.node.humanTouched')}</Tag>
- )}
- </Flexbox>
+ {/* A gate's raw node status stays `proposed` while it releases waves;
+ its verdict below says what state it is really in. */}
+ {!batchGate && !batchPlan && (
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Tag size={'small'}>{t(`goalProcess.kind.${node.kind}` as const)}</Tag>
+ <Tag size={'small'}>{t(`goalProcess.nodeStatus.${node.status}` as const)}</Tag>
+ {nodeView.humanTouches.length > 0 && (
+ <Tag size={'small'}>{t('goalProcess.node.humanTouched')}</Tag>
+ )}
+ </Flexbox>
+ )}
+
+ {batchGate && (
+ <GateDetail
+ decide={decide}
+ graph={graph}
+ model={batchGate.model}
+ round={batchGate.round}
+ onOpenNode={(nodeId) => openGoalNode(view.goalId, nodeId)}
+ />
+ )}
+
+ {batchPlan && <PlanDetail graph={graph} model={batchPlan.model} round={batchPlan.round} />}
{node.description &&
+ !batchGate &&
+ !batchPlan &&
(isFinding ? (
// A finding's description is the run's handoff — real Markdown, so
// render it as such instead of pre-wrapped source text. `flex-shrink: 0`
@@ -200,7 +231,7 @@ const Body = memo(() => {
</Section>
))}
- {node.kind === 'decision' && nodeView.decision && (
+ {node.kind === 'decision' && nodeView.decision && !batchGate && (
<Section title={t('goalProcess.gate.decisionPointLabel')}>
{/* State the problem itself; the resolution options carry the choices. */}
<Text fontSize={13}>{gateReasonText ?? nodeView.decision.question}</Text>
diff --git a/src/features/Portal/GoalNode/Title.tsx b/src/features/Portal/GoalNode/Title.tsx
index 43e443780df..1ed50b63d4d 100644
--- a/src/features/Portal/GoalNode/Title.tsx
+++ b/src/features/Portal/GoalNode/Title.tsx
@@ -1,11 +1,17 @@
-import { Flexbox } from '@lobehub/ui';
+import { Flexbox, Icon } from '@lobehub/ui';
import { Text } from '@lobehub/ui/base-ui';
+import { DoorOpen } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { graphNodeKind } from '@/features/AgentGoals/Experiments/model';
+import { coordinatorNodeTitleKey } from '@/features/AgentGoals/ProcessControl/coordinatorCopy';
import { buildGoalGraphView } from '@/features/AgentGoals/ProcessControl/goalGraphViewModel';
-import { KindIcon } from '@/features/AgentGoals/ProcessControl/shared';
+import {
+ findBatchGate,
+ findBatchPlan,
+} from '@/features/AgentGoals/ProcessControl/Graph/batchModel';
+import { GATE_COLOR, KindIcon } from '@/features/AgentGoals/ProcessControl/shared';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
import { goalSelectors, useGoalStore } from '@/store/goal';
@@ -19,13 +25,32 @@ const Title = memo(() => {
if (!snapshot || !view) return undefined;
const graph = buildGoalGraphView(snapshot);
const nodeView = graph.byId[view.nodeId];
- return nodeView ? { ...nodeView.node, kind: graphNodeKind(graph, nodeView) } : undefined;
- }, [snapshot, view]);
+ if (!nodeView) return undefined;
+ // Coordinator-authored titles are English; a batch gate also names its round.
+ const revision = findBatchGate(graph, nodeView.node.id)?.round.revision;
+ const plan = findBatchPlan(graph, nodeView.node.id)?.round;
+ const titleKey = coordinatorNodeTitleKey(nodeView);
+ const title = plan
+ ? t(plan.forked ? 'goalBatch.template.forked' : 'goalBatch.template.title', {
+ revision: plan.revision,
+ })
+ : revision && revision > 1
+ ? t('goalBatch.gate.titleRound', { revision })
+ : titleKey
+ ? t(titleKey as any)
+ : nodeView.node.title;
+ return { gate: !!revision, kind: graphNodeKind(graph, nodeView), title };
+ }, [snapshot, view, t]);
return (
// Hug the content so the shared `…` sits right after the title.
<Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
- {node && <KindIcon kind={node.kind} />}
+ {node &&
+ (node.gate ? (
+ <Icon color={GATE_COLOR.line} icon={DoorOpen} size={14} />
+ ) : (
+ <KindIcon kind={node.kind} />
+ ))}
<Text className={oneLineEllipsis} style={{ flex: '0 1 auto', fontSize: 14, minWidth: 0 }}>
{node?.title ?? t('goalProcess.node.detailTitle')}
</Text>
diff --git a/src/services/goal.ts b/src/services/goal.ts
index e80c0306f4a..bf0f6125a8d 100644
--- a/src/services/goal.ts
+++ b/src/services/goal.ts
@@ -1,4 +1,4 @@
-import type { GoalStatus } from '@lobechat/const/goal';
+import { GOAL_GRAPH_CAPABILITY, type GoalStatus } from '@lobechat/const/goal';
import type {
GoalCreateConfig,
GoalGraphSnapshot,
@@ -68,7 +68,12 @@ class GoalService {
/** The whole Goal Graph in one read: nodes, edges, decisions, events, work-version links. */
getGraph = async (id: string): Promise<GoalGraphSnapshot> => {
- const { data } = await lambdaClient.goal.graph.query({ id });
+ // This client draws batches; without the declaration the server sends an
+ // older client's shape (see `graphForClient`).
+ const { data } = await lambdaClient.goal.graph.query({
+ capabilities: [GOAL_GRAPH_CAPABILITY.batch],
+ id,
+ });
return data;
};
@@ -130,10 +135,14 @@ class GoalService {
maxTotalCost?: number | null;
}) => lambdaClient.goal.setBudget.mutate(params);
+ /**
+ * A batch is only ever created by decomposition, never hand-authored, so the
+ * add-node surface accepts every kind except `batch`.
+ */
addNode = async (params: {
description?: string;
id: string;
- kind: GoalNodeKind;
+ kind: Exclude<GoalNodeKind, 'batch'>;
priority?: number;
title: string;
}) => lambdaClient.goal.addNode.mutate(params);