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.

♻️ refactor(goal): plan simple goals in one pass, hand the rest to the main Agent (#20899)

Arvin Xu76495d1fd060
diff --git a/apps/server/src/services/goal/criteriaGenerator.test.ts b/apps/server/src/services/goal/criteriaGenerator.test.ts
index dc82402dc43..cd44f6dc6f8 100644
--- a/apps/server/src/services/goal/criteriaGenerator.test.ts
+++ b/apps/server/src/services/goal/criteriaGenerator.test.ts
@@ -68,16 +68,16 @@ describe('GoalCriteriaGeneratorService', () => {
expect.objectContaining({ schema: expect.objectContaining({ name: 'goal_decomposition' }) }),
expect.objectContaining({
tracing: {
- promptVersion: 'v8',
+ promptVersion: 'v9',
scenario: 'goal_decompose',
schemaName: 'goal_decomposition',
},
}),
);
generateObject.mockResolvedValueOnce({ ...draft, tasks: [{ title: 'Missing instruction' }] });
- await expect(
- service.decompose({ requirement: 'Upgrade office editing' }),
- ).resolves.toBeUndefined();
+ await expect(service.decompose({ requirement: 'Upgrade office editing' })).rejects.toThrow(
+ 'did not match the decomposition schema: tasks.0.instruction',
+ );
});
it('rejects criteria containing evidence values outside the supported enums', async () => {
diff --git a/apps/server/src/services/goal/criteriaGenerator.ts b/apps/server/src/services/goal/criteriaGenerator.ts
index fea3e3d54d2..b0fbddada65 100644
--- a/apps/server/src/services/goal/criteriaGenerator.ts
+++ b/apps/server/src/services/goal/criteriaGenerator.ts
@@ -72,6 +72,8 @@ export interface GoalPlanDraft {
const decompositionSchema = z.object({
/** Readings the plan relies on that the goal did not state. */
assumptions: z.array(z.string()).default([]),
+ /** Why one planning pass is not enough; the main Agent plans instead. */
+ escalate: z.string().nullish(),
problemStatement: z.string().min(1),
/**
* The planner's batch claim. Present only when it judged the goal to be one
@@ -186,14 +188,14 @@ export class GoalCriteriaGeneratorService {
/**
* Plan the opening exploration structure for a goal that has no tasks yet:
- * the core question plus 1–5 independent directions. Returns undefined on
- * any model/schema failure so the coordinator can fall back to a single
- * task seeded from the raw requirement instead of stalling the goal.
+ * the core question plus 1–5 independent directions. Throws on a model or
+ * schema failure; the coordinator then falls back to a single task seeded
+ * from the raw requirement and records why, instead of stalling the goal.
*/
async decompose(params: {
clarifications?: GoalClarificationAnswer[];
requirement: string;
- }): Promise<GoalDecompositionDraft | undefined> {
+ }): Promise<GoalDecompositionDraft> {
const modelConfig = await resolveGoalModelConfig(this.db, this.userId);
const ai = new AiGenerationService(this.db, this.userId, this.workspaceId);
const raw = await ai.generateObject(
@@ -216,7 +218,13 @@ export class GoalCriteriaGeneratorService {
const parsed = decompositionSchema.safeParse(raw);
if (!parsed.success) {
log('goal decomposition did not match schema: %O', parsed.error.flatten());
- return undefined;
+ // Thrown, not swallowed: the coordinator records why it fell back.
+ throw new Error(
+ `The planner's answer did not match the decomposition schema: ${parsed.error.issues
+ .slice(0, 3)
+ .map((issue) => `${issue.path.join('.') || '(root)'} ${issue.message}`)
+ .join('; ')}`,
+ );
}
return parsed.data;
}
diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.ts
index 206458ca178..d4b256a3b48 100644
--- a/apps/server/src/services/goal/index.test.ts
+++ b/apps/server/src/services/goal/index.test.ts
@@ -8,7 +8,7 @@ import {
} from '@lobechat/const/goal';
import type { ChatTopicMetadata } from '@lobechat/types';
import * as goalGraphUtils from '@lobechat/utils/goalGraph';
-import { eq, sql } from 'drizzle-orm';
+import { and, eq, sql } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getTestDB } from '@/database/core/getTestDB';
@@ -2087,6 +2087,95 @@ describe('GoalService', () => {
expect(after.nodes.filter((n) => n.kind === 'task')).toHaveLength(12);
});
+ /**
+ * Regression: a planner failure was swallowed whole — the goal quietly
+ * became one task built from the raw requirement, and nothing anywhere said
+ * the planner had failed or why.
+ */
+ it('records why the planner failed on the task it fell back to', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockRejectedValue({
+ error: { message: 'Insufficient Balance' },
+ errorType: 'InsufficientQuota',
+ });
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ requirement: '迁移 12 个 store', title: 'Migrate' });
+ await service.tick(graph.goal.id);
+
+ const task = (await service.graph(graph.goal.id)).nodes.find((n) => n.kind === 'task');
+ const [created] = await serverDB
+ .select()
+ .from(goalEvents)
+ .where(and(eq(goalEvents.entityId, task.id), eq(goalEvents.eventType, 'created')));
+ expect(created.reason).toBe(
+ 'Planner failed (InsufficientQuota: Insufficient Balance); no main Agent could take the goal; started from the raw requirement',
+ );
+ });
+
+ it('records why a batch claim was refused on the first task it planned instead', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ problemStatement: '把 8 个 store 迁移到 replica',
+ rollout: {
+ recipeOutline: '把 store 换成 replica 支撑的实现',
+ repeatable: true,
+ unitCount: 8,
+ units: Array.from({ length: 8 }, (_, i) => `Unit ${i + 1}`),
+ variants: [],
+ },
+ tasks: Array.from({ length: 3 }, (_, i) => ({
+ dependsOn: [],
+ instruction: `把 src/store/store${i + 1}.ts 换成 replica 实现`,
+ title: `Unit ${i + 1}`,
+ })),
+ });
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ title: 'Migrate 8 stores' });
+ await service.tick(graph.goal.id);
+
+ const tasks = (await service.graph(graph.goal.id)).nodes.filter((n) => n.kind === 'task');
+ const reasons = await serverDB
+ .select({ entityId: goalEvents.entityId, reason: goalEvents.reason })
+ .from(goalEvents)
+ .where(eq(goalEvents.eventType, 'created'));
+ const reasonOf = (id: string) => reasons.find((event) => event.entityId === id)?.reason;
+ expect(reasonOf(tasks[0].id)).toBe(
+ 'Batch claim refused (unitCount 8 is below the threshold 10); planned unit by unit',
+ );
+ // Said once, not on every task.
+ expect(reasonOf(tasks[1].id)).toBeNull();
+ });
+
+ /**
+ * Regression: a model titles its probes around the unit — "迁移 device store
+ * (探针)" for unit `device` — and the roster de-duplicated on exact titles,
+ * so every probed unit was queued again and would run twice.
+ */
+ it('does not queue a probed unit again when the probe title wraps its name', async () => {
+ const units = Array.from({ length: 12 }, (_, i) => `store${i + 1}`);
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ problemStatement: '把 12 个同构的 store 迁移到 replica',
+ rollout: {
+ recipeOutline: '把 store 换成 replica 支撑的实现',
+ repeatable: true,
+ unitCount: 12,
+ units,
+ variants: [],
+ },
+ tasks: units.slice(0, 3).map((unit) => ({
+ dependsOn: [],
+ instruction: `把 src/store/${unit}.ts 换成 replica 实现,并补冷启动回归测试`,
+ title: `迁移 ${unit} store(探针)`,
+ })),
+ });
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({ title: 'Migrate 12 stores' });
+ await service.tick(graph.goal.id);
+
+ const roster = (await service.graph(graph.goal.id)).goal.config!.rolloutState!.unitTitles!;
+ expect(roster).toHaveLength(12);
+ expect(roster.slice(0, 3)).toEqual(units.slice(0, 3).map((u) => `迁移 ${u} store(探针)`));
+ expect(roster.slice(3)).toEqual(units.slice(3));
+ });
+
it('materializes a fallback roster above the batch cap without trimming it', async () => {
const units = Array.from({ length: 64 }, (_, i) => `Unit ${i + 1}`);
vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index ef22ed5292c..ea7fab4db0c 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -1,3 +1,5 @@
+import { randomUUID } from 'node:crypto';
+
import type { GoalAdvanceEffect, GoalMetricCriteriaState } from '@lobechat/agent-tracing';
import { buildGoalRequirement } from '@lobechat/builtin-tool-goal';
import {
@@ -32,6 +34,7 @@ import type {
GoalNodeKind,
GoalNodeStatus,
GoalPauseReason,
+ GoalRolloutPolicy,
GoalRolloutState,
GoalStatus,
GoalTickResult,
@@ -154,6 +157,45 @@ 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');
+/**
+ * Why the system planner's one pass should go to the main Agent, or undefined
+ * when its plan can run: the pass failed, the planner said it was not enough,
+ * or it claimed a batch it could not lay out. A goal that is simply not a batch
+ * is not a reason — the ordinary plan is right for it.
+ */
+const planningHandoffReason = (
+ plan: GoalDecompositionDraft | undefined,
+ plannerFailure: string | undefined,
+ rollout: GoalRolloutPolicy | undefined,
+ maxUnits: number,
+): string | undefined => {
+ if (!plan) return `Planner failed (${plannerFailure ?? 'no answer'})`;
+ const asked = plan.escalate?.trim();
+ if (asked) return `Planner asked for the main Agent: ${asked}`;
+ if (!plan.rollout || rollout?.trigger === 'off') return undefined;
+ const verdict = evaluateHomogeneity(
+ plan.rollout,
+ plan.tasks.map((draft) => ({ instruction: draft.instruction, title: draft.title })),
+ { maxUnits, minUnits: rollout?.minHomogeneousUnits },
+ );
+ return verdict.malformed
+ ? `Batch claim could not be laid out (${verdict.reasons.join('; ')})`
+ : undefined;
+};
+
+/**
+ * One line for why the planner failed, for the audit trail. Model runtime
+ * errors arrive as plain objects (`{ errorType, error }`), not `Error`s.
+ */
+const describePlannerFailure = (error: unknown): string => {
+ const runtime = error as { error?: { message?: string }; errorType?: string } | undefined;
+ const text =
+ error instanceof Error
+ ? error.message
+ : [runtime?.errorType, runtime?.error?.message].filter(Boolean).join(': ') || String(error);
+ return text.length > 300 ? `${text.slice(0, 299)}…` : text;
+};
+
const draftNotStarted = (goalId: string) =>
new TRPCError({
code: 'CONFLICT',
@@ -3672,9 +3714,19 @@ export class GoalService {
const generator = new GoalCriteriaGeneratorService(this.db, this.userId, this.workspaceId);
const clarifications = collectClarificationAnswers(graph);
+ // A failed plan still starts the goal from the raw requirement, but says
+ // so: the server log and the first task's audit event carry the cause.
+ let plannerFailure: string | undefined;
const plan = await generator
.decompose({ clarifications, requirement })
- .catch(() => undefined);
+ .catch((error: unknown) => {
+ plannerFailure = describePlannerFailure(error);
+ console.error(
+ `[GoalService] goal ${goalId} decomposition failed; starting from the raw requirement:`,
+ error,
+ );
+ return undefined;
+ });
// A graph without a problem node has nowhere to hang a question, so its
// questions are planned around as assumptions like a re-plan's would be.
const understanding = plan
@@ -3685,6 +3737,27 @@ export class GoalService {
)
: undefined;
+ // The system planner does one simple pass. When that pass failed, said it
+ // was not enough, or claimed a batch it could not lay out, the main Agent
+ // — which can inspect the workspace — plans the goal instead. Without one
+ // (no goal agent, or no turn could start) the pass below still runs.
+ const handoff = planningHandoffReason(
+ plan,
+ plannerFailure,
+ graph.goal.config?.rollout,
+ MAX_ROLLOUT_ROSTER,
+ );
+ if (handoff && graph.goal.agentId) {
+ const handed = await this.handPlanningToMainAgent(graph, handoff);
+ if (handed) {
+ effects.push({
+ detail: `planning handed to the main Agent: ${handoff}`,
+ type: 'goal_status',
+ });
+ return handed;
+ }
+ }
+
const draftTasks: GoalDecompositionDraft['tasks'] = plan?.tasks ?? [
{
// The user's answers are authoritative; a planner failure after the
@@ -3805,7 +3878,7 @@ export class GoalService {
minUnits: existingRollout?.minHomogeneousUnits,
},
)
- : { batch: false, reasons: [] as string[] };
+ : { batch: false, malformed: false, reasons: [] as string[] };
log(
'decomposition rollout: trigger=%s claim=%o tasks=%d verdict=%o',
@@ -3816,7 +3889,13 @@ export class GoalService {
);
if (rolloutClaim && rolloutEnabled && verdict.batch && currentProblem) {
- const roster = normalizeRolloutRoster(rolloutClaim.units, draftTasks, draftTasks.length);
+ const roster = normalizeRolloutRoster(
+ rolloutClaim.units,
+ draftTasks,
+ draftTasks.length,
+ undefined,
+ { matchUnitInProbeTitle: true },
+ );
const canarySize =
rolloutTrigger === 'full'
? roster.length
@@ -3873,6 +3952,7 @@ export class GoalService {
draftTasks,
draftTasks.length,
Number.POSITIVE_INFINITY,
+ { matchUnitInProbeTitle: true },
).map((title, index) => {
const draft = draftTasks[index];
return {
@@ -3886,6 +3966,19 @@ export class GoalService {
})
: draftTasks;
+ // Why this goal was planned unit by unit, on the first task's `created`
+ // event: a planner failure, or a batch claim the checks refused.
+ // A hand-over that did not happen (no main Agent could take the goal)
+ // says so too.
+ const unhanded = handoff ? '; no main Agent could take the goal' : '';
+ let fallbackReason = !plan
+ ? `Planner failed (${plannerFailure ?? 'no answer'})${unhanded}; started from the raw requirement`
+ : plan.escalate?.trim()
+ ? `Planner asked for the main Agent (${plan.escalate.trim()})${unhanded}; ran its own plan`
+ : rolloutClaim && rolloutEnabled && !verdict.batch
+ ? `Batch claim refused (${verdict.reasons.join('; ')}); planned unit by unit`
+ : undefined;
+
const createdIds: string[] = [];
for (const draft of plannedUnits) {
// An experiment is a container for a candidate answer, not the
@@ -3909,6 +4002,7 @@ export class GoalService {
scopeId: experiment?.id,
description: draft.instruction,
kind: 'task',
+ reason: fallbackReason,
title: draft.title,
});
if (!node) throw new Error('Failed to create a planned task');
@@ -3916,6 +4010,7 @@ export class GoalService {
await writer.createEdge(goalId, currentProblem.id, node.id, 'decomposes');
createdIds.push(node.id);
committedEffects.push({ nodeId: node.id, type: 'created_node', detail: draft.title });
+ fallbackReason = undefined;
}
// The planner's `dependsOn` indices become `depends_on` edges, drawn
@@ -3968,6 +4063,28 @@ export class GoalService {
}
};
+ /**
+ * Give the goal's planning to its main Agent, opening one for a goal that had
+ * none. Returns undefined when no turn could start (no eligible agent, turn or
+ * budget limits); a policy opened here is then removed again — only that one,
+ * by its token — so the goal keeps the system planner and does not gain an
+ * uninvited planner later, while a policy a person set meanwhile stays.
+ */
+ private handPlanningToMainAgent = async (graph: GoalGraphSnapshot, reason: string) => {
+ const goalId = graph.goal.id;
+ const token = randomUUID();
+ await this.goalModel.openManagerPolicy(goalId, { openedForHandoff: token });
+ const result = await new GoalManagerService(this.db, this.userId, this.workspaceId)
+ .planInstead(await this.requireGraph(goalId), reason)
+ .catch((error: unknown) => {
+ console.error(`[GoalService] goal ${goalId} could not hand planning over:`, error);
+ return null;
+ });
+ if (result) return result;
+ await this.goalModel.closeHandoffManagerPolicy(goalId, token);
+ return undefined;
+ };
+
/**
* Judge a repeated batch's gate, but only once the wave it released has fully
* settled. Returns undefined when there is nothing to judge: no batch, a batch
diff --git a/apps/server/src/services/goal/manager.test.ts b/apps/server/src/services/goal/manager.test.ts
index 128091bb8f2..267a071ba9b 100644
--- a/apps/server/src/services/goal/manager.test.ts
+++ b/apps/server/src/services/goal/manager.test.ts
@@ -34,6 +34,7 @@ import { AiAgentService } from '@/server/services/aiAgent';
import { TopicStartReservationError } from '@/server/services/aiAgent/topicStartReservation';
import { deviceGateway } from '../deviceGateway';
+import { GoalCriteriaGeneratorService } from './criteriaGenerator';
import { GoalService } from './index';
import { decideFailedTurn, GoalManagerService, MAX_FAILED_MANAGER_TURNS } from './manager';
import * as scheduler from './scheduler';
@@ -2924,3 +2925,230 @@ describe('decideFailedTurn', () => {
).toMatchObject({ action: 'retry', charged: true });
});
});
+
+/**
+ * The system planner does one simple pass. When that pass fails, says it is not
+ * enough, or claims a batch it cannot lay out, the main Agent plans instead —
+ * rather than the goal starting from one raw-requirement task or a flat fan-out.
+ */
+describe('planning the system planner hands to the main Agent', () => {
+ const units = Array.from({ length: 12 }, (_, i) => `store${i + 1}`);
+ const simplePlan = {
+ problemStatement: '把 12 个 store 迁移到 replica',
+ tasks: [{ dependsOn: [], instruction: '迁移 store1', title: 'store1' }],
+ };
+ const unmanagedGoal = async () => {
+ const graph = await service().create({ createdByAgentId: agentId, title: 'Migrate stores' });
+ await db.update(goals).set({ config: {} }).where(eq(goals.id, graph.goal.id));
+ return graph.goal.id;
+ };
+ const after = async (id: string) => {
+ const goal = (await model().findById(id))!;
+ const tasks = (await service().graph(id)).nodes.filter((n) => n.kind === 'task');
+ return { config: goal.config!, tasks };
+ };
+
+ it('hands a goal the planner says needs more than one pass to the main Agent', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ ...simplePlan,
+ escalate: '要先读仓库才能确定有哪些 store',
+ });
+ const id = await unmanagedGoal();
+
+ expect((await service().tick(id)).outcome).toBe('waiting_external');
+
+ const { config, tasks } = await after(id);
+ expect(config.manager).toEqual({ openedForHandoff: expect.any(String) });
+ expect(config.managerState?.token).toBeTruthy();
+ // Nothing from the planner's own pass ran.
+ expect(tasks).toHaveLength(0);
+ const prompt = vi.mocked(AiAgentService.prototype.execAgent).mock.calls.at(-1)![0].prompt;
+ expect(prompt).toContain('Planner asked for the main Agent: 要先读仓库才能确定有哪些 store');
+ });
+
+ /**
+ * Regression: the hand-over started the turn while the system planner still
+ * held its planning lease and released it right after, so the turn's input
+ * snapshot never matched again and every plan the Agent submitted was
+ * refused as stale.
+ */
+ it('accepts the plan the main Agent submits after a hand-over', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ ...simplePlan,
+ escalate: '要先读仓库才能确定有哪些 store',
+ });
+ const id = await unmanagedGoal();
+ await service().tick(id);
+ const state = (await model().findById(id))!.config!.managerState!;
+ const op = await ops().findByTopicSourceMessage(
+ state.topicId,
+ `msg_goal_manager_${state.token}`,
+ );
+
+ await manager().submit(id, state.token, op!.id, taskPlan);
+
+ expect((await after(id)).tasks.map((n) => n.title)).toEqual(['Audit']);
+ });
+
+ it('hands a failed planning pass to the main Agent', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockRejectedValue(
+ new Error('model timed out'),
+ );
+ const id = await unmanagedGoal();
+
+ expect((await service().tick(id)).outcome).toBe('waiting_external');
+
+ const { config, tasks } = await after(id);
+ expect(config.managerState?.token).toBeTruthy();
+ expect(tasks).toHaveLength(0);
+ const prompt = vi.mocked(AiAgentService.prototype.execAgent).mock.calls.at(-1)![0].prompt;
+ expect(prompt).toContain('Planner failed (model timed out)');
+ });
+
+ it('hands a batch claim it could not lay out to the main Agent', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ ...simplePlan,
+ // Twelve units claimed, three listed: the waves would drop the other nine.
+ rollout: {
+ recipeOutline: '定义 replica 并删掉 SWR 持久化',
+ repeatable: true,
+ unitCount: 12,
+ units: units.slice(0, 3),
+ variants: [],
+ },
+ tasks: units.slice(0, 2).map((unit) => ({ dependsOn: [], instruction: unit, title: unit })),
+ });
+ const id = await unmanagedGoal();
+
+ await service().tick(id);
+
+ const { config, tasks } = await after(id);
+ expect(config.managerState?.token).toBeTruthy();
+ expect(tasks).toHaveLength(0);
+ const prompt = vi.mocked(AiAgentService.prototype.execAgent).mock.calls.at(-1)![0].prompt;
+ expect(prompt).toContain('Batch claim could not be laid out (roster lists 3 of the 12');
+ });
+
+ it('keeps a goal that is simply not a batch on the system planner', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ ...simplePlan,
+ rollout: {
+ recipeOutline: '定义 replica',
+ repeatable: true,
+ unitCount: 3,
+ units: units.slice(0, 3),
+ variants: [],
+ },
+ tasks: units.slice(0, 2).map((unit) => ({ dependsOn: [], instruction: unit, title: unit })),
+ });
+ const id = await unmanagedGoal();
+
+ await service().tick(id);
+
+ const { config, tasks } = await after(id);
+ expect(config.manager).toBeUndefined();
+ expect(tasks.map((n) => n.title)).toEqual(units.slice(0, 3));
+ expect(AiAgentService.prototype.execAgent).not.toHaveBeenCalled();
+ });
+
+ /**
+ * Regression: a hand-over that could not start removed `config.manager`
+ * unconditionally, so a policy a person set while it ran was deleted too.
+ */
+ it('keeps a main Agent policy a person set while the hand-over ran', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ ...simplePlan,
+ escalate: '要先读仓库',
+ });
+ vi.spyOn(GoalManagerService.prototype, 'planInstead').mockImplementation(async (graph) => {
+ await db
+ .update(goals)
+ .set({ config: sql`jsonb_set(${goals.config}, '{manager}', '{"maxTurns": 7}'::jsonb)` })
+ .where(eq(goals.id, graph.goal.id));
+ return null;
+ });
+ const id = await unmanagedGoal();
+
+ await service().tick(id);
+
+ expect((await after(id)).config.manager).toEqual({ maxTurns: 7 });
+ });
+
+ /**
+ * Regression: a goal whose main Agent had used its turns took the uninvited
+ * limit branch on hand-over, which paused the goal and dropped the system
+ * planner's own plan, though a hand-over that cannot start promises that plan.
+ */
+ it('runs its own plan instead of pausing when the main Agent has no turns left', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ ...simplePlan,
+ escalate: '要先读仓库',
+ });
+ const graph = await service().create({ createdByAgentId: agentId, title: 'Migrate stores' });
+ // The system planner leads (exploration on); the main Agent's one turn is spent.
+ await db
+ .update(goals)
+ .set({
+ config: {
+ exploration: { maxExperiments: 2 },
+ manager: { maxTurns: 1 },
+ managerState: { consumed: true, token: 'spent', turns: 1 } as GoalConfig['managerState'],
+ },
+ })
+ .where(eq(goals.id, graph.goal.id));
+
+ await service().tick(graph.goal.id);
+
+ const goal = (await model().findById(graph.goal.id))!;
+ expect(goal.status).not.toBe('paused');
+ expect((await after(graph.goal.id)).tasks.map((n) => n.title)).toEqual(['store1']);
+ expect(AiAgentService.prototype.execAgent).not.toHaveBeenCalled();
+ });
+
+ /**
+ * Regression: a hand-over whose dispatch was refused its topic reservation
+ * still reported a started turn, so the system planner's plan was dropped and
+ * the goal waited out a turn that never ran.
+ */
+ it('runs its own plan when the hand-over dispatch is refused', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ ...simplePlan,
+ escalate: '要先读仓库',
+ });
+ vi.mocked(AiAgentService.prototype.execAgent).mockImplementationOnce(async () => {
+ throw new TopicStartReservationError('Topic tpc remained busy while starting operation x');
+ });
+ const id = await unmanagedGoal();
+
+ expect((await service().tick(id)).outcome).toBe('advanced');
+
+ const { config, tasks } = await after(id);
+ expect(tasks.map((n) => n.title)).toEqual(['store1']);
+ expect(config.manager).toBeUndefined();
+ expect(config.managerState).toMatchObject({ consumed: true, dispatchNeverStarted: true });
+ });
+
+ it('runs its own plan, and adds no main Agent, when none can take the goal', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ ...simplePlan,
+ escalate: '要先读仓库',
+ });
+ vi.spyOn(GoalManagerService.prototype, 'planInstead').mockResolvedValue(null);
+ const id = await unmanagedGoal();
+
+ await service().tick(id);
+
+ const { config, tasks } = await after(id);
+ // The policy opened for the hand-over is gone again, so no uninvited
+ // planner appears later.
+ expect(config.manager).toBeUndefined();
+ expect(tasks.map((n) => n.title)).toEqual(['store1']);
+ const [created] = await db
+ .select({ reason: goalEvents.reason })
+ .from(goalEvents)
+ .where(eq(goalEvents.entityId, tasks[0].id));
+ expect(created.reason).toBe(
+ 'Planner asked for the main Agent (要先读仓库); no main Agent could take the goal; ran its own plan',
+ );
+ });
+});
diff --git a/apps/server/src/services/goal/manager.ts b/apps/server/src/services/goal/manager.ts
index d4d8c74f3ab..e16de72b7cb 100644
--- a/apps/server/src/services/goal/manager.ts
+++ b/apps/server/src/services/goal/manager.ts
@@ -394,8 +394,15 @@ const managerTurnToken = (goalId: string) => `${goalId}_${randomUUID()}`;
*/
export const managerSnapshot = (graph: GoalGraphSnapshot) => {
// Coordinator receipts are not planning input: arming a Task's quota wake while a
- // turn runs must not make that turn's plan stale.
- const { managerState: _state, quotaRetryWakeAt: _quotaWake, ...config } = graph.goal.config ?? {};
+ // turn runs must not make that turn's plan stale, and neither may the system
+ // planner's lease — a hand-over starts the turn while the lease is still held
+ // and releases it right after.
+ const {
+ managerState: _state,
+ planningCheckpoint: _lease,
+ quotaRetryWakeAt: _quotaWake,
+ ...config
+ } = graph.goal.config ?? {};
return createHash('sha256')
.update(
JSON.stringify({
@@ -964,6 +971,28 @@ export class GoalManagerService {
return this.startTurn(graph, problem);
};
+ /**
+ * Plan a goal the system planner handed over in its first pass — it failed, or
+ * judged one pass not enough. Nothing runs yet, so this is an ordinary first
+ * turn; the reason reaches the Agent as the turn's continuation.
+ */
+ async planInstead(graph: GoalGraphSnapshot, reason: string): Promise<GoalTickResult | null> {
+ if (!this.eligible(graph)) return null;
+ const settled = await this.settleInFlight(graph);
+ if (settled) return settled;
+ // An offer, not an obligation: with no turn or budget left the hand-over is
+ // declined, and the system planner's own plan runs. Left to `startTurn`, the
+ // limit would pause the goal instead and drop that plan.
+ const policy = graph.goal.config!.manager!;
+ if (
+ (graph.goal.config?.managerState?.turns ?? 0) >=
+ (policy.maxTurns ?? DEFAULT_MANAGER_MAX_TURNS) ||
+ (await this.budgetBlocked(graph))
+ )
+ return null;
+ return this.startTurn(graph, undefined, reason, { declineRefused: true });
+ }
+
/** Return measured shortfalls to planning without weakening acceptance. */
reconsiderAcceptance = async (
graph: GoalGraphSnapshot,
@@ -1168,6 +1197,9 @@ export class GoalManagerService {
graph: GoalGraphSnapshot,
problem?: { reason: string; taskId?: string },
continuation?: string,
+ // A hand-over has the system planner's plan to fall back on, so a dispatch
+ // proven never started declines instead of waiting out the turn.
+ { declineRefused = false }: { declineRefused?: boolean } = {},
): Promise<GoalTickResult | null> => {
const { goal } = graph;
const policy = goal.config!.manager!;
@@ -1381,10 +1413,17 @@ export class GoalManagerService {
// call has returned. Any other failure may come after a run went live, so
// it stays unconfirmed. Decided from the error, never from rows the owner
// can edit or delete.
- if (error instanceof TopicStartReservationError)
- await this.recordUnstartedDispatch(goal.id, claimed.token).catch((saveError) =>
- console.error('[goal:manager] failed to record the refused dispatch', saveError),
- );
+ if (error instanceof TopicStartReservationError) {
+ const recorded = await this.recordUnstartedDispatch(
+ goal.id,
+ claimed.token,
+ declineRefused,
+ ).catch((saveError) => {
+ console.error('[goal:manager] failed to record the refused dispatch', saveError);
+ return false;
+ });
+ if (recorded && declineRefused) return null;
+ }
}
return this.wait(goal.id, 'Main Agent dispatched with CLI planning access');
};
@@ -1414,12 +1453,20 @@ export class GoalManagerService {
return true;
});
- /** Mark a turn whose dispatch was refused its topic reservation as never started. */
- private recordUnstartedDispatch = async (goalId: string, token: string) =>
+ /**
+ * Mark a turn whose dispatch was refused its topic reservation as never
+ * started; `settle` also consumes it, for a caller that will not wait it out.
+ */
+ private recordUnstartedDispatch = async (goalId: string, token: string, settle: boolean) =>
this.db.transaction(async (db) => {
const fresh = await new GoalModel(db, this.userId, this.workspaceId).lockById(goalId);
- if (fresh?.config?.managerState?.token === token)
- await this.save(db, goalId, { ...fresh.config.managerState, dispatchNeverStarted: true });
+ if (fresh?.config?.managerState?.token !== token) return false;
+ await this.save(db, goalId, {
+ ...fresh.config.managerState,
+ dispatchNeverStarted: true,
+ ...(settle && { consumed: true }),
+ });
+ return true;
});
/**
diff --git a/apps/server/src/services/goal/rolloutBatch.test.ts b/apps/server/src/services/goal/rolloutBatch.test.ts
new file mode 100644
index 00000000000..1af30623087
--- /dev/null
+++ b/apps/server/src/services/goal/rolloutBatch.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from 'vitest';
+
+import { normalizeRolloutRoster } from './rolloutBatch';
+
+describe('normalizeRolloutRoster', () => {
+ const probes = (...titles: string[]) => titles.map((title) => ({ title }));
+
+ it('does not queue a unit again when a probe title wraps its name', () => {
+ expect(
+ normalizeRolloutRoster(
+ ['device', 'toolPayload', 'brief'],
+ probes('迁移 device store(探针)'),
+ 1,
+ undefined,
+ { matchUnitInProbeTitle: true },
+ ),
+ ).toEqual(['迁移 device store(探针)', 'toolPayload', 'brief']);
+ });
+
+ /**
+ * Regression: every unit named inside a probe title was dropped, so the probe
+ * `agent runtime` also swallowed the separate unit `agent`, which then never
+ * ran.
+ */
+ it('lets a probe stand for one unit only, the longest name its title holds', () => {
+ expect(
+ normalizeRolloutRoster(
+ ['agent runtime', 'agent', '设备列表', '设备'],
+ probes('迁移 agent runtime(探针)', '迁移设备列表'),
+ 2,
+ undefined,
+ { matchUnitInProbeTitle: true },
+ ),
+ ).toEqual(['迁移 agent runtime(探针)', '迁移设备列表', 'agent', '设备']);
+ });
+
+ it('keeps exact titles only for a roster a person or Agent wrote', () => {
+ expect(normalizeRolloutRoster(['Device list', 'Device'], probes('Device list'), 1)).toEqual([
+ 'Device list',
+ 'Device',
+ ]);
+ });
+});
diff --git a/apps/server/src/services/goal/rolloutBatch.ts b/apps/server/src/services/goal/rolloutBatch.ts
index 81ef5231e7d..9e0d05e4905 100644
--- a/apps/server/src/services/goal/rolloutBatch.ts
+++ b/apps/server/src/services/goal/rolloutBatch.ts
@@ -17,6 +17,7 @@ import type { GoalModel } from '@/database/models/goal';
import type { GoalGraphModel } from '@/database/models/goalGraph';
import { BatchPlanSkillService, planUnitBrief } from './batchPlanSkill';
+import { unitsNamedByProbes } from './spec';
const log = debug('lobe-server:goal-rollout');
@@ -32,15 +33,27 @@ export const MAX_ROLLOUT_ROSTER = 60;
* `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.
+ *
+ * `matchUnitInProbeTitle` is for a model's roster, whose probe titles wrap the
+ * unit: a unit a probe title names is that probe, not a second unit run again in
+ * a wave (see `unitsNamedByProbes`). Rosters a person or Agent wrote keep exact
+ * titles only.
*/
export const normalizeRolloutRoster = (
units: string[] | undefined,
probeDrafts: { title: string }[],
canarySize: number,
limit: number = MAX_ROLLOUT_ROSTER,
+ { matchUnitInProbeTitle = false }: { matchUnitInProbeTitle?: boolean } = {},
): string[] => {
const probeTitles = probeDrafts.slice(0, canarySize).map((draft) => draft.title);
const seen = new Set(probeTitles);
+ if (matchUnitInProbeTitle)
+ for (const unit of unitsNamedByProbes(
+ probeTitles,
+ (units ?? []).map((unit) => unit.trim()),
+ ).keys())
+ seen.add(unit);
const rest: string[] = [];
for (const unit of units ?? []) {
const title = unit.trim();
diff --git a/apps/server/src/services/goal/spec.test.ts b/apps/server/src/services/goal/spec.test.ts
index 7166f29c40f..5196f1447df 100644
--- a/apps/server/src/services/goal/spec.test.ts
+++ b/apps/server/src/services/goal/spec.test.ts
@@ -1,38 +1,6 @@
import { describe, expect, it } from 'vitest';
-import {
- evaluateHomogeneity,
- HOMOGENEITY_MIN_SIMILARITY,
- maskConcreteNames,
- minPairwiseSimilarity,
- uncoveredAxisValues,
-} from './spec';
-
-describe('maskConcreteNames', () => {
- it('masks paths, identifiers and numbers so one recipe reads the same twice', () => {
- const a = maskConcreteNames('Migrate src/store/userStore.ts using the same 3 steps');
- const b = maskConcreteNames('Migrate src/store/topicStore.ts using the same 3 steps');
- expect(a).toBe(b);
- });
-});
-
-describe('minPairwiseSimilarity', () => {
- it('is 1 for briefs that are one masked shape', () => {
- const similarity = minPairwiseSimilarity([
- { instruction: 'Move src/a.ts to the new API', title: 'Migrate A' },
- { instruction: 'Move src/b.ts to the new API', title: 'Migrate B' },
- ]);
- expect(similarity).toBeGreaterThanOrEqual(HOMOGENEITY_MIN_SIMILARITY);
- });
-
- it('falls below the threshold for unrelated briefs', () => {
- const similarity = minPairwiseSimilarity([
- { instruction: 'Write a benchmark paper', title: 'Paper' },
- { instruction: 'Provision a Postgres cluster', title: 'Infra' },
- ]);
- expect(similarity).toBeLessThan(HOMOGENEITY_MIN_SIMILARITY);
- });
-});
+import { evaluateHomogeneity, uncoveredAxisValues, unitsNamedByProbes } from './spec';
describe('evaluateHomogeneity', () => {
const spec = {
@@ -43,8 +11,8 @@ describe('evaluateHomogeneity', () => {
variants: [],
};
const probes = [
- { instruction: 'Migrate src/a.ts the same way', title: 'Migrate A' },
- { instruction: 'Migrate src/b.ts the same way', title: 'Migrate B' },
+ { instruction: 'Migrate src/a.ts the same way', title: 'Migrate 1' },
+ { instruction: 'Migrate src/b.ts the same way', title: 'Migrate 2' },
];
it('accepts one repeated mould above the threshold', () => {
@@ -55,41 +23,140 @@ describe('evaluateHomogeneity', () => {
expect(evaluateHomogeneity(spec, probes, { maxUnits: 60 }).batch).toBe(true);
});
- it('refuses a roster above the batch cap so nothing is silently trimmed', () => {
+ it('judges a broken claim malformed, so it goes to the main Agent', () => {
const verdict = evaluateHomogeneity(
{ ...spec, unitCount: 65, units: Array.from({ length: 65 }, (_, i) => `Migrate ${i + 1}`) },
probes,
{ maxUnits: 60 },
);
- expect(verdict.batch).toBe(false);
+ expect(verdict).toMatchObject({ batch: false, malformed: true });
expect(verdict.reasons.join(' ')).toContain('above the batch cap of 60');
+ expect(evaluateHomogeneity({ ...spec, recipeOutline: undefined }, probes).malformed).toBe(true);
+ expect(evaluateHomogeneity(spec, probes.slice(0, 1)).malformed).toBe(true);
});
- it('refuses a claim that is not repeatable', () => {
- expect(evaluateHomogeneity({ ...spec, repeatable: false }, probes).batch).toBe(false);
+ it('refuses a claim whose roster does not list every claimed unit', () => {
+ const verdict = evaluateHomogeneity({ ...spec, units: ['Migrate 1', 'Migrate 2'] }, probes);
+ expect(verdict).toMatchObject({ batch: false, malformed: true });
+ expect(verdict.reasons.join(' ')).toContain('roster lists 2 of the 50 claimed units');
});
- it('refuses a roster below the homogeneous-unit threshold', () => {
- expect(evaluateHomogeneity({ ...spec, unitCount: 2 }, probes).batch).toBe(false);
+ /**
+ * Regression: a probe the roster did not name was counted as one more unit,
+ * so nine declared units plus three unrelated probes made "twelve" and the
+ * batch passed — three requested units were never named and never delivered.
+ */
+ it('refuses a probe that is not one of the declared units', () => {
+ const units = Array.from({ length: 9 }, (_, i) => `Migrate ${i + 1}`);
+ const verdict = evaluateHomogeneity({ ...spec, unitCount: 12, units }, [
+ { instruction: 'x', title: 'Audit the cache layer' },
+ { instruction: 'x', title: 'Write the rollout doc' },
+ { instruction: 'x', title: 'Benchmark cold start' },
+ ]);
+ expect(verdict).toMatchObject({ batch: false, malformed: true });
+ expect(verdict.reasons.join(' ')).toContain('"Audit the cache layer"');
+ expect(verdict.reasons.join(' ')).toContain('roster lists 9 of the 12 claimed units');
});
- it('refuses probes that are not one mould', () => {
+ /**
+ * Regression: a claim below the batch threshold was never malformed, so a
+ * roster missing a unit planned ordinarily and silently dropped that unit.
+ */
+ it('hands over a small claim whose roster misses units, though it is no batch', () => {
+ const verdict = evaluateHomogeneity(
+ { ...spec, unitCount: 3, units: ['Migrate 1', 'Migrate 2'] },
+ probes,
+ );
+ expect(verdict).toMatchObject({ batch: false, malformed: true });
+ expect(verdict.reasons.join(' ')).toContain('roster lists 2 of the 3 claimed units');
+ // A complete small claim is just an ordinary plan, one probe or not.
+ expect(
+ evaluateHomogeneity(
+ { ...spec, unitCount: 3, units: ['Migrate 1', 'Migrate 2', 'Migrate 3'] },
+ probes.slice(0, 1),
+ ),
+ ).toMatchObject({ batch: false, malformed: false });
+ });
+
+ it('keeps a goal that is simply not a batch on the ordinary plan', () => {
+ expect(evaluateHomogeneity({ ...spec, repeatable: false }, probes)).toMatchObject({
+ batch: false,
+ malformed: false,
+ });
+ expect(evaluateHomogeneity({ ...spec, unitCount: 2 }, probes)).toMatchObject({
+ batch: false,
+ malformed: false,
+ });
+ });
+
+ /**
+ * Regression: the gate scored the wording of the probe briefs, which refused
+ * nearly every real plan (a Chinese clause was one token; a long first probe
+ * read as other work) and still could not tell an extra transformation from
+ * a longer brief. The probes prove the recipe by running behind the gate.
+ */
+ it('does not judge the recipe from how the probe briefs are worded', () => {
const verdict = evaluateHomogeneity(spec, [
- { instruction: 'Write a benchmark paper', title: 'Paper' },
- { instruction: 'Provision a Postgres cluster', title: 'Infra' },
+ {
+ instruction:
+ '以已迁移的 store 为参照,对 src/store/device 执行:1) 定义 replica;2) 组件改为从 selector 读取;3) 删除 SWR 持久化条目;4) 补冷启动回归测试。交付物与判定标准见下。',
+ title: 'Migrate 1',
+ },
+ { instruction: '同上,对 toolPayload 执行。', title: 'Migrate 2' },
]);
- expect(verdict.batch).toBe(false);
- expect(verdict.reasons.join(' ')).toContain('one reusable transformation');
+ expect(verdict.batch).toBe(true);
});
- it('refuses a claim whose roster does not list every claimed unit', () => {
- const verdict = evaluateHomogeneity({ ...spec, units: ['Migrate 1', 'Migrate 2'] }, probes);
- expect(verdict.batch).toBe(false);
- expect(verdict.reasons.join(' ')).toContain('roster lists 4 of the 50 claimed units');
+ it('counts a probe once when its title wraps the unit it stands for', () => {
+ const units = Array.from({ length: 12 }, (_, i) => `store${i + 1}`);
+ const verdict = evaluateHomogeneity(
+ { ...spec, unitCount: 12, units },
+ [
+ { instruction: '迁移', title: '迁移 store1 store(探针)' },
+ { instruction: '迁移', title: '迁移 store2 store(探针)' },
+ ],
+ { maxUnits: 12 },
+ );
+ expect(verdict.batch).toBe(true);
+ });
+});
+
+describe('unitsNamedByProbes', () => {
+ /**
+ * Regression: a unit with `/` or `.` fell back to substring matching, so the
+ * probe `Migrate src/a.tsx` stood for the unit `src/a.ts`, which was then
+ * dropped from the roster and never processed.
+ */
+ it('matches path and dotted unit names only on their boundaries', () => {
+ expect([
+ ...unitsNamedByProbes(
+ ['Migrate src/a.tsx', 'Move @scope/pkg.v2'],
+ ['src/a.ts', '@scope/pkg'],
+ ).keys(),
+ ]).toEqual([]);
+ expect([
+ ...unitsNamedByProbes(
+ ['Migrate src/a.ts (probe)', '迁移 store.device'],
+ ['src/a.ts', 'store.device'],
+ ).keys(),
+ ]).toEqual(['src/a.ts', 'store.device']);
+ // A full stop ending the title is not more name.
+ expect([...unitsNamedByProbes(['Migrate src/a.ts.'], ['src/a.ts']).keys()]).toEqual([
+ 'src/a.ts',
+ ]);
});
- it('refuses a claim with no recipe outline', () => {
- expect(evaluateHomogeneity({ ...spec, recipeOutline: undefined }, probes).batch).toBe(false);
+ /**
+ * Regression: every unit named inside a probe title was taken as probed, so
+ * the probe `agent runtime` also swallowed the separate unit `agent`.
+ */
+ it('lets a probe stand for one unit only, the longest name its title holds', () => {
+ expect([
+ ...unitsNamedByProbes(
+ ['迁移 agent runtime(探针)', '迁移设备列表'],
+ ['agent runtime', 'agent', '设备列表', '设备'],
+ ).keys(),
+ ]).toEqual(['agent runtime', '设备列表']);
});
});
diff --git a/apps/server/src/services/goal/spec.ts b/apps/server/src/services/goal/spec.ts
index 21ca1976023..2c1d524bb39 100644
--- a/apps/server/src/services/goal/spec.ts
+++ b/apps/server/src/services/goal/spec.ts
@@ -27,70 +27,17 @@ export interface ProbeBrief {
export interface HomogeneityVerdict {
batch: boolean;
+ /**
+ * The claim is broken, not merely "not a batch": the planner said one mould
+ * but could not lay it out (no recipe, a roster missing units or too large,
+ * probes that are not roster units). One pass was not enough, so the main
+ * Agent plans it instead when the Goal has one.
+ */
+ malformed: boolean;
/** Why it failed; empty when `batch` is true. Kept for the trace and tests. */
reasons: string[];
}
-/**
- * R2's executable core, restated as code: "replace the concrete file / module /
- * symbol names with placeholders — are the transformation steps still the same?"
- *
- * The masking is deliberately crude and deterministic. It is not trying to
- * understand the prose; it removes the parts that make two applications of one
- * recipe *look* different (paths, identifiers, numbers, and inline code), so
- * what is left can be compared. A false negative here only costs the batch
- * ceremony — the goal decomposes normally — which is the safe direction.
- */
-export const maskConcreteNames = (text: string): string =>
- text
- .replaceAll(/`[^`]*`/g, ' <code> ')
- // POSIX / URL-ish paths and dotted module specifiers.
- .replaceAll(/\b[\w.@-]*(?:\/[\w.@-]+)+\b/g, ' <path> ')
- // camelCase / PascalCase / SCREAMING_CASE symbols. The character classes
- // after each capital are lowercase/digit/underscore only, so the repeated
- // group cannot match the same text two ways (no super-linear backtracking).
- .replaceAll(/\b[a-z][a-z0-9_$]*(?:[A-Z][a-z0-9_$]*)+\b/g, ' <ident> ')
- .replaceAll(/\b(?:[A-Z][a-z0-9_$]*){2,}\b/g, ' <ident> ')
- .replaceAll(/\b[A-Z][A-Z0-9_]{2,}\b/g, ' <ident> ')
- // Bare numbers (counts, indices, thresholds).
- .replaceAll(/\b\d+(?:\.\d+)?\b/g, ' <n> ')
- .toLowerCase()
- .replaceAll(/\s+/g, ' ')
- .trim();
-
-const tokensOf = (text: string): Set<string> =>
- new Set(
- maskConcreteNames(text)
- .split(/[^\p{L}\p{N}<>]+/u)
- .filter((token) => token.length > 1),
- );
-
-const jaccard = (a: Set<string>, b: Set<string>): number => {
- if (a.size === 0 && b.size === 0) return 1;
- let intersection = 0;
- for (const token of a) if (b.has(token)) intersection += 1;
- return intersection / (a.size + b.size - intersection);
-};
-
-/** Lowest pairwise Jaccard similarity across every pair of probe shapes. */
-export const minPairwiseSimilarity = (briefs: ProbeBrief[]): number => {
- if (briefs.length < 2) return 1;
- const shapes = briefs.map((brief) => tokensOf(`${brief.title}\n${brief.instruction}`));
- let min = 1;
- for (let i = 0; i < shapes.length; i += 1) {
- for (let j = i + 1; j < shapes.length; j += 1) {
- min = Math.min(min, jaccard(shapes[i], shapes[j]));
- }
- }
- return min;
-};
-
-/**
- * Below this the probe briefs are describing different work, not one recipe
- * applied to different units.
- */
-export const HOMOGENEITY_MIN_SIMILARITY = 0.5;
-
const escapeRegExp = (value: string): string => value.replaceAll(/[.*+?^${}()|[\]\\]/g, '\\$&');
/**
@@ -137,18 +84,18 @@ export const uncoveredAxisValues = (
/**
* Validate the planner's batch claim before decomposition acts on it.
*
- * Every condition must hold: the planner marked it repeatable, named the one
- * reusable transformation, counted at least the threshold of homogeneous units,
- * listed every one of them in the roster, listed more than one probe, and the
- * probes really read as one mould after masking. Any failure keeps the ordinary
- * one-unit-per-task decomposition and records why.
+ * The checks are structural only: the planner marked it repeatable, named the
+ * one reusable transformation, counted at least the threshold of homogeneous
+ * units, listed every one of them in the roster, and listed more than one probe.
+ * Whether the recipe really holds is not judged from the wording here — the
+ * probes prove it by running, and the release gate holds the rest of the roster
+ * until they do. A claim that is not a batch keeps the ordinary decomposition; a
+ * broken one is `malformed`, which the coordinator hands to the main Agent.
*
* `maxUnits` is the batch roster's ceiling (the caller's config bound). A claim
* above it is refused here rather than batched, so the roster a batch carries is
* always the whole one: the coordinator waves it out unit by unit, and a cap
- * applied at creation would silently leave the tail undelivered. The refused
- * claim falls back to the ordinary decomposition, which materializes every unit
- * the planner listed.
+ * applied at creation would silently leave the tail undelivered.
*/
export const evaluateHomogeneity = (
spec: BatchSpecDraft,
@@ -156,27 +103,87 @@ export const evaluateHomogeneity = (
options: { maxUnits?: number; minUnits?: number } = {},
): HomogeneityVerdict => {
const minUnits = options.minUnits ?? ROLLOUT_MIN_HOMOGENEOUS_UNITS;
- const reasons: string[] = [];
+ // "Not a batch": the ordinary decomposition is the right plan.
+ const notBatch: string[] = [];
+ // A broken claim: one pass could not lay the mould out.
+ const broken: string[] = [];
- if (!spec.repeatable) reasons.push('planner did not mark the goal repeatable');
- if (!spec.recipeOutline?.trim()) reasons.push('no reusable recipe outline');
+ if (!spec.repeatable) notBatch.push('planner did not mark the goal repeatable');
if (!Number.isFinite(spec.unitCount) || spec.unitCount < minUnits)
- reasons.push(`unitCount ${spec.unitCount} is below the threshold ${minUnits}`);
+ notBatch.push(`unitCount ${spec.unitCount} is below the threshold ${minUnits}`);
+ if (!spec.recipeOutline?.trim()) broken.push('no reusable recipe outline');
// The roster is what the waves deliver: a claim the roster cannot account for
- // would exhaust it early and silently drop every unit it left out.
- const roster = new Set(
- [...briefs.map((brief) => brief.title), ...(spec.units ?? [])]
- .map((title) => title.trim())
- .filter(Boolean),
+ // would exhaust it early and silently drop every unit it left out. Only the
+ // declared units count, and every probe must be one of them — a probe the
+ // roster does not name would stand in for a unit nobody listed, and the unit
+ // it displaced would never be delivered.
+ const probeTitles = briefs.map((brief) => brief.title.trim()).filter(Boolean);
+ const units = (spec.units ?? []).map((unit) => unit.trim()).filter(Boolean);
+ const probed = unitsNamedByProbes(probeTitles, units);
+ const stray = probeTitles.filter(
+ (title) => !units.includes(title) && !units.some((unit) => probed.get(unit) === title),
);
- if (Number.isFinite(spec.unitCount) && roster.size < spec.unitCount)
- reasons.push(`roster lists ${roster.size} of the ${spec.unitCount} claimed units`);
+ if (stray.length)
+ broken.push(`probe ${stray.map((title) => `"${title}"`).join(', ')} is not a roster unit`);
+ const roster = new Set(units);
+ const lostUnits = Number.isFinite(spec.unitCount) && roster.size < spec.unitCount;
+ if (lostUnits) broken.push(`roster lists ${roster.size} of the ${spec.unitCount} claimed units`);
if (options.maxUnits !== undefined && roster.size > options.maxUnits)
- reasons.push(`roster lists ${roster.size} units, above the batch cap of ${options.maxUnits}`);
- if (briefs.length < 2) reasons.push('fewer than two probe units');
+ broken.push(`roster lists ${roster.size} units, above the batch cap of ${options.maxUnits}`);
+ if (briefs.length < 2) broken.push('fewer than two probe units');
+
+ // A claim that is not worth a batch (not repeatable, too few units) plans
+ // ordinarily, where probes and a recipe do not matter — but a roster missing
+ // units would drop them there too, so that stays broken either way.
+ const reasons = [...notBatch, ...broken];
+ return {
+ batch: reasons.length === 0,
+ malformed: broken.length > 0 && (notBatch.length === 0 || lostUnits),
+ reasons,
+ };
+};
+
+/**
+ * The roster units a model's probes stand for. Its probe titles wrap the unit
+ * ("迁移 device store(探针)" for unit `device`), so a unit is the probe when
+ * its title names it — as a whole word, or a substring in scripts without word
+ * boundaries. Each probe stands for one unit only, the longest name its title
+ * holds, so the probe `agent runtime` leaves the separate unit `agent` queued:
+ * a probe covering two units costs a rerun, never a unit that is dropped.
+ */
+/** Scripts written without spaces between words, where a name has no boundary. */
+const UNSPACED_SCRIPT = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
- if (briefs.length >= 2 && minPairwiseSimilarity(briefs) < HOMOGENEITY_MIN_SIMILARITY)
- reasons.push('probe briefs do not describe one reusable transformation');
+/**
+ * Whether a probe title names a unit. A unit in an unspaced script is matched
+ * as a substring; any other — a word, a path like `src/a.ts`, a dotted module —
+ * only where neither side continues it, so `src/a.tsx` and `src/a.ts.bak` do not
+ * name `src/a.ts`, and `agentic` does not name `agent`.
+ */
+const titleNamesUnit = (title: string, unit: string): boolean => {
+ const name = unit.trim().toLowerCase();
+ if (!name) return false;
+ const text = title.toLowerCase();
+ if (UNSPACED_SCRIPT.test(name)) return text.includes(name);
+ // A name continues through a separator into more name — `src/a.ts.bak`,
+ // `lib/src/a.ts`, `@scope/pkg.v2` are other units — while a full stop or a
+ // space after it does not.
+ const word = '[\\p{L}\\p{N}_]';
+ return new RegExp(
+ `(?<!${word})(?<!${word}[./-])${escapeRegExp(name)}(?!${word})(?![./-]${word})`,
+ 'u',
+ ).test(text);
+};
- return { batch: reasons.length === 0, reasons };
+export const unitsNamedByProbes = (probeTitles: string[], units: string[]): Map<string, string> => {
+ // unit → the probe title that stands for it
+ const named = new Map<string, string>();
+ const candidates = [...new Set(units)].filter((unit) => !probeTitles.includes(unit));
+ for (const probe of probeTitles) {
+ const unit = candidates
+ .filter((candidate) => !named.has(candidate) && titleNamesUnit(probe, candidate))
+ .sort((a, b) => b.length - a.length)[0];
+ if (unit) named.set(unit, probe);
+ }
+ return named;
};
diff --git a/packages/database/src/models/goal.ts b/packages/database/src/models/goal.ts
index 8d5bb1f4c15..0cb2c598a9b 100644
--- a/packages/database/src/models/goal.ts
+++ b/packages/database/src/models/goal.ts
@@ -3,6 +3,7 @@ import { randomUUID } from 'node:crypto';
import { GOAL_CLARIFICATION_TITLE, type GoalStatus } from '@lobechat/const/goal';
import type {
GoalDecisionOption,
+ GoalManagerPolicy,
GoalNodeStatus,
GoalRolloutPolicy,
GoalRolloutState,
@@ -208,6 +209,38 @@ export class GoalModel {
.where(and(eq(goals.id, id), this.ownership()));
};
+ /**
+ * Patch only `config.manager`: open the main Agent policy unless one is
+ * already there, which is kept as it is. The coordinator opens one when its
+ * own planner hands a goal over.
+ */
+ openManagerPolicy = async (id: string, policy: GoalManagerPolicy): Promise<void> => {
+ await this.db
+ .update(goals)
+ .set({
+ config: sql`jsonb_set(COALESCE(${goals.config}, '{}'::jsonb), '{manager}', COALESCE(${goals.config}->'manager', ${JSON.stringify(policy)}::jsonb))`,
+ updatedAt: new Date(),
+ })
+ .where(and(eq(goals.id, id), this.ownership()));
+ };
+
+ /**
+ * Remove the policy a hand-over opened, only while it is still that one: a
+ * policy a person set or changed in the meantime has another token, or none.
+ */
+ closeHandoffManagerPolicy = async (id: string, token: string): Promise<void> => {
+ await this.db
+ .update(goals)
+ .set({ config: sql`${goals.config} - 'manager'`, updatedAt: new Date() })
+ .where(
+ and(
+ eq(goals.id, id),
+ this.ownership(),
+ sql`${goals.config}->'manager'->>'openedForHandoff' = ${token}`,
+ ),
+ );
+ };
+
/** Patch only `config.rollout`, so auto-detection can persist the policy. */
updateRolloutPolicy = async (id: string, policy: GoalRolloutPolicy): Promise<void> => {
await this.db
diff --git a/packages/database/src/models/goalGraph.ts b/packages/database/src/models/goalGraph.ts
index 8e2ef8c304f..ffbb774429f 100644
--- a/packages/database/src/models/goalGraph.ts
+++ b/packages/database/src/models/goalGraph.ts
@@ -63,6 +63,8 @@ interface CreateNodeInput {
kind: GoalNodeKind;
priority?: number;
questionId?: string;
+ /** Why the node was created this way, kept on its `created` event. */
+ reason?: string;
scopeId?: string;
status?: GoalNodeStatus;
title: string;
@@ -566,7 +568,7 @@ export class GoalGraphModel {
createNode = async (goalId: string, input: CreateNodeInput) =>
this.db.transaction(async (tx) => {
if (!(await this.ownedGoal(goalId, tx))) return undefined;
- const { scopeId, questionId, ...values } = input;
+ const { scopeId, questionId, reason, ...values } = input;
if (input.kind === 'experiment' && !questionId)
throw new Error('An experiment must answer a question');
if (input.kind !== 'experiment' && questionId)
@@ -586,6 +588,7 @@ export class GoalGraphModel {
entityId: node.id,
entityType: 'node',
eventType: 'created',
+ reason,
});
const model = new GoalGraphModel(
tx as unknown as LobeChatDatabase,
diff --git a/packages/prompts/src/chains/goal.test.ts b/packages/prompts/src/chains/goal.test.ts
index fe8efb1c37c..b03a52381fe 100644
--- a/packages/prompts/src/chains/goal.test.ts
+++ b/packages/prompts/src/chains/goal.test.ts
@@ -44,7 +44,7 @@ describe('chainGoalDecompose', () => {
const { messages } = chainGoalDecompose({ requirement });
const prompt = messages[0].content;
- expect(GOAL_DECOMPOSE_PROMPT_VERSION).toBe('v8');
+ expect(GOAL_DECOMPOSE_PROMPT_VERSION).toBe('v9');
expect(messages[1].content).toContain(requirement);
expect(prompt).toContain('a request to build, fix, or upgrade requires implementation');
expect(prompt).toContain('It may pass when it proves a capability is missing');
@@ -64,6 +64,15 @@ describe('chainGoalDecompose', () => {
expect(prompt).toContain('after replacing the concrete file / module / symbol names');
// Probe-only tasks plus the full roster the coordinator promotes from.
expect(prompt).toContain('3–5 probes');
+ // One unit per probe, one template, no recipe-checking task: otherwise the
+ // probes stop reading as one mould and the batch is refused.
+ expect(prompt).toContain('Each probe is exactly ONE unit from rollout.units');
+ expect(prompt).toContain('Do not add tasks that verify, summarize or validate the recipe');
+ // One simple pass; anything harder is the main Agent's to plan.
+ expect(prompt).toContain('You plan in one pass, without seeing the workspace');
+ const schema = GOAL_DECOMPOSE_JSON_SCHEMA.schema as any;
+ expect(schema.properties.escalate.type).toEqual(['string', 'null']);
+ expect(schema.required).toContain('escalate');
expect(prompt).toContain('full roster of every homogeneous unit');
expect(prompt).toContain('leave rollout null');
diff --git a/packages/prompts/src/chains/goal.ts b/packages/prompts/src/chains/goal.ts
index 3469f748ba9..3f944f1aeea 100644
--- a/packages/prompts/src/chains/goal.ts
+++ b/packages/prompts/src/chains/goal.ts
@@ -65,7 +65,7 @@ export const GOAL_CRITERIA_DRAFT_JSON_SCHEMA = {
};
/** Bump when the goal decomposition planning prompt meaningfully changes. */
-export const GOAL_DECOMPOSE_PROMPT_VERSION = 'v8';
+export const GOAL_DECOMPOSE_PROMPT_VERSION = 'v9';
export const GOAL_DECOMPOSE_JSON_SCHEMA = {
name: 'goal_decomposition',
@@ -73,6 +73,12 @@ export const GOAL_DECOMPOSE_JSON_SCHEMA = {
additionalProperties: false,
properties: {
assumptions: { items: { maxLength: 280, type: 'string' }, maxItems: 5, type: 'array' },
+ /**
+ * One sentence on why this goal needs more than a single planning pass,
+ * so the main Agent — which can inspect the workspace — plans it instead.
+ * Null when the plan below is good enough to run.
+ */
+ escalate: { maxLength: 280, type: ['string', 'null'] },
problemStatement: { maxLength: 280, minLength: 1, type: 'string' },
/**
* Set only for one repeated mould — many structurally identical units
@@ -138,7 +144,7 @@ export const GOAL_DECOMPOSE_JSON_SCHEMA = {
type: 'array',
},
},
- required: ['problemStatement', 'questions', 'assumptions', 'tasks', 'rollout'],
+ required: ['problemStatement', 'questions', 'assumptions', 'tasks', 'rollout', 'escalate'],
type: 'object' as const,
},
strict: true,
@@ -169,6 +175,7 @@ export const chainGoalDecompose = ({
{
content: [
'You plan executable tasks for a persistent autonomous goal.',
+ 'You plan in one pass, without seeing the workspace. That suits a goal whose shape is clear from its wording. When planning it well needs more — reading the repository or files to know what the units are, ordering a multi-phase change, or you are not sure the work is one repeated mould — set escalate to one sentence saying what, and the main Agent, which can inspect the workspace, plans the goal instead. Still return your best plan below; it runs only if no main Agent can take the goal. Leave escalate null whenever your plan is good enough to run.',
'Decompose the goal into the outcome it must achieve and the tasks that together deliver it. Preserve the requested action: a request to build, fix, or upgrade requires implementation, not just investigation or verification.',
'Guidelines:',
'- problemStatement is 1–2 sentences naming the core question or outcome of the goal, in your own words. Never copy the acceptance-criteria list into it.',
@@ -193,7 +200,7 @@ export const chainGoalDecompose = ({
"- When you set rollout, repeatable must be true only if, after replacing the concrete file / module / symbol names with placeholders, every unit's transformation steps are still the same. If they differ, it is not one batch: leave rollout null and decompose the directions normally.",
'- rollout.unitCount is your honest count of the homogeneous units in the WHOLE goal (it will usually exceed the few tasks you list). recipeOutline names that single reusable transformation in one sentence. variants lists the axes the units vary along (e.g. axis "cold-start" with values ["yes","no"]); name an axis only if some unit actually takes each value you list.',
'- rollout.units is the full roster of every homogeneous unit as short titles, probes first and in delivery order (list all of them, up to 60). The coordinator promotes the units after the probes from this roster one wave at a time; a unit missing here will never be delivered.',
- '- When rollout is set, tasks lists only the few REPRESENTATIVE units to run first — 3–5 probes, not every unit. Choose probes that cover the declared variant axes and MUST include the hardest unit. The coordinator releases the remaining units in waves once the probes prove the class runs fully automatically; do not enumerate them here.',
+ '- When rollout is set, tasks lists only the few REPRESENTATIVE units to run first — 3–5 probes, not every unit. Choose probes that cover the declared variant axes and MUST include the hardest unit. Each probe is exactly ONE unit from rollout.units and its title is exactly that unit entry, character for character, and every probe instruction follows the same template — the shared recipe steps, then only the specifics of that unit — so the probes read as one mould. Do not add tasks that verify, summarize or validate the recipe: the gate of the coordinator does that after the probes. The coordinator releases the remaining units in waves once the probes prove the class runs fully automatically; do not enumerate them here.',
'- Write all fields in the language used by the goal.',
].join('\n'),
role: 'system',
diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.ts
index 161013ea0ae..3a3001417fb 100644
--- a/packages/types/src/goal.ts
+++ b/packages/types/src/goal.ts
@@ -236,6 +236,12 @@ export const summarizeGoalSupervision = (state?: GoalSupervisionState): GoalSupe
export interface GoalManagerPolicy {
instruction?: string;
maxTurns?: number;
+ /**
+ * Set when the coordinator opened this policy to hand its planning over; the
+ * token lets a hand-over that could not start remove its own policy and
+ * nothing a person set meanwhile.
+ */
+ openedForHandoff?: string;
}
/** Bounded wait on time or one correlated external result. */