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): draft topic goals until started, and let the agent run a batch (#20840)

Arvin Xu58ef4a5543dc
diff --git a/.agents/skills/cli/references/goal.md b/.agents/skills/cli/references/goal.md
index 3b576a267c8..769bb237abc 100644
--- a/.agents/skills/cli/references/goal.md
+++ b/.agents/skills/cli/references/goal.md
@@ -94,6 +94,29 @@ The file is one of:
an earlier task in the same plan. A later round without these links looks
unrelated to the evidence it uses.
+A `tasks` plan may declare a batch with `rollout` when the work applies one
+recipe to many units (migrate N stores, cache N resources, update N callers):
+
+```json
+{
+ "action": "tasks",
+ "reason": "...",
+ "rollout": {
+ "recipe": "<procedure every unit follows>",
+ "units": ["<unit>", { "title": "<unit>", "description": "<its own pointers>" }],
+ "variants": [{ "axis": "...", "values": ["...", "..."] }]
+ },
+ "tasks": [{ "title": "<probe unit>", "description": "<full brief>" }]
+}
+```
+
+`tasks` then hold 2-5 representative probes; `units` list every other unit. The
+probes run first, the rest are released wave by wave once the probes ran through
+without a person, and a rejection revises the recipe and re-probes. Whether the
+units are one mould is the planning agent's call; the server refuses only a
+malformed declaration, a Goal with `--rollout off`, or a batch already in flight.
+No planning turn starts while a batch is in flight.
+
`wait` is how a turn waits for time or external evidence — never sleep or poll.
Producers deliver the event with `lh goal wake`.
@@ -114,7 +137,8 @@ Submits the wrap-up report from the Goal's wrap-up run.
| Command | Effect |
| ------------------------------------- | -------------------------------------------------------------------- |
-| `lh goal create <title>` | Create a standalone goal and seed its graph |
+| `lh goal create <title>` | Create a goal and seed its graph (`--topic`: a draft) |
+| `lh goal start <id>` | Start a draft (`--rollout` folds its seed tasks into a batch) |
| `lh goal pause <id>` / `resume <id>` | Stop / restart coordination (`--confirm-exit` settles a paused turn) |
| `lh goal restart <id>` | Reset every unfinished task to backlog |
| `lh goal delete <id>` | Delete the goal and its graph (`--yes`) |
@@ -129,6 +153,15 @@ Submits the wrap-up report from the Goal's wrap-up run.
returns a `turnToken` for the first plan; without it the Goal is standalone and
never shows on that topic's goal tray.
+From a chat, `create --topic` opens the Goal as a **draft**: nothing is
+dispatched until it is started. Arrange it first — seed tasks with `-t` or
+`--task-file` (titles with descriptions), adjust with `add-node` / `add-edge` —
+then launch it with `lh goal start <id>`; the owner can also start it from the
+goal page. Many tasks of one recipe start as a batch:
+`lh goal start <id> --rollout canary --recipe-file <md> --probes <2-5 node ids>`
+moves the probes into a batch and turns every other seed (or only `--units`)
+into roster units released wave by wave behind the gate.
+
## Decision gates and graph editing
| Command | Effect |
diff --git a/apps/cli/src/commands/goal.ts b/apps/cli/src/commands/goal.ts
index 8d4ffc98136..d371e048951 100644
--- a/apps/cli/src/commands/goal.ts
+++ b/apps/cli/src/commands/goal.ts
@@ -22,6 +22,34 @@ import { resolveAppUrlBuilder } from './task/url';
// Typed rather than inferred: an `as const` map is indexable by a widened
// `any` node kind, which is how a renamed kind silently printed `undefined`
// here after the type checker had signed off everywhere else.
+
+/** `--task-file`: a JSON array of seed tasks, each a title or {"title","description"}. */
+const parseTaskFile = (raw: string): Array<string | { description?: string; title: string }> => {
+ const parsed: unknown = JSON.parse(raw);
+ if (!Array.isArray(parsed)) throw new Error('--task-file must hold a JSON array');
+ return parsed.map((item, index) => {
+ if (typeof item === 'string' && item.trim()) return item.trim();
+ if (item && typeof item === 'object' && typeof item.title === 'string' && item.title.trim())
+ return {
+ description: typeof item.description === 'string' ? item.description : undefined,
+ title: item.title.trim(),
+ };
+ throw new Error(`--task-file entry ${index} needs a title`);
+ });
+};
+
+/** `--variant mechanism=replica,swr` → one axis and its values. */
+const parseVariant = (raw: string) => {
+ const separator = raw.indexOf('=');
+ const axis = separator > 0 ? raw.slice(0, separator).trim() : '';
+ const values = (separator > 0 ? raw.slice(separator + 1) : '')
+ .split(',')
+ .map((value) => value.trim())
+ .filter(Boolean);
+ if (!axis || !values.length) throw new Error(`--variant expects axis=value1,value2; got ${raw}`);
+ return { axis, values };
+};
+
const nodeIcon: Record<GoalNodeKind, string> = {
batch: '▦',
decision: '◆',
@@ -474,10 +502,24 @@ export function registerGoalCommand(program: Command) {
);
goal
.command('plan <id>')
- .description('Atomically submit the current main Agent plan')
+ .summary('Atomically submit the current main Agent plan')
+ .description(
+ [
+ 'Atomically submit the current main Agent plan.',
+ '',
+ 'A tasks plan lists 1-10 tasks, each a title, a self-contained description and an optional dependsOn.',
+ 'When the work applies one recipe to many units (migrate N stores to one mechanism, give N resources',
+ 'the same caching, update N callers), declare a batch instead of listing every unit: add "rollout" with',
+ '"recipe" (the procedure every unit follows), "units" (every unit beyond the probes, as a title or',
+ '{"title","description"}) and optional "variants" ([{"axis","values"}]); "tasks" then hold 2-5',
+ 'representative probes. The probes run first and the rest are released wave by wave only after the',
+ 'probes ran through without a person; a rejection revises the recipe and re-probes. Units that differ',
+ 'only in names, files or details are still one mould; work whose steps differ per task is not.',
+ ].join('\n'),
+ )
.requiredOption(
'--file <path>',
- 'JSON plan: action tasks/wait/verify/retry/escalate, reason and action fields',
+ 'JSON plan: action tasks/wait/verify/retry/escalate, reason and action fields; a tasks plan may add "rollout" to run its units as a batch',
)
.requiredOption('--token <token>', 'Current server-issued planning turn token')
.option('--operation <id>', 'Defaults to LOBEHUB_OPERATION_ID')
@@ -562,13 +604,37 @@ export function registerGoalCommand(program: Command) {
'--max-manager-turns <n>',
'Add a main Agent with this turn limit; it takes over problems the system planner cannot route',
)
- .description('Create a standalone goal and seed its graph')
+ .summary('Create a goal and seed its graph')
+ .description(
+ [
+ 'Create a goal and seed its graph.',
+ '',
+ 'From a chat, create it with --topic. The goal opens as a draft bound to this topic: nothing is',
+ 'dispatched until it is started, so arrange it first:',
+ ' 1. Place the tasks: -t <titles...>, --task-file <json> for titles with descriptions, or later',
+ ' `lh goal add-node <id> task <title> -d <brief>` and `lh goal add-edge` for prerequisites.',
+ ' 2. Check the graph the command prints (or `lh goal show <id>`).',
+ ' 3. Start it: `lh goal start <id>` (see `lh man goal start`). The owner can also start it from the',
+ ' goal page.',
+ '',
+ 'Many tasks that apply one recipe to different units (migrate N stores, cache N resources, update N',
+ 'callers) should run as a batch: seed every unit as a task, then start with',
+ '`--rollout canary --recipe-file <md> --probes <2-5 node ids>`. The probes run first; the other units',
+ 'are released wave by wave only after the probes ran through without a person.',
+ '',
+ 'Without --topic the goal is standalone and starts at once; omit -t to let the planner decompose it.',
+ ].join('\n'),
+ )
.option('-r, --requirement <text>', 'Acceptance requirement')
.option(
'-i, --instruction <text>',
"The ask in the user's own words, shown on the problem node",
)
- .option('-t, --task <title...>', 'Initial task node titles (omit to let the planner decompose)')
+ .option('-t, --task <title...>', 'Seed task node titles (omit to let the planner decompose)')
+ .option(
+ '--task-file <path>',
+ 'Seed tasks from a JSON array of {"title","description"}; use it when each task needs its own brief',
+ )
.option(
'--agent <id>',
'Goal agent: supervises and plans the goal (defaults to the current agent)',
@@ -593,7 +659,7 @@ export function registerGoalCommand(program: Command) {
)
.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',
+ 'Batch roll-out policy: canary (probe first, then waves), full, or off to forbid a batch. Omit to decide when starting (lh goal start --rollout) or 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)')
@@ -605,7 +671,7 @@ export function registerGoalCommand(program: Command) {
)
.option(
'--topic',
- "Link the goal to the current topic. Use it whenever you create a goal for the user from a chat, not only for /goal: without it the goal is standalone and never shows on this topic's goal tray. This agent supervises the goal from this topic; the output carries a turnToken, so submit the first plan with `lh goal plan <id> --token <turnToken> --file <plan.json>`",
+ "Link the goal to the current topic. Use it whenever you create a goal for the user from a chat, not only for /goal: without it the goal is standalone and never shows on this topic's goal tray. This agent supervises the goal from this topic. The goal opens as a draft: arrange its tasks, then run `lh goal start <id>`",
)
// Former name of --topic, kept so existing prompts and scripts keep working.
.addOption(new Option('--conversation').hideHelp())
@@ -618,6 +684,10 @@ export function registerGoalCommand(program: Command) {
if (options.rollout && !['canary', 'full', 'off'].includes(options.rollout)) {
throw new Error('--rollout must be one of: canary, full, off');
}
+ const seedTasks = [
+ ...((options.task as string[] | undefined) ?? []),
+ ...(options.taskFile ? parseTaskFile(await readFile(options.taskFile, 'utf8')) : []),
+ ];
const operationId = process.env.LOBEHUB_OPERATION_ID;
const fromTopic = Boolean(options.topic || options.conversation);
if (fromTopic && !operationId) {
@@ -682,7 +752,7 @@ export function registerGoalCommand(program: Command) {
projectId: options.project,
requirement: options.requirement,
title,
- tasks: options.task,
+ tasks: seedTasks.length ? seedTasks : undefined,
};
// A topic goal takes its agent and topic from the running
// operation on the server; the CLI only names the run. Device and gateway
@@ -715,6 +785,10 @@ export function registerGoalCommand(program: Command) {
return outputJson({ ...result.data, turnToken, url }, options.json);
printGraph(result.data!);
console.log(`${pc.bold('goal')}: ${url}`);
+ if (result.data!.goal.status === 'draft')
+ console.log(
+ `${pc.bold('draft')}: nothing runs yet. Arrange the tasks, then start it: lh goal start ${result.data!.goal.id}`,
+ );
if (turnToken) {
console.log(
`${pc.bold('planning turn')}: lh goal plan ${result.data!.goal.id} --token ${turnToken} --file <plan.json>`,
@@ -722,6 +796,83 @@ export function registerGoalCommand(program: Command) {
}
});
+ goal
+ .command('start <id>')
+ .summary('Start a draft goal')
+ .description(
+ [
+ 'Start a draft goal. Until now nothing was dispatched; from here the coordinator runs its tasks.',
+ '',
+ 'Plain start dispatches the arranged tasks under the goal budget. To run many tasks of one recipe as a',
+ 'batch, pass --rollout with the recipe and 2-5 probe node ids: the probes move into a batch and run',
+ 'first; every other seed task (or only --units) leaves the graph as a roster unit, its description',
+ "kept as that unit's note, and is released wave by wave once the probes ran through without a person.",
+ 'A rejection revises the recipe and re-probes. Tasks that differ only in names, files or details are',
+ 'one recipe; tasks whose steps differ are not, so start those without --rollout.',
+ ].join('\n'),
+ )
+ .option('--rollout <mode>', 'Fold the seed tasks into a batch: canary or full')
+ .option('--probes <nodeIds...>', 'Seed task node ids that run first (2-5 for canary)')
+ .option(
+ '--units <nodeIds...>',
+ 'Seed task node ids that become batch units (default: every other seed)',
+ )
+ .option('--recipe <text>', 'The procedure every unit follows')
+ .option('--recipe-file <path>', 'Read the recipe from a markdown file')
+ .option(
+ '--variant <axis=values...>',
+ 'An axis the units differ along, e.g. mechanism=replica,swr (repeatable); the gate holds until the probes cover each value',
+ )
+ .option('--operation <id>', 'Defaults to LOBEHUB_OPERATION_ID')
+ .option('--json', 'Output JSON')
+ .action(
+ async (
+ id: string,
+ options: {
+ json?: boolean;
+ operation?: string;
+ probes?: string[];
+ recipe?: string;
+ recipeFile?: string;
+ rollout?: string;
+ units?: string[];
+ variant?: string[];
+ },
+ ) => {
+ let rollout;
+ if (options.rollout) {
+ if (!['canary', 'full'].includes(options.rollout))
+ throw new Error('--rollout must be canary or full');
+ const recipe = options.recipeFile
+ ? await readFile(options.recipeFile, 'utf8')
+ : options.recipe;
+ if (!recipe?.trim()) throw new Error('--rollout needs --recipe or --recipe-file');
+ if (!options.probes?.length) throw new Error('--rollout needs --probes <nodeIds...>');
+ rollout = {
+ probeNodeIds: options.probes,
+ recipe,
+ trigger: options.rollout as 'canary' | 'full',
+ unitNodeIds: options.units,
+ variants: options.variant?.map(parseVariant),
+ };
+ } else if (options.probes || options.units || options.recipe || options.recipeFile) {
+ throw new Error('--probes, --units and --recipe only apply with --rollout');
+ }
+ const client = await getTrpcClient();
+ const operationId = options.operation ?? process.env.LOBEHUB_OPERATION_ID;
+ const result =
+ hasOperationToken() && operationId
+ ? await client.goal.startOperation.mutate({ id, operationId, rollout })
+ : await client.goal.start.mutate({ id, rollout });
+ if (options.json) return outputJson(result.data);
+ log.info(
+ rollout
+ ? `${result.message}: ${rollout.probeNodeIds.length} probes run first, the rest wait behind the batch gate`
+ : result.message,
+ );
+ },
+ );
+
goal
.command('list')
.description('List goals with their graph roll-up')
diff --git a/apps/cli/src/commands/man.ts b/apps/cli/src/commands/man.ts
index f92cdb01cb6..b9ca0ee4c51 100644
--- a/apps/cli/src/commands/man.ts
+++ b/apps/cli/src/commands/man.ts
@@ -97,8 +97,12 @@ function formatAliasesSection(command: Command) {
function formatDescriptionSection(command: Command) {
const description = command.description() || 'No description available.';
+ const body = description
+ .split('\n')
+ .map((line) => (line ? ` ${line}` : ''))
+ .join('\n');
- return ['DESCRIPTION', ` ${description}`].join('\n');
+ return ['DESCRIPTION', body].join('\n');
}
function formatArgumentsSection(command: Command) {
diff --git a/apps/server/src/routers/lambda/__tests__/goal.start.test.ts b/apps/server/src/routers/lambda/__tests__/goal.start.test.ts
new file mode 100644
index 00000000000..70d99583a52
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/goal.start.test.ts
@@ -0,0 +1,78 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(function () {
+ return {};
+ }),
+}));
+
+vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({
+ withScopedPermission: vi.fn(function () {
+ return (opts: any) => opts.next({ ctx: opts.ctx });
+ }),
+}));
+
+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async (importOriginal) => {
+ const { authedProcedure } = await import('@/libs/trpc/lambda');
+ return { ...(await importOriginal<object>()), wsCompatProcedure: authedProcedure };
+});
+
+// Router contract tests do not launch an Agent runtime.
+vi.mock('@/server/services/aiAgent', () => ({ AiAgentService: vi.fn() }));
+vi.mock('@/server/services/goal', () => ({ GoalService: vi.fn(function () {}) }));
+
+const mockFindById = vi.fn();
+vi.mock('@/database/models/goal', () => ({
+ GoalModel: vi.fn(function () {
+ return { findById: mockFindById };
+ }),
+}));
+
+const mockStart = vi.fn();
+vi.mock('@/server/services/goal/start', () => ({
+ GoalStartService: vi.fn(function () {
+ return { start: mockStart };
+ }),
+}));
+
+vi.mock('@/server/services/goal/scheduler', () => ({ scheduleGoalAdvance: vi.fn() }));
+
+const { goalRouter } = await import('../goal');
+
+describe('goalRouter start', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockFindById.mockResolvedValue({ id: 'goal_1', status: 'draft', userId: 'creator' });
+ mockStart.mockResolvedValue({ id: 'goal_1', status: 'running' });
+ });
+
+ /**
+ * Regression: the goal row is visible workspace-wide, so without the row
+ * check any member could launch — and, with a rollout, fold away the seed
+ * nodes of — another member's draft.
+ */
+ it("refuses a workspace member starting another member's draft", async () => {
+ const caller = goalRouter.createCaller({
+ serverDB: {},
+ userId: 'other-member',
+ workspaceId: 'ws_1',
+ workspaceRole: 'member',
+ } as any);
+
+ await expect(caller.start({ id: 'goal_1' })).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(mockStart).not.toHaveBeenCalled();
+ });
+
+ it('lets the creator or a workspace owner start it', async () => {
+ for (const ctx of [
+ { userId: 'creator', workspaceRole: 'member' },
+ { userId: 'someone-else', workspaceRole: 'owner' },
+ ]) {
+ await goalRouter
+ .createCaller({ serverDB: {}, workspaceId: 'ws_1', ...ctx } as any)
+ .start({ id: 'goal_1' });
+ }
+ expect(mockStart).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.ts
index 4cb94b1c0bb..1ffeca5aaf8 100644
--- a/apps/server/src/routers/lambda/goal.ts
+++ b/apps/server/src/routers/lambda/goal.ts
@@ -18,6 +18,7 @@ import {
} from '@/server/services/goal/recoveryPolicy';
import { GoalReportStore, type SubmitGoalReportInput } from '@/server/services/goal/reportStore';
import { scheduleGoalAdvance } from '@/server/services/goal/scheduler';
+import { GoalStartService } from '@/server/services/goal/start';
import { GoalWaitService, goalWakeEventSchema } from '@/server/services/goal/wait';
import {
HeteroOperationPrincipalError,
@@ -336,6 +337,26 @@ const goalOperationReadProcedure = heteroAuthedProcedure.use(serverDatabase).use
});
});
+/** What `start` folds into a batch: the probes that run first, and the recipe every unit follows. */
+const startRolloutInput = z
+ .object({
+ probeNodeIds: z.array(z.string().min(1)).min(2).max(10),
+ recipe: z.string().trim().min(1).max(8000),
+ trigger: z.enum(['canary', 'full']).optional(),
+ unitNodeIds: z.array(z.string().min(1)).max(60).optional(),
+ variants: z
+ .array(
+ z.object({
+ axis: z.string().trim().min(1).max(120),
+ values: z.array(z.string().trim().min(1).max(120)).min(1).max(20),
+ }),
+ )
+ .max(10)
+ .optional(),
+ })
+ .strict();
+const startInput = idInput.extend({ rollout: startRolloutInput.optional() });
+
export const goalRouter = router({
wake: goalWriteProcedure
.input(goalWakeEventSchema.extend({ id: z.string() }))
@@ -441,6 +462,75 @@ export const goalRouter = router({
).submitFromOperation(input.id, input.report as SubmitGoalReportInput, input.operationId);
return { data, success: true };
}),
+ /** Launch a draft goal; until now the coordinator has left its graph alone. */
+ start: goalWriteProcedure.input(startInput).mutation(async ({ ctx, input }) => {
+ // A draft is its creator's arrangement: in a shared workspace only they or
+ // an owner may launch it (and, with a rollout, fold its seed nodes away).
+ const goal = await ctx.goalModel.findById(input.id);
+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
+ assertWorkspaceRowManageable(ctx, goal.userId, 'goal');
+ try {
+ const data = await new GoalStartService(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ ).start(input.id, { rollout: input.rollout });
+ await scheduleGoalAdvance({
+ goalId: input.id,
+ trigger: 'start',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+ return { data, message: 'Goal started', success: true };
+ } catch (error) {
+ mapGoalError(error, 'start');
+ }
+ }),
+ /** `start` from the goal agent's own run, authenticated by its operation token. */
+ startOperation: heteroAuthedProcedure
+ .use(serverDatabase)
+ .input(startInput.extend({ operationId: z.string().min(1) }))
+ .mutation(async ({ ctx, input: { operationId, ...input } }) => {
+ if (ctx.heteroAuthKind !== 'operation' || !ctx.heteroOperation) {
+ throw new TRPCError({
+ code: 'UNAUTHORIZED',
+ message: 'An operation-bound token is required',
+ });
+ }
+ let principal;
+ try {
+ principal = await resolveActiveHeteroOperationPrincipal({
+ capability: 'hetero:ingest',
+ claims: ctx.heteroOperation,
+ db: ctx.serverDB,
+ operationId,
+ });
+ } catch (error) {
+ if (!(error instanceof HeteroOperationPrincipalError)) throw error;
+ throw new TRPCError({
+ cause: error,
+ code:
+ error.status === 401 ? 'UNAUTHORIZED' : error.status === 409 ? 'CONFLICT' : 'FORBIDDEN',
+ message: error.message,
+ });
+ }
+ try {
+ const data = await new GoalStartService(
+ ctx.serverDB,
+ principal.userId,
+ principal.workspaceId,
+ ).start(input.id, { operationId, rollout: input.rollout });
+ await scheduleGoalAdvance({
+ goalId: input.id,
+ trigger: 'start',
+ userId: principal.userId,
+ workspaceId: principal.workspaceId,
+ });
+ return { data, message: 'Goal started', success: true };
+ } catch (error) {
+ mapGoalError(error, 'start');
+ }
+ }),
submitPlan: goalWriteProcedure
.input(
idInput.extend({
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index 05eb3663ae7..85ce4a373bf 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -6,7 +6,6 @@ import {
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,
@@ -103,6 +102,13 @@ import {
import { isGoalReportNode, withoutGoalReport } from './report';
import { GoalReportService } from './reportService';
import { GoalReportStore } from './reportStore';
+import {
+ carriedUnitBrief,
+ createRecipeUnitTask,
+ materializeRolloutBatch,
+ MAX_ROLLOUT_ROSTER,
+ normalizeRolloutRoster,
+} from './rolloutBatch';
import { evaluateRolloutGate, type RolloutGateResult, withGateVerdict } from './rolloutGate';
import { scheduleGoalAdvance } from './scheduler';
import { evaluateHomogeneity } from './spec';
@@ -145,83 +151,6 @@ const GOAL_ENDED_STATUSES = new Set<string>(['achieved', 'canceled']);
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'>) =>
goal.config?.taskAgentId ?? goal.agentId ?? undefined;
@@ -253,6 +182,11 @@ export interface CreateGoalGraphInput {
* prose — that text remains what every Task's execution context reads.
*/
criteria?: Array<{ description?: string; instruction?: string; title: string }>;
+ /**
+ * Create the goal as a `draft`: the graph can be arranged, and nothing is
+ * dispatched until `GoalStartService.start` launches it.
+ */
+ draft?: boolean;
maxRounds?: number;
maxTotalCost?: number;
/**
@@ -415,11 +349,14 @@ export class GoalService {
'Only a run in a topic with an agent can create a goal it supervises',
);
+ // A conversation goal opens as a draft: its agent arranges the graph in
+ // this run, and the goal runs only once someone starts it.
const created = await this.create({
...input,
agentId,
config: { ...input.config, manager: input.config?.manager ?? {} },
createdByAgentId: agentId,
+ draft: true,
topicId,
});
try {
@@ -672,6 +609,7 @@ export class GoalService {
maxTotalCost: input.maxTotalCost,
projectId: input.projectId,
requirement,
+ ...(input.draft ? { status: 'draft' as const } : {}),
...(input.topicId
? { subjectId: input.topicId, subjectType: 'topic' as const }
: { subjectType: 'standalone' as const }),
@@ -2386,6 +2324,13 @@ export class GoalService {
// The coordinator never sees the wrap-up report node: it runs after the
// Goal-level acceptance and does not take part in the Goal's status.
const graph = withoutGoalReport(await this.requireGraph(goalId));
+ // A draft is still being arranged; only `start` hands it to the coordinator.
+ if (graph.goal.status === 'draft')
+ return {
+ goalId,
+ message: `Goal is a draft; start it with lh goal start ${goalId}`,
+ outcome: 'no_progress',
+ };
if (graph.goal.config?.manager) {
// The system's own planner leads whenever the Goal has one: a main Agent is
// the fallback for problems that planner cannot express, not a replacement
@@ -3855,117 +3800,27 @@ export class GoalService {
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,
+ const { probeDrafts, probeIds } = await materializeRolloutBatch({
+ canarySize,
+ goalId,
+ goalModel,
+ policy: existingRollout,
+ problemId: currentProblem.id,
+ probes: draftTasks,
+ recipeOutline: rolloutClaim.recipeOutline,
+ repeatable: rolloutClaim.repeatable,
+ roster,
+ trigger: rolloutTrigger === 'full' ? 'full' : 'canary',
+ variants: rolloutClaim.variants,
+ writer,
});
- 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);
- }
+ committedEffects.push({
+ nodeId: probeIds[index],
+ type: 'created_node',
+ detail: draft.title,
+ });
}
-
- 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;
}
@@ -4155,6 +4010,7 @@ export class GoalService {
state.batchNodeId,
title,
policy.spec?.recipeOutline,
+ policy.unitBriefs?.[title],
);
if (nodeId) {
newIds.push(nodeId);
@@ -4499,7 +4355,7 @@ export class GoalService {
title: unit.title,
})),
...fresh.map((title) => ({
- brief: undefined as string | undefined,
+ brief: policy.unitBriefs?.[title],
from: undefined as string | undefined,
title,
})),
diff --git a/apps/server/src/services/goal/manager.README.md b/apps/server/src/services/goal/manager.README.md
index 4962282187e..10b140b7877 100644
--- a/apps/server/src/services/goal/manager.README.md
+++ b/apps/server/src/services/goal/manager.README.md
@@ -27,6 +27,16 @@ elsewhere are refused. Like `create --topic`, the topic comes from
the run's operation; an operation-token run (device or gateway) needs the
`goal:manage` capability that `/goal` grants.
+A topic goal (`create --topic`, `/goal`) opens as a `draft`. The coordinator
+leaves a draft alone: its agent arranges the graph — seed tasks, `add-node`,
+`add-edge`, even a submitted plan — and `lh goal start` (or the goal page's
+Start) moves it to `running` (`start.ts`). Starting a draft that already holds
+work settles the adopted planning turn on the spot, so dispatch does not wait
+for the creating run to exit; an empty draft keeps the turn open for a plan.
+`start --rollout` folds the seed tasks into a batch: the probes are re-created
+inside it and the other seeds leave the graph as roster units, their
+descriptions kept as unit notes (`rollout.unitBriefs`).
+
The main Agent must have a working shell and an authenticated `lh` CLI in its
execution environment (for example a configured device Kimi/Codex Agent). Its
normal Agent configuration selects the runtime; dispatch uses the same
@@ -55,6 +65,15 @@ commands. It submits a JSON file through `lh goal plan <goal-id> --token <turn>
is written. All existing work must first be settled. The coordinator creates
and runs ordinary Tasks. The terminal acceptance Task depends on the delivered
leaf Tasks, so it renders after the work it closes.
+ A `tasks` plan may add `rollout` — `recipe`, `units` (titles or
+ `{title, description}`) and optional `variants` — to declare one repeated
+ mould. Its `tasks` (2-5) become the probes of a `batch`, the units wait in
+ `rolloutState`, and the coordinator's gate releases them wave by wave
+ (`rolloutBatch.ts`, the same builder the system planner uses after `spec.ts`).
+ The judgement is the main Agent's: only a malformed declaration, a Goal with
+ rollout `off`, a takeover turn or a batch already in flight is refused. While
+ a batch is in flight no uninvited turn starts, so the gate — not a planning
+ turn — answers the moment its members settle.
- `verify`: reason; requests the ordinary independent final acceptance Task.
This does not mark the Goal achieved.
- `retry`: reason (checkpoint-aware recovery instruction), taskId and exact
diff --git a/apps/server/src/services/goal/manager.test.ts b/apps/server/src/services/goal/manager.test.ts
index 01e2dab40a6..8691f3f7639 100644
--- a/apps/server/src/services/goal/manager.test.ts
+++ b/apps/server/src/services/goal/manager.test.ts
@@ -4,6 +4,7 @@ import {
GOAL_COORDINATOR_ACTOR_ID,
GOAL_MANAGER_QUESTION_TITLE,
} from '@lobechat/const/goal';
+import type { GoalConfig } from '@lobechat/types';
import { eq, sql } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -36,6 +37,7 @@ import { deviceGateway } from '../deviceGateway';
import { GoalService } from './index';
import { decideFailedTurn, GoalManagerService, MAX_FAILED_MANAGER_TURNS } from './manager';
import * as scheduler from './scheduler';
+import { GoalStartService } from './start';
import { GoalWaitService } from './wait';
vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: () => db }));
@@ -54,6 +56,7 @@ const service = () => new GoalService(db, userId);
const manager = () => new GoalManagerService(db, userId);
const model = () => new GoalModel(db, userId);
const ops = () => new AgentOperationModel(db, userId);
+const starter = () => new GoalStartService(db, userId);
const taskPlan = {
action: 'tasks' as const,
reason: 'Audit before comparing',
@@ -108,7 +111,7 @@ afterEach(async () => {
await db.delete(table);
});
-async function start(maxTurns = 4) {
+async function start(maxTurns = 4, extraConfig: Partial<GoalConfig> = {}) {
const graph = await service().create({
title: 'Managed research',
createdByAgentId: agentId,
@@ -121,7 +124,7 @@ async function start(maxTurns = 4) {
// `failure_decision` ordering in GoalService).
await db
.update(goals)
- .set({ config: { manager: { maxTurns } } })
+ .set({ config: { manager: { maxTurns }, ...extraConfig } })
.where(eq(goals.id, graph.goal.id));
expect((await service().tick(graph.goal.id)).outcome).toBe('waiting_external');
const state = (await model().findById(graph.goal.id))!.config!.managerState!;
@@ -336,9 +339,9 @@ describe('CLI main Agent planning', () => {
action: 'tasks',
recorded: true,
});
- expect((await service().tick(graph.goal.id)).outcome).toBe('waiting_external');
- await ops().recordCompletion(conversationOpId, { status: 'done' });
- expect((await service().tick(graph.goal.id)).outcome).toBe('advanced');
+ // Planned but still a draft: nothing runs until the run starts it.
+ expect((await service().tick(graph.goal.id)).outcome).toBe('no_progress');
+ await starter().start(graph.goal.id, { operationId: conversationOpId });
expect((await service().tick(graph.goal.id)).taskId).toBeTruthy();
expect(vi.mocked(AiAgentService.prototype.execAgent)).not.toHaveBeenCalled();
expect(
@@ -346,6 +349,156 @@ describe('CLI main Agent planning', () => {
).toEqual([graph.goal.id]);
});
+ describe('draft until started', () => {
+ const seeds = [
+ { title: 'Device list', description: 'src/store/device/action.ts:175' },
+ { title: 'Tool payload', description: 'src/hooks/useToolResultPayload.ts:14' },
+ { title: 'Project skills', description: 'src/hooks/useFetchProjectSkills.ts:17' },
+ { title: 'Home inbox', description: 'HomeInbox/useHomeInboxTopics.ts:39' },
+ ];
+ const seedId = (graph: { nodes: { id: string; title: string }[] }, title: string) =>
+ graph.nodes.find((node) => node.title === title)!.id;
+
+ /**
+ * Regression: a conversation goal seeded with -t went live at once, so its
+ * agent arranged the graph while the coordinator was already dispatching.
+ */
+ it('dispatches nothing from a seeded draft until it is started', async () => {
+ await startConversationRun();
+ const { graph } = await service().createFromConversation(conversationOpId, {
+ tasks: seeds,
+ title: 'Cache the resources',
+ });
+ expect(graph.goal.status).toBe('draft');
+
+ expect((await service().tick(graph.goal.id)).outcome).toBe('no_progress');
+ expect((await service().graph(graph.goal.id)).nodes.some((n) => n.taskId)).toBe(false);
+
+ await starter().start(graph.goal.id, { operationId: conversationOpId });
+ // Started from inside the still-running conversation: the arrangement is
+ // the turn's answer, so the coordinator does not wait for the run to exit.
+ expect((await model().findById(graph.goal.id))!.status).toBe('running');
+ expect((await model().findById(graph.goal.id))!.config!.managerState).toMatchObject({
+ consumed: true,
+ submitted: { action: 'tasks' },
+ });
+ expect((await service().tick(graph.goal.id)).taskId).toBeTruthy();
+ });
+
+ it('folds the seeds into a batch when started with a rollout', async () => {
+ await startConversationRun();
+ const { graph } = await service().createFromConversation(conversationOpId, {
+ tasks: seeds,
+ title: 'Cache the resources',
+ });
+
+ await starter().start(graph.goal.id, {
+ operationId: conversationOpId,
+ rollout: {
+ probeNodeIds: [seedId(graph, 'Device list'), seedId(graph, 'Tool payload')],
+ recipe: 'Persist the resource and show stale data first',
+ },
+ });
+
+ const after = await service().graph(graph.goal.id);
+ const batch = after.nodes.find((n) => n.kind === 'batch')!;
+ const inBatch = new Set(
+ after.edges
+ .filter((edge) => edge.kind === 'contains' && edge.sourceNodeId === batch.id)
+ .map((edge) => edge.targetNodeId),
+ );
+ const tasks = after.nodes.filter((n) => n.kind === 'task');
+ expect(tasks.map((n) => n.title)).toEqual(['Device list', 'Tool payload']);
+ expect(tasks.every((n) => inBatch.has(n.id))).toBe(true);
+ expect(tasks[0].description).toBe('src/store/device/action.ts:175');
+ const config = (await model().findById(graph.goal.id))!.config!;
+ expect(config.rolloutState).toMatchObject({
+ phase: 'probe',
+ unitTitles: ['Device list', 'Tool payload', 'Project skills', 'Home inbox'],
+ });
+ expect(config.rollout?.unitBriefs).toEqual({
+ 'Home inbox': 'HomeInbox/useHomeInboxTopics.ts:39',
+ 'Project skills': 'src/hooks/useFetchProjectSkills.ts:17',
+ });
+ });
+
+ /**
+ * Regression: probes listed after the probe that builds on them lost the
+ * link (only earlier probes were kept), so the two ran at once.
+ */
+ it('keeps a probe prerequisite whatever order the probes are listed in', async () => {
+ await startConversationRun();
+ const { graph } = await service().createFromConversation(conversationOpId, {
+ tasks: seeds,
+ title: 'Cache the resources',
+ });
+ await new GoalGraphModel(db, userId).createEdge(
+ graph.goal.id,
+ seedId(graph, 'Tool payload'),
+ seedId(graph, 'Device list'),
+ 'depends_on',
+ );
+
+ await starter().start(graph.goal.id, {
+ rollout: {
+ // The dependent first: it must still wait for its prerequisite.
+ probeNodeIds: [seedId(graph, 'Tool payload'), seedId(graph, 'Device list')],
+ recipe: 'Persist the resource',
+ },
+ });
+
+ const after = await service().graph(graph.goal.id);
+ const task = (title: string) =>
+ after.nodes.find((n) => n.kind === 'task' && n.title === title)!.id;
+ expect(
+ after.edges.some(
+ (edge) =>
+ edge.kind === 'depends_on' &&
+ edge.sourceNodeId === task('Tool payload') &&
+ edge.targetNodeId === task('Device list'),
+ ),
+ ).toBe(true);
+ });
+
+ it('refuses to fold a seed another kept node depends on, changing nothing', async () => {
+ await startConversationRun();
+ const { graph } = await service().createFromConversation(conversationOpId, {
+ tasks: seeds,
+ title: 'Cache the resources',
+ });
+ await new GoalGraphModel(db, userId).createEdge(
+ graph.goal.id,
+ seedId(graph, 'Home inbox'),
+ seedId(graph, 'Project skills'),
+ 'depends_on',
+ );
+
+ await expect(
+ starter().start(graph.goal.id, {
+ rollout: {
+ probeNodeIds: [seedId(graph, 'Device list'), seedId(graph, 'Tool payload')],
+ recipe: 'Persist the resource',
+ unitNodeIds: [seedId(graph, 'Project skills')],
+ },
+ }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ expect((await model().findById(graph.goal.id))!.status).toBe('draft');
+ expect(
+ (await service().graph(graph.goal.id)).nodes.filter((n) => n.kind === 'task'),
+ ).toHaveLength(4);
+ });
+
+ it('starts a draft only once', async () => {
+ await startConversationRun();
+ const { graph } = await service().createFromConversation(conversationOpId, {
+ tasks: seeds,
+ title: 'Cache the resources',
+ });
+ await starter().start(graph.goal.id);
+ await expect(starter().start(graph.goal.id)).rejects.toMatchObject({ code: 'CONFLICT' });
+ });
+ });
+
it('counts only planning turns, not the rest of the conversation, as management spend', async () => {
await startConversationRun();
await ops().recordStart({
@@ -417,8 +570,8 @@ describe('CLI main Agent planning', () => {
expect(
await manager().submit(graph.goal.id, turnToken, 'op_client_only_local_run', taskPlan),
).toEqual({ action: 'tasks', recorded: true });
- // No run to watch exit: the submitted plan settles the turn.
- expect((await service().tick(graph.goal.id)).outcome).toBe('advanced');
+ // No run to watch exit: starting the planned draft settles the turn.
+ await starter().start(graph.goal.id);
expect((await service().tick(graph.goal.id)).taskId).toBeTruthy();
expect(vi.mocked(AiAgentService.prototype.execAgent)).not.toHaveBeenCalled();
@@ -667,6 +820,7 @@ describe('CLI main Agent planning', () => {
const { graph: b } = await service().createFromConversation(sharedRunId, {
title: 'Second goal',
});
+ await starter().start(b.goal.id);
await ops().recordCompletion(sharedRunId, { status: 'done' });
expect((await service().tick(b.goal.id)).outcome).toBe('advanced');
expect((await service().tick(b.goal.id)).outcome).toBe('waiting_external');
@@ -734,7 +888,12 @@ describe('CLI main Agent planning', () => {
const { id, state, op } = await start();
// No-op writes to the very rows the snapshot covers, mid-turn.
for (const node of (await service().graph(id)).nodes) {
- await new GoalGraphModel(db, userId).updateNodeStatus(id, node.id, node.status, 'retry churn');
+ await new GoalGraphModel(db, userId).updateNodeStatus(
+ id,
+ node.id,
+ node.status,
+ 'retry churn',
+ );
}
await expect(manager().submit(id, state.token, op.id, taskPlan)).resolves.toBeTruthy();
});
@@ -1616,6 +1775,98 @@ describe('CLI main Agent planning', () => {
* whitelist, which is why a Goal could park on a person for hours with a main
* Agent configured and idle.
*/
+describe('a batch the main Agent declares', () => {
+ const batchPlan = {
+ action: 'tasks' as const,
+ reason: 'Twelve resources share one caching recipe',
+ tasks: [
+ { title: 'Device list', description: 'Persist device:listDevices; online state unknown' },
+ { title: 'Tool payload', description: 'Persist toolResultPayload in IndexedDB, capped' },
+ ],
+ rollout: {
+ recipe: 'Persist the resource, show stale data first, revalidate, add a regression test',
+ units: [
+ { title: 'Project skills', description: 'src/hooks/useFetchProjectSkills.ts:17' },
+ 'Home inbox',
+ 'Device list',
+ ],
+ },
+ };
+
+ const settle = async (ids: string[]) => {
+ for (const id of ids)
+ await db.update(goalNodes).set({ status: 'resolved' }).where(eq(goalNodes.id, id));
+ };
+
+ it('lays the probes into a batch and keeps the rest of the roster waiting', async () => {
+ const { id, state, op } = await start();
+ await manager().submit(id, state.token, op.id, batchPlan);
+
+ const graph = await service().graph(id);
+ const batch = graph.nodes.find((n) => n.kind === 'batch')!;
+ const tasksInGraph = graph.nodes.filter((n) => n.kind === 'task');
+ expect(tasksInGraph.map((n) => n.title)).toEqual(['Device list', 'Tool payload']);
+ const contained = graph.edges
+ .filter((edge) => edge.kind === 'contains' && edge.sourceNodeId === batch.id)
+ .map((edge) => edge.targetNodeId);
+ expect(tasksInGraph.every((n) => contained.includes(n.id))).toBe(true);
+ const config = (await model().findById(id))!.config!;
+ expect(config.rolloutState).toMatchObject({
+ phase: 'probe',
+ releasedCount: 2,
+ unitTitles: ['Device list', 'Tool payload', 'Project skills', 'Home inbox'],
+ });
+ expect(config.rollout).toMatchObject({
+ canarySize: 2,
+ trigger: 'canary',
+ unitBriefs: { 'Project skills': 'src/hooks/useFetchProjectSkills.ts:17' },
+ });
+ });
+
+ it('lets the gate release the next wave instead of starting a planning turn', async () => {
+ const { id, state, op } = await start();
+ await manager().submit(id, state.token, op.id, batchPlan);
+ await ops().recordCompletion(op.id, { status: 'done' });
+ await service().tick(id);
+ const probes = (await service().graph(id)).nodes.filter((n) => n.kind === 'task');
+ await settle(probes.map((n) => n.id));
+
+ await service().tick(id);
+
+ const after = await service().graph(id);
+ const released = after.nodes.find((n) => n.title === 'Project skills');
+ expect(released?.description).toContain('src/hooks/useFetchProjectSkills.ts:17');
+ expect(released?.description).toContain('show stale data first');
+ expect((await model().findById(id))!.config!.managerState!.token).toBe(state.token);
+ });
+
+ it.each([
+ {
+ label: 'rollout is turned off for the goal',
+ config: { rollout: { trigger: 'off' as const } },
+ plan: batchPlan,
+ },
+ {
+ label: 'it names a single probe',
+ config: {},
+ plan: { ...batchPlan, tasks: batchPlan.tasks.slice(0, 1) },
+ },
+ {
+ label: 'its roster holds nothing beyond the probes',
+ config: {},
+ plan: { ...batchPlan, rollout: { ...batchPlan.rollout, units: ['Device list'] } },
+ },
+ ])('refuses a batch when $label, writing nothing', async ({ config, plan }) => {
+ const { id, state, op } = await start(4, config);
+
+ await expect(manager().submit(id, state.token, op.id, plan)).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ });
+ expect((await service().graph(id)).nodes.filter((n) => n.kind !== 'problem')).toHaveLength(0);
+ expect((await model().findById(id))!.config!.managerState!.submitted).toBeUndefined();
+ });
+});
+
describe('planner precedence', () => {
const explored = (maxTurns = 4) =>
service().create({
@@ -2532,4 +2783,4 @@ describe('decideFailedTurn', () => {
decideFailedTurn({ category: 'quota', body: { rateLimitInfo: { resetsAt: past } } }, {}, now),
).toMatchObject({ action: 'retry', charged: true });
});
-});
\ No newline at end of file
+});
diff --git a/apps/server/src/services/goal/manager.ts b/apps/server/src/services/goal/manager.ts
index 3ae0a711d84..37520914128 100644
--- a/apps/server/src/services/goal/manager.ts
+++ b/apps/server/src/services/goal/manager.ts
@@ -5,6 +5,7 @@ import {
GOAL_CLARIFICATION_OPTION,
GOAL_COORDINATOR_ACTOR_ID,
GOAL_MANAGER_QUESTION_TITLE,
+ ROLLOUT_MAX_CANARY_SIZE,
} from '@lobechat/const/goal';
import { buildGoalManagerPrompt } from '@lobechat/prompts';
import type {
@@ -45,6 +46,11 @@ import {
QUOTA_RESET_MARGIN_MS,
type RunFailure,
} from './recoveryPolicy';
+import {
+ materializeRolloutBatch,
+ MAX_ROLLOUT_ROSTER,
+ normalizeRolloutRoster,
+} from './rolloutBatch';
import { scheduleGoalAdvance } from './scheduler';
import { recoveryEligibility } from './supervisor/policy';
import { goalWaitSchema, GoalWaitService } from './wait';
@@ -102,6 +108,39 @@ const goalAskSchema = z
ask.options.some((option) => option.id === ask.recommendedOptionId),
{ message: 'recommendedOptionId must name one of the options' },
);
+const planRolloutSchema = z
+ .object({
+ /** The one reusable recipe every unit follows; the batch's Template, revised on every break. */
+ recipe: reason,
+ /** Every unit after the probes in `tasks`, in delivery order; a unit may carry its own notes. */
+ units: z
+ .array(
+ z.union([
+ z.string().trim().min(1).max(255),
+ z
+ .object({
+ title: z.string().trim().min(1).max(255),
+ description: z.string().trim().max(8000).optional(),
+ })
+ .strict(),
+ ]),
+ )
+ .min(1)
+ .max(MAX_ROLLOUT_ROSTER),
+ /** Axes the units vary along; the gate holds until the probes cover every value. */
+ variants: z
+ .array(
+ z
+ .object({
+ axis: z.string().trim().min(1).max(120),
+ values: z.array(z.string().trim().min(1).max(120)).min(1).max(20),
+ })
+ .strict(),
+ )
+ .max(10)
+ .optional(),
+ })
+ .strict();
export const goalPlanSchema = z.discriminatedUnion('action', [
z
.object({
@@ -126,6 +165,14 @@ export const goalPlanSchema = z.discriminatedUnion('action', [
)
.min(1)
.max(10),
+ /**
+ * Declares the work one repeated mould and delivers it as a batch (STAMP):
+ * `tasks` become the probes that run first, the units below wait, and the
+ * coordinator releases them wave by wave once the gate shows the probes ran
+ * through without a person. Whether the work is one mould is the main
+ * Agent's judgement; the server only checks the declaration is well formed.
+ */
+ rollout: planRolloutSchema.optional(),
})
.strict(),
z.object({ action: z.literal('verify'), reason }).strict(),
@@ -499,6 +546,27 @@ export class GoalManagerService {
return state;
});
+ /**
+ * Starting a draft is the planning turn's answer. A conversation goal adopts
+ * the run that created it as its first turn, and coordination waits for that
+ * run to exit — so without this, `start` from inside the run would still
+ * dispatch nothing until the run ends. When the draft holds work, the turn is
+ * settled here: its arrangement is the plan. An empty draft keeps the turn
+ * open so the agent can still submit one. Caller holds the goal row lock.
+ */
+ closeTurnOnStart = async (goal: GoalItem, hasWork: boolean) => {
+ const state = goal.config?.managerState;
+ if (!state || state.consumed || !hasWork) return;
+ await this.save(this.db, goal.id, {
+ ...state,
+ consumed: true,
+ submitted: state.submitted ?? {
+ action: 'tasks',
+ reason: 'Started with the tasks arranged in the draft',
+ },
+ });
+ };
+
/**
* Move the management conversation onto the agent that now supervises the Goal.
*
@@ -1111,6 +1179,12 @@ export class GoalManagerService {
if (!problem) {
if (state?.readyForAcceptance || nodes.some((n) => n.title === GOAL_ACCEPTANCE_TASK_TITLE))
return null;
+ // A batch in flight is the coordinator's to drive: when its members settle,
+ // the gate decides the next wave. A turn here would claim that moment —
+ // every member is terminal, so nothing looks in flight — and the waves
+ // would never release. Planning resumes once the roster is delivered.
+ const batch = goal.config?.rolloutState;
+ if (batch && batch.phase !== 'done') return null;
const tasks = await new TaskModel(this.db, this.userId, this.workspaceId).findByIds(
unfinished.flatMap((n) => (n.taskId ? [n.taskId] : [])),
);
@@ -1381,7 +1455,10 @@ export class GoalManagerService {
return rejectPlan('operation_mismatch', op?.status);
}
const graph = await this.graph(db).getGraph(goal.id);
- if (!graph || !activeStatuses.has(goal.status)) return rejectPlan('inactive', op?.status);
+ // A draft takes plans too: the tasks land on the graph it is arranging, and
+ // nothing dispatches until the goal is started.
+ if (!graph || !(activeStatuses.has(goal.status) || goal.status === 'draft'))
+ return rejectPlan('inactive', op?.status);
if (graph.decisions.some((d) => d.status === 'pending'))
return rejectPlan('pending_decision', op?.status);
if (state.submitted) return { code: 'duplicate', ok: true, submitted: state.submitted };
@@ -1547,6 +1624,83 @@ export class GoalManagerService {
});
};
+ /**
+ * Lay a main Agent's declared batch onto the graph, returning the probe node
+ * IDs in the order of `plan.tasks`. Refuses — before anything is written — a
+ * declaration the Goal's own policy or state cannot carry: rollout turned off,
+ * a takeover turn, a batch already in flight, or a probe/roster size outside
+ * what the gate and the waves can deliver whole.
+ */
+ private declareBatch = async (
+ db: LobeChatDatabase,
+ input: {
+ agentId: string;
+ goal: GoalItem;
+ plan: Extract<GoalPlan, { action: 'tasks' }> & {
+ rollout: z.infer<typeof planRolloutSchema>;
+ };
+ problemId?: string;
+ state: GoalManagerState;
+ writer: GoalGraphModel;
+ },
+ ): Promise<string[]> => {
+ const { agentId, goal, plan, problemId, state, writer } = input;
+ const refuse = (message: string, code: 'BAD_REQUEST' | 'CONFLICT' = 'BAD_REQUEST') => {
+ throw new TRPCError({ code, message });
+ };
+ const policy = goal.config?.rollout;
+ const trigger = policy?.trigger ?? 'canary';
+ if (trigger === 'off')
+ refuse('This Goal has rollout turned off; submit the units as ordinary tasks');
+ if (state.problem) refuse('A takeover turn cannot open a batch; answer the problem it names');
+ const active = goal.config?.rolloutState;
+ if (active && active.phase !== 'done')
+ refuse('A batch is already in flight; let its gate and waves finish first', 'CONFLICT');
+ if (!problemId) refuse('The Goal has no problem node to hang a batch on');
+ const maxProbes = trigger === 'full' ? 10 : ROLLOUT_MAX_CANARY_SIZE;
+ if (plan.tasks.length < 2 || plan.tasks.length > maxProbes)
+ refuse(`A batch runs 2-${maxProbes} probe tasks before its gate; got ${plan.tasks.length}`);
+
+ const units = plan.rollout.units.map((unit) =>
+ typeof unit === 'string' ? { title: unit } : unit,
+ );
+ const roster = normalizeRolloutRoster(
+ units.map((unit) => unit.title),
+ plan.tasks,
+ plan.tasks.length,
+ Number.POSITIVE_INFINITY,
+ );
+ if (roster.length > MAX_ROLLOUT_ROSTER)
+ refuse(
+ `A batch roster holds at most ${MAX_ROLLOUT_ROSTER} units; got ${roster.length}. Split the work into more than one Goal`,
+ );
+ if (roster.length <= plan.tasks.length)
+ refuse('The batch roster has no units beyond its probes; submit ordinary tasks instead');
+
+ const unitBriefs = Object.fromEntries(
+ units.flatMap((unit) =>
+ 'description' in unit && unit.description ? [[unit.title, unit.description]] : [],
+ ),
+ );
+ const { probeIds } = await materializeRolloutBatch({
+ canarySize: plan.tasks.length,
+ createdByAgentId: agentId,
+ goalId: goal.id,
+ goalModel: new GoalModel(db, this.userId, this.workspaceId),
+ policy,
+ problemId: problemId!,
+ probes: plan.tasks.map((task) => ({ instruction: task.description, title: task.title })),
+ recipeOutline: plan.rollout.recipe,
+ repeatable: true,
+ roster,
+ trigger: trigger === 'full' ? 'full' : 'canary',
+ unitBriefs,
+ variants: plan.rollout.variants,
+ writer,
+ });
+ return probeIds;
+ };
+
submit = async (goalId: string, token: string, operationId: string, input: GoalPlan) => {
const plan = goalPlanSchema.parse(input);
const armed = plan.action === 'wait' ? GoalWaitService.arm(plan.until) : undefined;
@@ -1622,7 +1776,18 @@ export class GoalManagerService {
});
const problem = graph.nodes.find((n) => n.kind === 'problem');
const createdIds: string[] = [];
- for (const { dependsOn: _dependsOn, ...task } of plan.tasks) {
+ if (plan.rollout) {
+ const probeIds = await this.declareBatch(db, {
+ agentId,
+ goal,
+ plan: { ...plan, rollout: plan.rollout },
+ problemId: problem?.id,
+ state,
+ writer: authored,
+ });
+ createdIds.push(...probeIds);
+ }
+ for (const { dependsOn: _dependsOn, ...task } of plan.rollout ? [] : plan.tasks) {
const node = await authored.createNode(goalId, {
...task,
kind: 'task',
@@ -1742,4 +1907,4 @@ export class GoalManagerService {
);
return result;
};
-}
\ No newline at end of file
+}
diff --git a/apps/server/src/services/goal/rolloutBatch.ts b/apps/server/src/services/goal/rolloutBatch.ts
new file mode 100644
index 00000000000..f357ec92eb4
--- /dev/null
+++ b/apps/server/src/services/goal/rolloutBatch.ts
@@ -0,0 +1,256 @@
+import {
+ GOAL_BATCH_ASSAY_TITLE,
+ GOAL_BATCH_TEMPLATE_TITLE,
+ GOAL_BATCH_TITLE,
+ ROLLOUT_WAVE_SIZE_DEFAULT,
+} from '@lobechat/const/goal';
+import type { GoalRolloutPolicy, GoalRolloutState, GoalRolloutVariantAxis } from '@lobechat/types';
+
+import type { GoalModel } from '@/database/models/goal';
+import type { GoalGraphModel } from '@/database/models/goalGraph';
+
+/** Upper bound on a batch roster; a planner that over-lists cannot swamp the config. */
+export 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.
+ */
+export const normalizeRolloutRoster = (
+ units: string[] | undefined,
+ probeDrafts: { title: string }[],
+ 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.
+ */
+export 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 unit that came
+ * with its own notes (an agent-declared roster), or a re-opened unit, also keeps
+ * that brief.
+ */
+export 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;
+};
+
+export interface RolloutBatchProbe {
+ /** 0-based indices of earlier probes this one builds on. */
+ dependsOn?: number[];
+ instruction: string;
+ title: string;
+}
+
+export interface MaterializeRolloutBatchInput {
+ /** How many of `probes` run before the gate; the rest of the roster waits. */
+ canarySize: number;
+ /** The main Agent that declared the batch; absent when the system planner did. */
+ createdByAgentId?: string;
+ goalId: string;
+ goalModel: GoalModel;
+ /** The policy the caller already chose (trigger, sizes); persisted underneath. */
+ policy?: GoalRolloutPolicy;
+ probes: RolloutBatchProbe[];
+ problemId: string;
+ recipeOutline?: string;
+ repeatable: boolean;
+ /** The whole roster, probes first, in delivery order. */
+ roster: string[];
+ trigger: 'canary' | 'full';
+ /** Per-unit notes keyed by roster title, appended to the recipe when a wave releases it. */
+ unitBriefs?: Record<string, string>;
+ variants?: GoalRolloutVariantAxis[];
+ writer: GoalGraphModel;
+}
+
+/**
+ * Lay one repeated mould onto the graph as a class rather than N flat siblings:
+ * a `batch` container, its Template (the recipe), its Assay (the release gate)
+ * and only the K probe tasks. The roster waits in `rolloutState`; the
+ * coordinator releases it one wave at a time once the gate passes.
+ *
+ * Shared by the system planner (after `spec.ts` agrees with its claim) and by a
+ * main Agent that declares the rollout in its own plan.
+ */
+export const materializeRolloutBatch = async ({
+ canarySize,
+ createdByAgentId,
+ goalId,
+ goalModel,
+ policy,
+ problemId,
+ probes,
+ recipeOutline,
+ repeatable,
+ roster,
+ trigger,
+ unitBriefs,
+ variants,
+ writer,
+}: MaterializeRolloutBatchInput) => {
+ const batch = await writer.createNode(goalId, {
+ createdByAgentId,
+ description: recipeOutline,
+ kind: 'batch',
+ title: GOAL_BATCH_TITLE,
+ });
+ if (!batch) throw new Error('Failed to create a planned batch');
+ await writer.createEdge(goalId, problemId, batch.id, 'decomposes');
+
+ const template = await writer.createNode(goalId, {
+ createdByAgentId,
+ description: 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 =
+ trigger === 'full'
+ ? undefined
+ : await writer.createNode(goalId, {
+ createdByAgentId,
+ 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 (trigger !== 'full' && !assay) throw new Error('Failed to create a batch assay');
+
+ const probeDrafts = probes.slice(0, canarySize);
+ const probeIds: string[] = [];
+ for (const draft of probeDrafts) {
+ const node = await writer.createNode(goalId, {
+ createdByAgentId,
+ 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);
+ }
+
+ // 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 (trigger === 'full') {
+ for (const title of roster.slice(probeIds.length)) {
+ const nodeId = await createRecipeUnitTask(
+ writer,
+ goalId,
+ batch.id,
+ title,
+ recipeOutline,
+ unitBriefs?.[title],
+ );
+ if (nodeId) massNodeIds.push(nodeId);
+ }
+ }
+
+ const rolloutState: GoalRolloutState = {
+ batchNodeId: batch.id,
+ assayNodeId: assay?.id,
+ massNodeIds: massNodeIds.length ? massNodeIds : undefined,
+ phase: trigger === 'full' ? 'mass' : 'probe',
+ probeNodeIds: probeIds,
+ releasedCount: probeIds.length + massNodeIds.length,
+ templateNodeId: template.id,
+ templateRevision: 1,
+ unitTitles: roster,
+ waveIndex: trigger === 'full' ? 1 : 0,
+ };
+ await goalModel.updateRolloutState(goalId, rolloutState);
+
+ // Always persist what was 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, {
+ ...policy,
+ canarySize: trigger === 'full' ? undefined : (policy?.canarySize ?? canarySize),
+ spec: { recipeOutline, repeatable, variantAxes: variants },
+ trigger,
+ unitBriefs: unitBriefs && Object.keys(unitBriefs).length ? unitBriefs : undefined,
+ units: roster,
+ waveSize: policy?.waveSize ?? ROLLOUT_WAVE_SIZE_DEFAULT,
+ });
+
+ return { batchId: batch.id, massNodeIds, probeDrafts, probeIds };
+};
diff --git a/apps/server/src/services/goal/start.ts b/apps/server/src/services/goal/start.ts
new file mode 100644
index 00000000000..b5eea84e97b
--- /dev/null
+++ b/apps/server/src/services/goal/start.ts
@@ -0,0 +1,279 @@
+import { ROLLOUT_MAX_CANARY_SIZE } from '@lobechat/const/goal';
+import type { GoalGraphSnapshot, GoalItem, GoalRolloutVariantAxis } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+
+import { AgentOperationModel } from '@/database/models/agentOperation';
+import { GoalModel } from '@/database/models/goal';
+import { GoalGraphModel } from '@/database/models/goalGraph';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { GoalManagerService } from './manager';
+import {
+ materializeRolloutBatch,
+ MAX_ROLLOUT_ROSTER,
+ normalizeRolloutRoster,
+} from './rolloutBatch';
+
+export interface StartGoalRolloutInput {
+ /** Seed task nodes that run first, before the gate; the rest of the seeds become the roster. */
+ probeNodeIds: string[];
+ /** The one procedure every unit follows; the batch's Template. */
+ recipe: string;
+ /** Overrides the goal's own `config.rollout.trigger`; `off` is not a way to start a batch. */
+ trigger?: 'canary' | 'full';
+ /** Seeds that become roster units; every other seed when omitted. Seeds left out stay ordinary tasks. */
+ unitNodeIds?: string[];
+ variants?: GoalRolloutVariantAxis[];
+}
+
+export interface StartGoalInput {
+ /**
+ * The agent run starting the goal. Must be the goal agent's: a draft is the
+ * goal agent's arrangement, so another agent cannot launch it.
+ */
+ operationId?: string;
+ rollout?: StartGoalRolloutInput;
+}
+
+const refuse = (message: string, code: 'BAD_REQUEST' | 'CONFLICT' = 'BAD_REQUEST'): never => {
+ throw new TRPCError({ code, message });
+};
+
+/**
+ * Seed tasks still waiting in the draft: unbound task nodes outside any
+ * container — seeded with `-t`/`--task-file`, added with `add-node`, or planned.
+ * Only these can be folded into a batch; a node inside an experiment is work
+ * of another kind.
+ */
+const draftSeeds = (graph: GoalGraphSnapshot) => {
+ const contained = new Set(
+ graph.edges.filter((edge) => edge.kind === 'contains').map((edge) => edge.targetNodeId),
+ );
+ return graph.nodes.filter(
+ (node) =>
+ node.kind === 'task' && node.status === 'proposed' && !node.taskId && !contained.has(node.id),
+ );
+};
+
+/**
+ * The probes with every prerequisite ahead of what builds on it, otherwise in
+ * the order given. The batch keeps a probe's `depends_on` links only to earlier
+ * probes, so `--probes` listed out of dependency order would otherwise drop the
+ * link and run the two at once. A cycle cannot be ordered and is refused.
+ */
+const orderByPrerequisites = <T extends { id: string; title: string }>(
+ probes: T[],
+ graph: GoalGraphSnapshot,
+): T[] => {
+ const ids = new Set(probes.map((probe) => probe.id));
+ const prerequisites = new Map(
+ probes.map((probe) => [
+ probe.id,
+ new Set(
+ graph.edges
+ .filter(
+ (edge) =>
+ edge.kind === 'depends_on' &&
+ edge.sourceNodeId === probe.id &&
+ ids.has(edge.targetNodeId),
+ )
+ .map((edge) => edge.targetNodeId),
+ ),
+ ]),
+ );
+ const ordered: T[] = [];
+ const placed = new Set<string>();
+ while (ordered.length < probes.length) {
+ const next = probes.find(
+ (probe) =>
+ !placed.has(probe.id) &&
+ [...prerequisites.get(probe.id)!].every((prerequisite) => placed.has(prerequisite)),
+ );
+ if (!next)
+ return refuse(
+ `The probes depend on each other in a cycle: ${probes
+ .filter((probe) => !placed.has(probe.id))
+ .map((probe) => `"${probe.title}"`)
+ .join(', ')}`,
+ );
+ ordered.push(next);
+ placed.add(next.id);
+ }
+ return ordered;
+};
+
+/**
+ * Launch a draft Goal.
+ *
+ * A Goal created from a conversation starts as a `draft`: its agent (or the
+ * person) arranges the graph — seed tasks, edges, a batch — and nothing is
+ * dispatched until someone starts it. Starting is the one explicit transition
+ * to `running`; the coordinator ignores a draft until then.
+ */
+export class GoalStartService {
+ constructor(
+ private readonly db: LobeChatDatabase,
+ private readonly userId: string,
+ private readonly workspaceId?: string,
+ ) {}
+
+ start = async (goalId: string, input: StartGoalInput = {}): Promise<GoalItem> =>
+ this.db.transaction(async (tx) => {
+ const db = tx as unknown as LobeChatDatabase;
+ const goalModel = new GoalModel(db, this.userId, this.workspaceId);
+ const goal = await goalModel.lockById(goalId);
+ if (!goal) return refuse('Goal not found');
+ if (goal.status !== 'draft')
+ refuse(`Goal is ${goal.status}; only a draft goal can be started`, 'CONFLICT');
+
+ let actorAgentId: string | undefined;
+ if (input.operationId) {
+ const operation = await new AgentOperationModel(db, this.userId, this.workspaceId).findById(
+ input.operationId,
+ );
+ // The run acts for its own user: the goal agent's run may start only a
+ // goal that user owns, never another workspace member's draft.
+ if (!operation || operation.agentId !== goal!.agentId || goal!.userId !== this.userId)
+ refuse('Only the goal agent or its owner can start this goal', 'CONFLICT');
+ actorAgentId = operation!.agentId ?? undefined;
+ }
+ const writer = new GoalGraphModel(
+ db,
+ this.userId,
+ this.workspaceId,
+ actorAgentId ? { id: actorAgentId, type: 'agent' } : undefined,
+ );
+
+ if (input.rollout) await this.foldSeedsIntoBatch(db, goal!, writer, input.rollout);
+
+ const graph = await writer.getGraph(goalId);
+ const hasWork = !!graph?.nodes.some(
+ (node) =>
+ node.kind === 'task' && !['resolved', 'retired', 'rejected'].includes(node.status),
+ );
+ await new GoalManagerService(db, this.userId, this.workspaceId).closeTurnOnStart(
+ goal!,
+ hasWork,
+ );
+ await goalModel.updateStatus(goalId, 'running');
+ await writer.recordGoalStatus(
+ goalId,
+ 'draft',
+ 'running',
+ actorAgentId ? 'Started by the goal agent' : 'Started by the owner',
+ );
+ return (await goalModel.findById(goalId))!;
+ });
+
+ /**
+ * Turn the draft's seed tasks into one batch: the chosen probes run first,
+ * the unit seeds (every other seed unless named) become the roster — each
+ * description is that unit's note — and leave the graph until the gate
+ * releases them. The seeds never ran,
+ * so removing them loses no history.
+ */
+ private foldSeedsIntoBatch = async (
+ db: LobeChatDatabase,
+ goal: GoalItem,
+ writer: GoalGraphModel,
+ rollout: StartGoalRolloutInput,
+ ) => {
+ const policy = goal.config?.rollout;
+ if (policy?.trigger === 'off')
+ refuse('This Goal has rollout turned off; start it without a batch');
+ const trigger = rollout.trigger ?? (policy?.trigger === 'full' ? 'full' : 'canary');
+ if (!rollout.recipe.trim()) refuse('A batch needs the recipe every unit follows');
+
+ const graph = await writer.getGraph(goal.id);
+ const problem = graph?.nodes.find((node) => node.kind === 'problem');
+ if (!graph || !problem) return refuse('The Goal has no problem node to hang a batch on');
+ if (goal.config?.rolloutState) refuse('This Goal already has a batch', 'CONFLICT');
+
+ const seeds = draftSeeds(graph);
+ const probeIds = [...new Set(rollout.probeNodeIds)];
+ const probes = orderByPrerequisites(
+ probeIds.map(
+ (id) =>
+ seeds.find((seed) => seed.id === id) ??
+ refuse(`Probe ${id} is not a seed task of this draft`),
+ ),
+ graph,
+ );
+ const maxProbes = trigger === 'full' ? 10 : ROLLOUT_MAX_CANARY_SIZE;
+ if (probes.length < 2 || probes.length > maxProbes)
+ refuse(`A batch runs 2-${maxProbes} probe tasks before its gate; got ${probes.length}`);
+ const units = rollout.unitNodeIds
+ ? [...new Set(rollout.unitNodeIds)]
+ .filter((id) => !probeIds.includes(id))
+ .map(
+ (id) =>
+ seeds.find((seed) => seed.id === id) ??
+ refuse(`Unit ${id} is not a seed task of this draft`),
+ )
+ : seeds.filter((seed) => !probeIds.includes(seed.id));
+ if (!units.length)
+ refuse('Every seed is a probe; leave some seeds as units or start without a batch');
+ // The folded seeds leave the graph, and their links go with them. A node
+ // staying behind that builds on one would silently lose that prerequisite.
+ const folded = new Set([...probes, ...units].map((node) => node.id));
+ const stranded = graph.edges.find(
+ (edge) =>
+ edge.kind === 'depends_on' &&
+ folded.has(edge.targetNodeId) &&
+ !folded.has(edge.sourceNodeId),
+ );
+ if (stranded) {
+ const title = (id: string) => graph.nodes.find((node) => node.id === id)?.title ?? id;
+ refuse(
+ `"${title(stranded.sourceNodeId)}" depends on "${title(stranded.targetNodeId)}", which joins the batch; remove that link or keep it out of the batch`,
+ );
+ }
+
+ const roster = normalizeRolloutRoster(
+ units.map((unit) => unit.title),
+ probes,
+ probes.length,
+ Number.POSITIVE_INFINITY,
+ );
+ if (roster.length > MAX_ROLLOUT_ROSTER)
+ refuse(
+ `A batch roster holds at most ${MAX_ROLLOUT_ROSTER} units; got ${roster.length}. Split the work into more than one Goal`,
+ );
+
+ // Probe-to-probe prerequisites survive the move; links to units do not —
+ // a unit is not on the graph until a wave releases it.
+ const indexOf = new Map(probes.map((probe, index) => [probe.id, index]));
+ const probeDrafts = probes.map((probe, index) => ({
+ dependsOn: graph.edges
+ .filter((edge) => edge.kind === 'depends_on' && edge.sourceNodeId === probe.id)
+ .map((edge) => indexOf.get(edge.targetNodeId))
+ // Ordered by prerequisites above, so every probe it builds on comes first.
+ .filter((dep): dep is number => dep !== undefined && dep < index),
+ instruction: probe.description?.trim() || probe.title,
+ title: probe.title,
+ }));
+ const unitBriefs = Object.fromEntries(
+ units.flatMap((unit) =>
+ unit.description?.trim() ? [[unit.title, unit.description.trim()]] : [],
+ ),
+ );
+
+ await writer.removeDraftNodes(goal.id, [...folded], 'Folded into the batch before start');
+ await materializeRolloutBatch({
+ canarySize: probes.length,
+ createdByAgentId: goal.agentId ?? undefined,
+ goalId: goal.id,
+ goalModel: new GoalModel(db, this.userId, this.workspaceId),
+ policy,
+ problemId: problem.id,
+ probes: probeDrafts,
+ recipeOutline: rollout.recipe.trim(),
+ repeatable: true,
+ roster,
+ trigger,
+ unitBriefs,
+ variants: rollout.variants,
+ writer,
+ });
+ };
+}
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index e6d9ff2690d..a511141952e 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -656,6 +656,7 @@
"goalList.roundProgress": "Round {{current}}/{{total}}",
"goalList.status.achieved": "Achieved",
"goalList.status.canceled": "Canceled",
+ "goalList.status.draft": "Not started",
"goalList.status.error": "Needs attention",
"goalList.status.paused": "Paused",
"goalList.status.planning": "Planning",
@@ -770,6 +771,7 @@
"goalProcess.deliverables.from": "From “{{title}}”",
"goalProcess.deliverables.title": "Deliverables",
"goalProcess.deliverables.untitled": "Untitled",
+ "goalProcess.draft": "Not started — nothing runs until you start it. Check the tasks below first.",
"goalProcess.edge.contradicts": "contradicts",
"goalProcess.edge.derivedFrom": "Derived from",
"goalProcess.edge.investigates": "investigates",
@@ -1092,6 +1094,7 @@
"goalProcess.signOff.requestChangesEffect": "Send it back to the Agent. Say what to change in the notes.",
"goalProcess.signOff.sentBack": "Sent back for changes",
"goalProcess.stale.description": "No heartbeat for {{duration}}. The next advance marks this attempt lost and starts a fresh one — it does not count as a failure.",
+ "goalProcess.start": "Start",
"goalProcess.summary.done": "Done · {{count}} attempts",
"goalProcess.summary.gateOpen": "Waiting for your decision",
"goalProcess.summary.gateResolved": "Decided: {{option}}",
@@ -1116,6 +1119,7 @@
"goalTask.stage.verifying": "Accept",
"goalTask.status.achieved": "Achieved",
"goalTask.status.canceled": "Canceled",
+ "goalTask.status.draft": "Not started",
"goalTask.status.error": "Needs attention",
"goalTask.status.paused": "Paused",
"goalTask.status.planning": "Planning",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index cd497088d5e..ac08af19df2 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -656,6 +656,7 @@
"goalList.roundProgress": "第 {{current}}/{{total}} 轮",
"goalList.status.achieved": "已达成",
"goalList.status.canceled": "已取消",
+ "goalList.status.draft": "未启动",
"goalList.status.error": "需要处理",
"goalList.status.paused": "已暂停",
"goalList.status.planning": "规划中",
@@ -770,6 +771,7 @@
"goalProcess.deliverables.from": "来自「{{title}}」",
"goalProcess.deliverables.title": "交付物",
"goalProcess.deliverables.untitled": "未命名",
+ "goalProcess.draft": "尚未启动:启动前不会派发任何任务,可以先检查下面的任务。",
"goalProcess.edge.contradicts": "反驳",
"goalProcess.edge.derivedFrom": "派生自",
"goalProcess.edge.investigates": "调查",
@@ -1092,6 +1094,7 @@
"goalProcess.signOff.requestChangesEffect": "退回给 Agent 重做,在补充说明里写要改什么",
"goalProcess.signOff.sentBack": "已退回修改",
"goalProcess.stale.description": "已 {{duration}} 没有心跳。下一次推进会把这次尝试标为失联并重开一次,不计失败次数。",
+ "goalProcess.start": "启动",
"goalProcess.summary.done": "完成 · {{count}} 次尝试",
"goalProcess.summary.gateOpen": "等你决定",
"goalProcess.summary.gateResolved": "已决定:{{option}}",
@@ -1116,6 +1119,7 @@
"goalTask.stage.verifying": "验收",
"goalTask.status.achieved": "已达成",
"goalTask.status.canceled": "已取消",
+ "goalTask.status.draft": "未启动",
"goalTask.status.error": "需要处理",
"goalTask.status.paused": "已暂停",
"goalTask.status.planning": "规划中",
diff --git a/packages/agent-tracing/src/goal/types.ts b/packages/agent-tracing/src/goal/types.ts
index ecc413473ba..b1569c23f47 100644
--- a/packages/agent-tracing/src/goal/types.ts
+++ b/packages/agent-tracing/src/goal/types.ts
@@ -18,6 +18,8 @@
export type GoalAdvanceTrigger =
| 'wake'
| 'create'
+ /** A draft was started: the coordinator's first move on an arranged graph. */
+ | 'start'
| 'decide'
| 'settle'
| 'sweep'
diff --git a/packages/builtin-tool-goal/src/conversationGoalPrompt.test.ts b/packages/builtin-tool-goal/src/conversationGoalPrompt.test.ts
index 5c79bf72eb9..35064b31536 100644
--- a/packages/builtin-tool-goal/src/conversationGoalPrompt.test.ts
+++ b/packages/builtin-tool-goal/src/conversationGoalPrompt.test.ts
@@ -32,12 +32,27 @@ describe('withConversationGoalPrompt', () => {
expect(withConversationGoalPrompt(' ', '/goal ship the report')).toBe(conversationGoalPrompt);
});
- it('tells the agent to create the goal from this conversation and plan it in the same run', () => {
+ it('tells the agent to create the goal from this conversation and start it in the same run', () => {
expect(conversationGoalPrompt).toContain('lh goal create');
expect(conversationGoalPrompt).toContain('--conversation');
+ // A bound goal handed back with a turn token is still planned in this run.
expect(conversationGoalPrompt).toContain('lh goal plan <goalId> --token <turnToken>');
});
+ /**
+ * Regression: a conversation goal went live the moment it was created, so
+ * the agent arranged its tasks while they were already dispatching, and a
+ * set of one-recipe tasks could never become a batch.
+ */
+ it('creates the goal as a draft with its tasks, then starts it, as a batch when one recipe', () => {
+ expect(conversationGoalPrompt).toContain('--task-file <tasks.json>');
+ expect(conversationGoalPrompt).toContain('nothing is dispatched until you start it');
+ expect(conversationGoalPrompt).toContain('lh goal start <goalId> --json');
+ expect(conversationGoalPrompt).toContain(
+ 'lh goal start <goalId> --rollout canary --recipe-file <recipe.md> --probes',
+ );
+ });
+
it('binds a goal the user names instead of creating a duplicate', () => {
// `goal:manage` reaches a device or gateway run only through `/goal`, so
// these instructions are the only way such a run can bind an existing goal.
diff --git a/packages/builtin-tool-goal/src/conversationGoalPrompt.ts b/packages/builtin-tool-goal/src/conversationGoalPrompt.ts
index 08730db4534..93e19ecf141 100644
--- a/packages/builtin-tool-goal/src/conversationGoalPrompt.ts
+++ b/packages/builtin-tool-goal/src/conversationGoalPrompt.ts
@@ -15,18 +15,19 @@ import { isGoalPrompt } from './goalPrompt';
export const conversationGoalPrompt = `The user sent this request with LobeHub's /goal command (the prefix was removed before it reached you; it is not your own /goal command). They are asking you to turn the request into a long-running LobeHub Goal that you supervise from this conversation, not to do the work yourself in this run.
1. Draft the goal from the user's request, in the user's language: a short title, the requirement, and one concrete, checkable acceptance criterion per explicit requirement. Do not add requirements the user did not ask for.
-2. Create it bound to this conversation (the LOBEHUB_* environment already identifies you and this conversation):
- lh goal create "<title>" --conversation -r "<requirement>" -i "<the user's ask in their words>" --criterion "<criterion>" --criterion "<criterion>" --json
- The output contains goal.id and turnToken. You are now the goal's supervising agent, and this run is its first planning turn.
-3. Plan it now from the goal graph already printed by lh goal create (do not run lh goal show or other lh goal commands: this run's credentials only allow creating or binding this goal and submitting its plan). Write a JSON plan file and submit it once:
- lh goal plan <goalId> --token <turnToken> --file <path> --json
- Plan schema: {"action":"tasks","reason":"evidence-based rationale","tasks":[{"title":"specific task","description":"self-contained contract: inputs, output and acceptance"}]}
- Plan bounded, independent tasks; the goal's coordinator dispatches and runs them under the goal budget.
-4. Then end the run with one or two sentences in the user's language: the goal is running, and what the first tasks are.
+2. Create it bound to this conversation, with its tasks (the LOBEHUB_* environment already identifies you and this conversation). Write the tasks to a JSON file — bounded, independent tasks, each [{"title":"specific task","description":"self-contained contract: inputs, output and acceptance"}] — then:
+ lh goal create "<title>" --conversation -r "<requirement>" -i "<the user's ask in their words>" --criterion "<criterion>" --criterion "<criterion>" --task-file <tasks.json> --json
+ The goal opens as a draft: nothing is dispatched until you start it. The output contains goal.id, the graph with each task's node id, and turnToken. You are now the goal's supervising agent.
+3. Start it from the graph lh goal create printed (do not run lh goal show or other lh goal commands: this run's credentials only allow creating or binding this goal, planning it and starting it):
+ lh goal start <goalId> --json
+ If the tasks apply one recipe to many units (migrate N stores to one mechanism, give N resources the same caching, update N callers), start them as a batch instead:
+ lh goal start <goalId> --rollout canary --recipe-file <recipe.md> --probes <2-5 task node ids> --json
+ The recipe is the procedure every unit follows; the probes are the most representative units, covering every way the units differ. The probes run first, and the other tasks are released wave by wave only after the probes ran through without a person; a rejection revises the recipe and re-probes. Tasks that differ only in names, files or details are one recipe; tasks whose steps differ are not, so start those without --rollout.
+4. Then end the run with one or two sentences in the user's language: the goal is running, and what runs first.
If the request instead asks to attach an existing goal to this conversation (it names a goal id like goal_xxx, or a /goal/goal_xxx link, to continue, bind or supervise here), do not create a new goal. Bind that one:
lh goal bind-topic <goalId> --json
-Add --force only when the user explicitly asks to move a goal that is already bound to another conversation; otherwise report the refusal and stop. If the output contains a turnToken, this run is a planning turn: plan from the goal graph it printed and submit with lh goal plan as in step 3, then end as in step 4. Without a turnToken, tasks are already in flight: do not plan, and end with one or two sentences saying the goal is now supervised from this conversation.
+Add --force only when the user explicitly asks to move a goal that is already bound to another conversation; otherwise report the refusal and stop. If the output contains a turnToken, this run is a planning turn: plan from the goal graph it printed, write a JSON plan file and submit it once with lh goal plan <goalId> --token <turnToken> --file <path> --json, using {"action":"tasks","reason":"evidence-based rationale","tasks":[{"title":"specific task","description":"self-contained contract: inputs, output and acceptance"}]}, then end as in step 4. Without a turnToken, tasks are already in flight: do not plan, and end with one or two sentences saying the goal is now supervised from this conversation.
Do not execute, preview or self-check the tasks, mark them complete, change budgets, or claim the goal is achieved. Later planning turns continue in this conversation once tasks deliver.`;
diff --git a/packages/const/src/goal.ts b/packages/const/src/goal.ts
index aad79a18198..70da58fc0ba 100644
--- a/packages/const/src/goal.ts
+++ b/packages/const/src/goal.ts
@@ -7,6 +7,8 @@
* including human review (`review`) and the terminal `achieved` outcome.
*/
export const goalStatuses = [
+ // Arranged but not started: the coordinator leaves it alone until `start`.
+ 'draft',
'planning',
'running',
'verifying',
diff --git a/packages/database/src/models/goalGraph.ts b/packages/database/src/models/goalGraph.ts
index 7cc82fa4626..8e2ef8c304f 100644
--- a/packages/database/src/models/goalGraph.ts
+++ b/packages/database/src/models/goalGraph.ts
@@ -713,6 +713,41 @@ export class GoalGraphModel {
return edge;
});
+ /**
+ * Take nodes back off a draft Goal's graph, with every edge touching them.
+ *
+ * Only a `draft` can lose nodes, and only ones never bound to a Task: nothing
+ * has run, so no history goes with them. A started Goal retires nodes instead.
+ */
+ removeDraftNodes = async (goalId: string, nodeIds: string[], reason: string) =>
+ this.db.transaction(async (tx) => {
+ const goal = await this.ownedGoal(goalId, tx);
+ if (!goal) return 0;
+ if (goal.status !== 'draft') throw new Error('Only a draft Goal can remove nodes');
+ if (!nodeIds.length) return 0;
+ const removed = await tx
+ .delete(goalNodes)
+ .where(
+ and(
+ eq(goalNodes.goalId, goalId),
+ inArray(goalNodes.id, nodeIds),
+ isNull(goalNodes.taskId),
+ ),
+ )
+ .returning({ id: goalNodes.id });
+ if (removed.length !== nodeIds.length)
+ throw new Error('Only unbound nodes of this Goal can be removed');
+ for (const { id } of removed) {
+ await this.appendEvent(tx, goalId, {
+ entityId: id,
+ entityType: 'node',
+ eventType: 'unlinked',
+ reason,
+ });
+ }
+ return removed.length;
+ });
+
bindTask = async (goalId: string, nodeId: string, taskId: string) =>
this.db.transaction(async (tx) => {
if (!(await this.ownedGoal(goalId, tx))) return undefined;
@@ -986,4 +1021,4 @@ export class GoalGraphModel {
await settleDecisionBriefs(tx, decision.id, 'canceled', reason);
return decision;
});
-}
\ No newline at end of file
+}
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index ab557db93fd..22c35a2c1a5 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -2157,6 +2157,7 @@ export default {
'goalList.roundProgress': 'Round {{current}}/{{total}}',
'goalList.status.achieved': 'Achieved',
'goalList.status.canceled': 'Canceled',
+ 'goalList.status.draft': 'Not started',
'goalList.status.error': 'Needs attention',
'goalList.status.paused': 'Paused',
'goalList.status.planning': 'Planning',
@@ -2170,6 +2171,7 @@ export default {
'goalTask.tasksDone': '{{passed}}/{{total}} tasks done',
'goalTask.status.achieved': 'Achieved',
'goalTask.status.canceled': 'Canceled',
+ 'goalTask.status.draft': 'Not started',
'goalTask.status.error': 'Needs attention',
'goalTask.status.paused': 'Paused',
'goalTask.status.planning': 'Planning',
@@ -2718,6 +2720,9 @@ export default {
'goalProcess.pause': 'Pause',
'goalProcess.resume': 'Resume',
'goalProcess.paused': 'Paused — no new work will start',
+ 'goalProcess.draft':
+ 'Not started — nothing runs until you start it. Check the tasks below first.',
+ 'goalProcess.start': 'Start',
'goalPage.allGoals': 'All goals',
'goalPage.activeGoals': 'Open goals',
'goalPage.description':
diff --git a/packages/prompts/src/chains/goalManager.test.ts b/packages/prompts/src/chains/goalManager.test.ts
index ad70cddf016..50b6998f01f 100644
--- a/packages/prompts/src/chains/goalManager.test.ts
+++ b/packages/prompts/src/chains/goalManager.test.ts
@@ -28,7 +28,7 @@ describe('buildGoalManagerPrompt', () => {
'keeps supervision language tied to the goal rather than the English control prompt: %s',
(requirement) => {
const prompt = buildGoalManagerPrompt({ ...base, requirement });
- expect(GOAL_MANAGER_PROMPT_VERSION).toBe('v8');
+ expect(GOAL_MANAGER_PROMPT_VERSION).toBe('v9');
expect(cdataOf(prompt, 'requirement')).toBe(requirement);
expect(prompt).toContain('Use the language of the Goal requirement');
expect(prompt).toContain(
@@ -43,6 +43,25 @@ describe('buildGoalManagerPrompt', () => {
},
);
+ /**
+ * Regression: a main Agent planning one recipe over many units only knew the
+ * flat tasks schema, so it seeded every unit at once and the batch rollout
+ * (probes, gate, waves) never ran for an agent-planned Goal.
+ */
+ it('teaches when to declare a batch and the rollout schema to declare it with', () => {
+ const prompt = buildGoalManagerPrompt(base);
+ expect(prompt).toContain('Batch (one repeated mould)');
+ expect(prompt).toContain('"tasks" become 2-5 probes');
+ const tasksSchemas = prompt
+ .split('\n')
+ .filter((line) => line.startsWith('{"action":"tasks"'))
+ .map((line) => JSON.parse(line));
+ expect(tasksSchemas.find((schema) => schema.rollout)?.rollout).toMatchObject({
+ recipe: expect.any(String),
+ units: expect.any(Array),
+ });
+ });
+
/**
* Regression: a takeover turn has to know what it is taking over. Without the
* problem the coordinator hands over, the main Agent reads an ordinary planning
@@ -120,7 +139,7 @@ describe('buildGoalManagerPrompt', () => {
});
expect(prompt.split('\n')[0]).toBe(
- '<goalTurn goal="goal_1" maxTurns="12" trigger="settled" turn="3" version="v8">',
+ '<goalTurn goal="goal_1" maxTurns="12" trigger="settled" turn="3" version="v9">',
);
expect(prompt.endsWith('</goalTurn>')).toBe(true);
// CommonMark ends an HTML block at a blank line; the client needs one block.
diff --git a/packages/prompts/src/chains/goalManager.ts b/packages/prompts/src/chains/goalManager.ts
index c6a41b20827..fa70fe659d2 100644
--- a/packages/prompts/src/chains/goalManager.ts
+++ b/packages/prompts/src/chains/goalManager.ts
@@ -12,8 +12,10 @@ import { GOAL_TURN_TAG } from '@lobechat/const';
* wall of identical text every turn.
* v8 lets an escalation carry an `ask` — the owner's question with concrete
* answers (and, on a takeover, what each answer does to the blocked Task).
+ * v9 teaches the batch: a tasks plan may declare `rollout`, so one recipe over
+ * many units runs a few probes first and the rest wave by wave behind a gate.
*/
-export const GOAL_MANAGER_PROMPT_VERSION = 'v8';
+export const GOAL_MANAGER_PROMPT_VERSION = 'v9';
export interface GoalManagerFeedbackNote {
/** `user`, or `agent <id>` for an agent-written comment. */
@@ -146,6 +148,13 @@ const feedback = (note: GoalManagerFeedbackNote, isNew: boolean) => {
const takeoverRules =
'Takeover: without you this Goal stops on a person, so decide what actually moves it: a corrective task that replaces the stuck work, independent verification when the evidence already warrants it, a diagnosed retry (only a transport failure is retryable; anything else will be refused), or — when the block genuinely needs a human — escalate with the specific question they have to answer. Two limits are enforced, so do not spend the turn on them: a FAILED Goal acceptance can only be escalated, not replaced by new work; and stuck work that something else depends on cannot be retired, so escalate that too.';
+/**
+ * When to declare a batch, and how. The judgement is the planning agent's; the
+ * server only checks the declaration is well formed.
+ */
+export const GOAL_BATCH_PLANNING_RULE =
+ 'Batch (one repeated mould): when the remaining work applies one recipe to many units — migrate N stores to one mechanism, give N resources the same caching, update N callers — and the first units will likely need a person (unsettled conventions, review, acceptance), do not plan every unit as a task. Add "rollout" to the tasks plan instead: "tasks" become 2-5 probes, the most representative units covering every variant, each with a full brief; "rollout.recipe" is the one procedure every unit follows; "rollout.units" lists every other unit in delivery order, as a title or as {"title","description"} when the unit has its own pointers; "rollout.variants" names the axes the units differ along, and the gate holds until the probes cover each value. The probes run first; the rest are released wave by wave only after every probe ran through without a person, and any rejection revises the recipe and starts a new probe round. Units that differ only in names, files or details are still one mould; work whose steps differ from task to task is not, so plan it as ordinary tasks. Never declare a batch on a Goal whose rollout is off. While a batch is in flight no planning turn starts; the next one comes after its roster is delivered.';
+
const contract = (input: GoalManagerPromptInput) =>
[
`You are the sole planning agent for Goal ${input.goalId}. Use the available shell and lh CLI, not a supervisor tool set.`,
@@ -158,9 +167,11 @@ const contract = (input: GoalManagerPromptInput) =>
`3. Write a JSON plan file and run lh goal plan ${input.goalId} --token ${input.token} --file <path> --json. The current operation ID is provided by LOBEHUB_OPERATION_ID.`,
'4. Submit one atomic plan, then exit. If submission rejects stale input or changed feedback, exit without repeatedly retrying this token; the next bounded turn receives fresh state. Do not start a poll loop or directly invoke task run/agent run for graph work: the server records and dispatches those runs under Goal budgets. Never lower the original requirement to produce a pass.',
'Give every planned task a dependsOn list naming the work it builds on: task node IDs from lh goal show for earlier rounds, or 0-based indexes of earlier tasks in the same plan. Omit it only for work that is genuinely independent — the Goal graph is laid out from these links, so a later round without them looks unrelated to the evidence it uses. Never depend on a retired or rejected node.',
+ GOAL_BATCH_PLANNING_RULE,
'When useful work must wait for time or external evidence, submit wait and exit; never sleep or poll. until is a future UTC ISO instant and a fallback check even if the optional event is lost. Events match type, key and current turn token; producers deliver using lh goal wake. A wake asks you to reconsider evidence, never proves success. Measured shortfalls are feedback: plan useful work or a bounded wait; do not lower the original target.',
'Choose exactly one schema:',
'{"action":"tasks","reason":"evidence-based rationale","tasks":[{"title":"specific task","description":"self-contained contract, inputs, output and acceptance","dependsOn":["task node ID from an earlier round", 0]}]}',
+ '{"action":"tasks","reason":"why these units are one mould","tasks":[{"title":"probe unit","description":"full brief for this unit"}],"rollout":{"recipe":"the procedure every unit follows","units":["unit title",{"title":"unit title","description":"this unit\'s own pointers"}],"variants":[{"axis":"what the units differ in","values":["value a","value b"]}]}}',
'{"action":"wait","reason":"why evidence must arrive later","until":"future UTC ISO instant","event":{"type":"external.result","key":"correlated job ID"}}',
'{"action":"verify","reason":"why the existing evidence warrants independent Goal verification"}',
'{"action":"retry","taskId":"failed Task ID","failedOperationId":"latest confirmed failure ID","reason":"diagnosis and checkpoint-aware recovery instruction"}',
diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.ts
index 9d1256a290a..fef151dc387 100644
--- a/packages/types/src/goal.ts
+++ b/packages/types/src/goal.ts
@@ -16,7 +16,15 @@ import type { WorkType } from './work';
* there), mirroring the AcceptanceStatus convention.
*/
export type GoalStatus =
- 'planning' | 'running' | 'verifying' | 'review' | 'paused' | 'achieved' | 'failed' | 'canceled';
+ | 'draft'
+ | 'planning'
+ | 'running'
+ | 'verifying'
+ | 'review'
+ | 'paused'
+ | 'achieved'
+ | 'failed'
+ | 'canceled';
/**
* The execution carrier a goal is optionally bound to. Goals are standalone
@@ -463,6 +471,12 @@ export interface GoalRolloutPolicy {
variantAxes?: GoalRolloutVariantAxis[];
};
trigger: GoalRolloutTrigger;
+ /**
+ * Notes for individual roster units, keyed by unit title. A main Agent that
+ * declares the batch can give each unit its own pointers (files, edge cases);
+ * a released unit's brief is the recipe plus its note.
+ */
+ unitBriefs?: Record<string, string>;
/**
* Roster of every homogeneous unit in the goal, probes included and in
* delivery order. Probes are the first, fully-briefed units; the coordinator
diff --git a/src/features/AgentGoals/GoalDetailActions.tsx b/src/features/AgentGoals/GoalDetailActions.tsx
index 0f548c1500b..2bd51e20345 100644
--- a/src/features/AgentGoals/GoalDetailActions.tsx
+++ b/src/features/AgentGoals/GoalDetailActions.tsx
@@ -44,6 +44,7 @@ const GoalDetailActions = memo<GoalDetailActionsProps>(({ agentId, goalId, proje
const canClose = useResourceManageable(creatorUserId);
const pauseGoal = useGoalStore((s) => s.pauseGoal);
const resumeGoal = useGoalStore((s) => s.resumeGoal);
+ const startGoal = useGoalStore((s) => s.startGoal);
const closeGoal = useGoalStore((s) => s.closeGoal);
const current = toManualStatus(status);
@@ -51,7 +52,7 @@ const GoalDetailActions = memo<GoalDetailActionsProps>(({ agentId, goalId, proje
const changeStatus = useCallback(
(next: ManualGoalStatus) => {
if (next === current) return;
- if (next === 'running') return void resumeGoal(goalId);
+ if (next === 'running') return void (status === 'draft' ? startGoal : resumeGoal)(goalId);
if (next === 'paused') return void pauseGoal(goalId);
// Closing interrupts live runs, so it asks first.
confirmModal({
@@ -63,7 +64,7 @@ const GoalDetailActions = memo<GoalDetailActionsProps>(({ agentId, goalId, proje
title: t(`goalDetail.closeConfirm.${next}.title`),
});
},
- [closeGoal, current, goalId, pauseGoal, resumeGoal, t],
+ [closeGoal, current, goalId, pauseGoal, resumeGoal, startGoal, status, t],
);
const items = useMemo<DropdownItem[]>(
diff --git a/src/features/AgentGoals/GoalDetailPage.tsx b/src/features/AgentGoals/GoalDetailPage.tsx
index 74c20f45db7..f97cfb8dd86 100644
--- a/src/features/AgentGoals/GoalDetailPage.tsx
+++ b/src/features/AgentGoals/GoalDetailPage.tsx
@@ -1,7 +1,7 @@
'use client';
import { Flexbox } from '@lobehub/ui';
-import { Button, Text } from '@lobehub/ui/base-ui';
+import { Button, Text, toast } from '@lobehub/ui/base-ui';
import { createStaticStyles } from 'antd-style';
import { PauseIcon, PlayIcon } from 'lucide-react';
import { memo, useEffect, useRef, useState } from 'react';
@@ -67,6 +67,7 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {
const snapshot = useGoalStore(goalSelectors.goalGraph(goalId));
const pauseGoal = useGoalStore((s) => s.pauseGoal);
const resumeGoal = useGoalStore((s) => s.resumeGoal);
+ const startGoal = useGoalStore((s) => s.startGoal);
const buildAgentPath = useAgentRoutePath(agentId ?? '');
@@ -81,6 +82,7 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {
// While the exploration map runs fullscreen its overlay carries the portal
// panel; ours unmounts so exactly one PortalContent is alive at a time.
const [graphFullscreen, setGraphFullscreen] = useState(false);
+ const [starting, setStarting] = useState(false);
// Same per-view width grammar as the conversation portal, but remembered
// under the 'goal' scope: resizing here never affects the chat surface.
@@ -237,6 +239,34 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {
{/* Pause/resume above the requirement document — its reviewed
home. The status glyph keeps the "running" animation; this
button is only the control. */}
+ {/* A draft is still being arranged: nothing has been dispatched,
+ and starting it is the one explicit move into running. */}
+ {goal.status === 'draft' && (
+ <Flexbox horizontal align={'center'} gap={10} paddingBlock={'8px 0'}>
+ {canEdit && (
+ <Button
+ icon={PlayIcon}
+ loading={starting}
+ type={'primary'}
+ onClick={async () => {
+ setStarting(true);
+ try {
+ await startGoal(goal.id);
+ } catch (error) {
+ toast.error((error as Error).message);
+ } finally {
+ setStarting(false);
+ }
+ }}
+ >
+ {t('goalProcess.start')}
+ </Button>
+ )}
+ <Text fontSize={12} type={'secondary'}>
+ {t('goalProcess.draft')}
+ </Text>
+ </Flexbox>
+ )}
{canPause && (
<Flexbox horizontal align={'center'} gap={10} paddingBlock={'8px 0'}>
<Button
diff --git a/src/features/AgentGoals/goalPresentation.ts b/src/features/AgentGoals/goalPresentation.ts
index 5e432cfa19d..530eb73e139 100644
--- a/src/features/AgentGoals/goalPresentation.ts
+++ b/src/features/AgentGoals/goalPresentation.ts
@@ -6,6 +6,7 @@ import { formatDuration } from '@lobechat/utils';
const goalStatusKeyMap = {
achieved: 'goalList.status.achieved',
canceled: 'goalList.status.canceled',
+ draft: 'goalList.status.draft',
failed: 'goalList.status.error',
paused: 'goalList.status.paused',
planning: 'goalList.status.planning',
@@ -38,6 +39,7 @@ export const goalStatusToTaskStatus = (goalStatus: GoalStatus): TaskStatus => {
case 'review': {
return 'paused';
}
+ case 'draft':
case 'planning': {
return 'backlog';
}
diff --git a/src/features/AgentGoals/goalStatusMenu.test.ts b/src/features/AgentGoals/goalStatusMenu.test.ts
index 7cfc6c33163..8fa77c71133 100644
--- a/src/features/AgentGoals/goalStatusMenu.test.ts
+++ b/src/features/AgentGoals/goalStatusMenu.test.ts
@@ -26,4 +26,11 @@ describe('goal status menu', () => {
expect(toManualStatus('review')).toBe('running');
expect(toManualStatus('failed')).toBeUndefined();
});
+
+ it('offers only starting a draft goal, unchecked', () => {
+ expect(toManualStatus('draft')).toBeUndefined();
+ expect(isStatusChoiceDisabled('running', 'draft', true)).toBe(false);
+ expect(isStatusChoiceDisabled('paused', 'draft', true)).toBe(true);
+ expect(isStatusChoiceDisabled('canceled', 'draft', true)).toBe(true);
+ });
});
diff --git a/src/features/AgentGoals/goalStatusMenu.ts b/src/features/AgentGoals/goalStatusMenu.ts
index 627f50f4364..f374bbf6278 100644
--- a/src/features/AgentGoals/goalStatusMenu.ts
+++ b/src/features/AgentGoals/goalStatusMenu.ts
@@ -11,6 +11,8 @@ export const MANUAL_STATUSES: ManualGoalStatus[] = ['running', 'paused', 'achiev
const PAUSABLE_STATUSES = new Set(['paused', 'planning', 'running', 'verifying']);
export const toManualStatus = (status: string | undefined): ManualGoalStatus | undefined => {
+ // A draft is in none of the manual states yet; picking "running" starts it.
+ if (status === 'draft') return;
if (status === 'paused' || status === 'achieved' || status === 'canceled') return status;
if (status === 'failed') return;
return status ? 'running' : undefined;
@@ -28,6 +30,8 @@ export const isStatusChoiceDisabled = (
canClose: boolean,
): boolean => {
if (next === 'paused') return !PAUSABLE_STATUSES.has(status ?? '');
+ // Closing a draft would end a goal that never ran; delete it instead.
+ if (status === 'draft' && next !== 'running') return true;
if (next === 'achieved' || next === 'canceled') return !canClose;
return false;
};
diff --git a/src/features/Conversation/Messages/GoalTaskCard/goalCardModel.ts b/src/features/Conversation/Messages/GoalTaskCard/goalCardModel.ts
index c36f2e4b1c3..6b25f9679ad 100644
--- a/src/features/Conversation/Messages/GoalTaskCard/goalCardModel.ts
+++ b/src/features/Conversation/Messages/GoalTaskCard/goalCardModel.ts
@@ -84,6 +84,8 @@ const resolveStage = (
case 'verifying': {
return 'verifying';
}
+ // A draft is still being arranged, whatever tasks it already holds.
+ case 'draft':
case 'planning': {
return 'planning';
}
diff --git a/src/features/Conversation/Messages/GoalTaskCard/goalTaskProgress.test.ts b/src/features/Conversation/Messages/GoalTaskCard/goalTaskProgress.test.ts
index b2b294a6c69..2868c7e5575 100644
--- a/src/features/Conversation/Messages/GoalTaskCard/goalTaskProgress.test.ts
+++ b/src/features/Conversation/Messages/GoalTaskCard/goalTaskProgress.test.ts
@@ -26,6 +26,13 @@ describe('getGoalTaskProgress', () => {
);
});
+ it('reads a seeded draft as not started rather than executing', () => {
+ // A draft already holds its tasks, but none of them runs until it is started.
+ expect(getGoalTaskProgress({ criteriaCount: 2, status: 'draft', taskTotal: 4 }).phase).toBe(
+ 'draft',
+ );
+ });
+
it('lets a waiting decision gate outrank the goal status', () => {
// A goal keeps its `running` row while a gate is open; the card must still
// read as blocked on the user, not as work in progress.
diff --git a/src/features/Conversation/Messages/GoalTaskCard/goalTaskProgress.ts b/src/features/Conversation/Messages/GoalTaskCard/goalTaskProgress.ts
index a404b043615..174479bf150 100644
--- a/src/features/Conversation/Messages/GoalTaskCard/goalTaskProgress.ts
+++ b/src/features/Conversation/Messages/GoalTaskCard/goalTaskProgress.ts
@@ -3,6 +3,7 @@ import type { GoalStatus } from '@lobechat/const/goal';
export type GoalTaskPhase =
| 'achieved'
| 'canceled'
+ | 'draft'
| 'error'
| 'paused'
| 'planning'
@@ -24,6 +25,10 @@ interface GoalTaskProgressInput {
const resolvePhase = (status?: GoalStatus, pendingDecisions = 0, taskTotal = 0): GoalTaskPhase => {
if (pendingDecisions > 0) return 'waiting';
switch (status) {
+ // Arranged but not started: nothing runs until someone starts it.
+ case 'draft': {
+ return 'draft';
+ }
// A goal adopted from a conversation turns `running` the moment it is
// created, before its first plan lands any Task — both read as planning.
case 'planning': {
diff --git a/src/services/goal.ts b/src/services/goal.ts
index bf0f6125a8d..d6ce66683df 100644
--- a/src/services/goal.ts
+++ b/src/services/goal.ts
@@ -98,6 +98,9 @@ class GoalService {
resume = async (id: string) => lambdaClient.goal.resume.mutate({ id });
+ /** Launch a draft goal; nothing was dispatched before this. */
+ start = async (id: string) => lambdaClient.goal.start.mutate({ id });
+
/** Answer a goal's whole clarification round; the goal re-plans once with every answer. */
answerClarifications = async (params: {
answers: Array<{ decisionId: string; optionId: string; resolution?: string }>;
diff --git a/src/store/goal/action.ts b/src/store/goal/action.ts
index edd9945620f..46606ac5943 100644
--- a/src/store/goal/action.ts
+++ b/src/store/goal/action.ts
@@ -306,6 +306,11 @@ export class GoalActionImpl {
await this.refreshGoalGraph(goalId);
};
+ startGoal = async (goalId: string): Promise<void> => {
+ await goalService.start(goalId);
+ await this.refreshGoalGraph(goalId);
+ };
+
setGoalBudget = async (
goalId: string,
budget: {