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.

🐛 fix(goal): create experiments only for planned hypotheses and fail dead dispatches (#19339)

Arvin Xu20f16ef4cd02
diff --git a/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts
index dc804ff10d3..f3092f41007 100644
--- a/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts
@@ -952,6 +952,42 @@ describe('Task Router Integration', () => {
expect(found.data.status).toBe('paused');
expect(found.data.error).toContain('LLM failed');
});
+
+ it('does not book a running topic when execAgent reports a dispatch failure', async () => {
+ // A heterogeneous dispatch or operation startup failure comes back as a
+ // result (`success: false`) rather than a throw: the topic and its error
+ // bubble already exist. Booking that dead operation as a running run left
+ // the Task in flight forever, with a goal coordinator recording a start.
+ mockExecAgent.mockResolvedValueOnce({
+ error:
+ 'Heterogeneous agent provider binding is only supported for Desktop local execution.',
+ message: 'Heterogeneous agent provider binding requires Desktop local execution',
+ operationId: 'op_dead',
+ status: 'error',
+ success: false,
+ topicId: testTopicId,
+ });
+
+ const task = await caller.create({
+ assigneeAgentId: testAgentId,
+ instruction: 'Test',
+ });
+
+ await expect(caller.run({ id: task.data.id })).rejects.toThrow();
+
+ const found = await caller.find({ id: task.data.id });
+ expect(found.data.status).toBe('paused');
+ expect(found.data.error).toContain('Desktop local execution');
+
+ // The attempt stays visible, but as a failed run — never a running one.
+ const runs = await new TaskTopicModel(serverDB, userId).findByTaskId(task.data.id);
+ expect(runs.map((run) => [run.topicId, run.operationId, run.status])).toEqual([
+ [testTopicId, 'op_dead', 'failed'],
+ ]);
+ // ...so a fresh run is allowed instead of "already has a running topic".
+ await caller.run({ id: task.data.id });
+ expect((await caller.detail({ id: task.data.id })).data?.status).toBe('running');
+ });
});
describe('clearAll', () => {
diff --git a/apps/server/src/services/goal/criteriaGenerator.test.ts b/apps/server/src/services/goal/criteriaGenerator.test.ts
index 0e8e3608b0b..2aec337be5b 100644
--- a/apps/server/src/services/goal/criteriaGenerator.test.ts
+++ b/apps/server/src/services/goal/criteriaGenerator.test.ts
@@ -63,7 +63,7 @@ describe('GoalCriteriaGeneratorService', () => {
expect.objectContaining({ schema: expect.objectContaining({ name: 'goal_decomposition' }) }),
expect.objectContaining({
tracing: {
- promptVersion: 'v4',
+ promptVersion: 'v5',
scenario: 'goal_decompose',
schemaName: 'goal_decomposition',
},
diff --git a/apps/server/src/services/goal/criteriaGenerator.ts b/apps/server/src/services/goal/criteriaGenerator.ts
index 8a2170c7662..d749b29fed4 100644
--- a/apps/server/src/services/goal/criteriaGenerator.ts
+++ b/apps/server/src/services/goal/criteriaGenerator.ts
@@ -74,6 +74,12 @@ const decompositionSchema = z.object({
z.object({
/** 0-based indices of earlier tasks this one consumes; drives `depends_on` edges. */
dependsOn: z.array(z.number().int().nonnegative()).optional(),
+ /**
+ * Present only when the direction is a candidate answer under test; the
+ * coordinator then wraps its Task in an experiment container. Ordinary
+ * delivery steps carry `null` and attach straight to the problem.
+ */
+ hypothesis: z.string().max(280).nullable().optional(),
instruction: z.string().min(1),
title: z.string().min(1).max(80),
}),
diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.ts
index 7c5a2a2bffe..5051dce0b78 100644
--- a/apps/server/src/services/goal/index.test.ts
+++ b/apps/server/src/services/goal/index.test.ts
@@ -852,13 +852,34 @@ describe('GoalService', () => {
expect(await service.graph(graph.goal.id)).toBeDefined();
});
- it('creates persistent answer containers by default without exploration enabled', async () => {
+ it('attaches seed tasks straight to the problem instead of wrapping each in an experiment', async () => {
+ // An experiment is a candidate answer under test. A caller-supplied seed is
+ // ordinary work, so it takes the same shape as a planned or manager-submitted
+ // Task: a `decomposes` edge from the problem, no answer container.
const service = new GoalService(serverDB, userId);
- const graph = await service.create({ title: 'Question', tasks: ['Candidate answer'] });
+ const graph = await service.create({ title: 'Question', tasks: ['Seed work'] });
const question = graph.nodes.find((n) => n.kind === 'problem')!;
- const answer = graph.nodes.find((n) => n.kind === 'experiment')!;
const task = graph.nodes.find((n) => n.kind === 'task')!;
expect(graph.goal.config?.exploration).toBeUndefined();
+ expect(graph.nodes.filter((n) => n.kind === 'experiment')).toHaveLength(0);
+ expect(graph.edges).toEqual([
+ expect.objectContaining({
+ kind: 'decomposes',
+ sourceNodeId: question.id,
+ targetNodeId: task.id,
+ }),
+ ]);
+ });
+
+ it('seeds the exploration baseline inside an experiment container', async () => {
+ const service = new GoalService(serverDB, userId);
+ const graph = await service.create({
+ config: { exploration: { instruction: 'Compare evidence', maxExperiments: 3 } },
+ title: 'Explore',
+ });
+ const question = graph.nodes.find((n) => n.kind === 'problem')!;
+ const answer = graph.nodes.find((n) => n.kind === 'experiment')!;
+ const task = graph.nodes.find((n) => n.kind === 'task')!;
expect(answer.taskId).toBeNull();
expect(graph.edges).toEqual(
expect.arrayContaining([
@@ -880,8 +901,13 @@ describe('GoalService', () => {
vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
problemStatement: '核心问题的一句话陈述',
tasks: [
- { dependsOn: [], instruction: '收集原始材料', title: '方向A:收集' },
- { dependsOn: [0], instruction: '分析并综合结论', title: '方向B:分析' },
+ { dependsOn: [], hypothesis: null, instruction: '收集原始材料', title: '方向A:收集' },
+ {
+ dependsOn: [0],
+ hypothesis: '按模块聚类比按时间排序更能暴露根因',
+ instruction: '分析并综合结论',
+ title: '方向B:分析',
+ },
// Self and forward references are planner hallucinations — dropped.
{ dependsOn: [1, 2, 9], instruction: '汇编最终报告', title: '方向C:汇编' },
],
@@ -905,14 +931,37 @@ describe('GoalService', () => {
'方向B:分析',
'方向C:汇编',
]);
- expect(after.nodes.find((n) => n.kind === 'problem')?.description).toBe('核心问题的一句话陈述');
- expect(after.nodes.filter((n) => n.kind === 'experiment')).toHaveLength(3);
- expect(after.edges.filter((e) => e.kind === 'answers')).toHaveLength(3);
- expect(after.edges.filter((e) => e.kind === 'contains')).toHaveLength(3);
+ const problem = after.nodes.find((n) => n.kind === 'problem')!;
+ expect(problem.description).toBe('核心问题的一句话陈述');
+
+ // Only the direction the planner marked as a hypothesis becomes a candidate
+ // answer: one experiment answering the problem and containing that Task.
+ // The certain steps attach straight to the problem.
+ const byTitle = new Map(after.nodes.map((n) => [n.title, n.id]));
+ const experiments = after.nodes.filter((n) => n.kind === 'experiment');
+ expect(experiments).toHaveLength(1);
+ expect(experiments[0]).toMatchObject({
+ description: '按模块聚类比按时间排序更能暴露根因',
+ title: '方向B:分析',
+ });
+ expect(after.edges.filter((e) => e.kind === 'answers')).toEqual([
+ expect.objectContaining({ sourceNodeId: experiments[0].id, targetNodeId: problem.id }),
+ ]);
+ expect(after.edges.filter((e) => e.kind === 'contains')).toEqual([
+ expect.objectContaining({
+ sourceNodeId: experiments[0].id,
+ targetNodeId: byTitle.get('方向B:分析'),
+ }),
+ ]);
+ expect(
+ after.edges
+ .filter((e) => e.kind === 'decomposes' && e.sourceNodeId === problem.id)
+ .map((e) => e.targetNodeId)
+ .sort(),
+ ).toEqual([byTitle.get('方向A:收集'), byTitle.get('方向C:汇编')].sort());
// The planner's dependsOn indices become depends_on edges, dependent →
// prerequisite; the self and forward references were dropped.
- const byTitle = new Map(after.nodes.map((n) => [n.title, n.id]));
const deps = after.edges
.filter((e) => e.kind === 'depends_on')
.map((e) => [e.sourceNodeId, e.targetNodeId]);
@@ -925,28 +974,34 @@ describe('GoalService', () => {
);
});
- it('creates persistent answer containers by default without exploration enabled', async () => {
+ it('plans a goal without hypotheses as plain tasks under the problem', async () => {
+ vi.spyOn(GoalCriteriaGeneratorService.prototype, 'decompose').mockResolvedValue({
+ problemStatement: '修好最近三天的 bug',
+ tasks: [
+ { dependsOn: [], hypothesis: null, instruction: '列出 issue', title: '建立清单' },
+ { dependsOn: [0], hypothesis: null, instruction: '逐项修复', title: '实施修复' },
+ ],
+ });
const service = new GoalService(serverDB, userId);
- const graph = await service.create({ title: 'Question', tasks: ['Candidate answer'] });
- const question = graph.nodes.find((n) => n.kind === 'problem')!;
- const answer = graph.nodes.find((n) => n.kind === 'experiment')!;
- const task = graph.nodes.find((n) => n.kind === 'task')!;
- expect(graph.goal.config?.exploration).toBeUndefined();
- expect(answer.taskId).toBeNull();
- expect(graph.edges).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- kind: 'answers',
- sourceNodeId: answer.id,
- targetNodeId: question.id,
- }),
- expect.objectContaining({
- kind: 'contains',
- sourceNodeId: answer.id,
- targetNodeId: task.id,
- }),
- ]),
+ const graph = await service.create({ title: 'Bug sweep' });
+
+ expect((await service.tick(graph.goal.id)).outcome).toBe('advanced');
+
+ const after = await service.graph(graph.goal.id);
+ const problem = after.nodes.find((n) => n.kind === 'problem')!;
+ const taskIds = after.nodes.filter((n) => n.kind === 'task').map((n) => n.id);
+ expect(taskIds).toHaveLength(2);
+ expect(after.nodes.filter((n) => n.kind === 'experiment')).toHaveLength(0);
+ expect(after.edges.filter((e) => e.kind === 'answers' || e.kind === 'contains')).toHaveLength(
+ 0,
);
+ expect(
+ after.edges
+ .filter((e) => e.kind === 'decomposes' && e.sourceNodeId === problem.id)
+ .map((e) => e.targetNodeId)
+ .sort(),
+ ).toEqual([...taskIds].sort());
+ expect(after.edges.filter((e) => e.kind === 'depends_on')).toHaveLength(1);
});
it('plans the decomposition once when two advances race through the planner', async () => {
@@ -1034,9 +1089,9 @@ describe('GoalService', () => {
}
const after = await service.graph(graph.goal.id);
expect(after.nodes.filter((node) => node.kind === 'task')).toHaveLength(1);
- expect(after.nodes.filter((node) => node.kind === 'experiment')).toHaveLength(1);
+ expect(after.nodes.filter((node) => node.kind === 'experiment')).toHaveLength(0);
expect(after.nodes.find((node) => node.kind === 'problem')?.description).toBe('First plan');
- expect(after.edges.filter((edge) => edge.kind === 'answers')).toHaveLength(1);
+ expect(after.edges.filter((edge) => edge.kind === 'decomposes')).toHaveLength(1);
});
it('rejects a late planner after an expired lease is taken over', async () => {
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index dd7a4ce33e6..9a49cccba58 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -302,21 +302,15 @@ export class GoalService {
});
if (!problem) throw new Error('Failed to seed goal problem');
- const seeds =
- input.tasks ??
- (config?.exploration
- ? [
- {
- title: input.title,
- description: `Produce one initial baseline experiment for this Goal. ${input.problemDescription ?? requirement ?? input.title}\nExploration method: ${config.exploration.instruction}\nExecute the baseline only; later experiments are scheduled by the Goal coordinator. Include a self-contained result and evidence.`,
- },
- ]
- : []);
- for (const seed of seeds) {
- const { description, title } = typeof seed === 'string' ? { title: seed } : seed;
+ // An exploration baseline is the goal's first candidate answer, so it
+ // lives inside an experiment container the explorer can branch from.
+ // Caller-supplied seed tasks are ordinary work: they attach straight to
+ // the problem the way a planned or manager-submitted task does.
+ if (config?.exploration && !input.tasks) {
+ const description = `Produce one initial baseline experiment for this Goal. ${input.problemDescription ?? requirement ?? input.title}\nExploration method: ${config.exploration.instruction}\nExecute the baseline only; later experiments are scheduled by the Goal coordinator. Include a self-contained result and evidence.`;
const experiment = await authorGraph.createNode(goal.id, {
kind: 'experiment',
- title,
+ title: input.title,
description,
questionId: problem.id,
createdByAgentId: input.createdByAgentId,
@@ -324,12 +318,23 @@ export class GoalService {
if (!experiment) throw new Error('Failed to seed experiment');
const taskNode = await authorGraph.createNode(goal.id, {
scopeId: experiment.id,
+ createdByAgentId: input.createdByAgentId,
+ description,
+ kind: 'task',
+ title: input.title,
+ });
+ if (!taskNode) throw new Error('Failed to seed goal task');
+ }
+ for (const seed of input.tasks ?? []) {
+ const { description, title } = typeof seed === 'string' ? { title: seed } : seed;
+ const taskNode = await authorGraph.createNode(goal.id, {
createdByAgentId: input.createdByAgentId,
description,
kind: 'task',
title,
});
if (!taskNode) throw new Error('Failed to seed goal task');
+ await authorGraph.createEdge(goal.id, problem.id, taskNode.id, 'decomposes');
}
} catch (error) {
await this.goalModel.delete(goal.id).catch(() => {});
@@ -2100,15 +2105,22 @@ export class GoalService {
const createdIds: string[] = [];
for (const draft of draftTasks) {
- const experiment = currentProblem
- ? await writer.createNode(goalId, {
- kind: 'experiment',
- title: draft.title,
- description: draft.instruction,
- questionId: currentProblem.id,
- })
- : undefined;
- if (currentProblem && !experiment)
+ // An experiment is a container for a candidate answer, not the
+ // default shell around every planned step. Only a direction the
+ // planner marked with a hypothesis gets one; a certain delivery step
+ // attaches straight to the problem, the same shape a manager-planned
+ // Task takes.
+ const hypothesis = draft.hypothesis?.trim();
+ const experiment =
+ currentProblem && hypothesis
+ ? await writer.createNode(goalId, {
+ kind: 'experiment',
+ title: draft.title,
+ description: hypothesis,
+ questionId: currentProblem.id,
+ })
+ : undefined;
+ if (currentProblem && hypothesis && !experiment)
throw new Error('Failed to create a planned experiment');
const node = await writer.createNode(goalId, {
scopeId: experiment?.id,
@@ -2117,6 +2129,8 @@ export class GoalService {
title: draft.title,
});
if (!node) throw new Error('Failed to create a planned task');
+ if (!experiment && currentProblem)
+ await writer.createEdge(goalId, currentProblem.id, node.id, 'decomposes');
createdIds.push(node.id);
committedEffects.push({ nodeId: node.id, type: 'created_node', detail: draft.title });
}
diff --git a/apps/server/src/services/taskRunner/index.ts b/apps/server/src/services/taskRunner/index.ts
index 11c6ea16cfd..99a349427ba 100644
--- a/apps/server/src/services/taskRunner/index.ts
+++ b/apps/server/src/services/taskRunner/index.ts
@@ -258,6 +258,29 @@ export class TaskRunnerService {
...(continueTopicId && { appContext: { topicId: continueTopicId } }),
});
+ if (!result.success) {
+ // execAgent reports a dispatch or startup failure as a result rather
+ // than a throw (`startOperation`, `heteroDispatch`): the assistant
+ // bubble already carries the error and the run's lifecycle hooks have
+ // fired. Booking that dead operation as a running topic would leave
+ // the Task looking in flight — a goal coordinator would even record a
+ // `started_run` for it — with nothing left to ever settle it. Keep the
+ // attempt visible as a failed run, then fail the kickoff like any other.
+ if (result.topicId && !continueTopicId) {
+ await this.taskModel.incrementTopicCount(task.id);
+ await this.taskModel.updateCurrentTopic(task.id, result.topicId);
+ await this.taskTopicModel.add(task.id, result.topicId, {
+ operationId: result.operationId,
+ seq: (task.totalTopics || 0) + 1,
+ trigger,
+ });
+ }
+ if (result.topicId) {
+ await this.taskTopicModel.updateStatus(task.id, result.topicId, 'failed');
+ }
+ throw new Error(result.error || result.message || 'Agent run failed to start');
+ }
+
if (result.topicId) {
if (continueTopicId) {
await this.taskTopicModel.updateStatus(task.id, continueTopicId, 'running');
diff --git a/packages/prompts/src/chains/goal.test.ts b/packages/prompts/src/chains/goal.test.ts
index 287975d5eef..4dce173f754 100644
--- a/packages/prompts/src/chains/goal.test.ts
+++ b/packages/prompts/src/chains/goal.test.ts
@@ -43,7 +43,7 @@ describe('chainGoalDecompose', () => {
const { messages } = chainGoalDecompose({ requirement });
const prompt = messages[0].content;
- expect(GOAL_DECOMPOSE_PROMPT_VERSION).toBe('v4');
+ expect(GOAL_DECOMPOSE_PROMPT_VERSION).toBe('v5');
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');
diff --git a/packages/prompts/src/chains/goal.ts b/packages/prompts/src/chains/goal.ts
index ee0877d0617..f88a65c503e 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 = 'v4';
+export const GOAL_DECOMPOSE_PROMPT_VERSION = 'v5';
export const GOAL_DECOMPOSE_JSON_SCHEMA = {
name: 'goal_decomposition',
@@ -78,10 +78,11 @@ export const GOAL_DECOMPOSE_JSON_SCHEMA = {
additionalProperties: false,
properties: {
dependsOn: { items: { minimum: 0, type: 'integer' }, type: 'array' },
+ hypothesis: { maxLength: 280, type: ['string', 'null'] },
instruction: { minLength: 1, type: 'string' },
title: { maxLength: 80, minLength: 1, type: 'string' },
},
- required: ['title', 'instruction', 'dependsOn'],
+ required: ['title', 'instruction', 'dependsOn', 'hypothesis'],
type: 'object',
},
maxItems: 5,
@@ -127,6 +128,7 @@ export const chainGoalDecompose = ({
'- Preserve every concrete URL, scope, constraint, and numeric threshold from the goal in whichever task it belongs to.',
'- Order tasks so that earlier ones produce what later ones consume.',
'- For each task, set dependsOn to the 0-based indices of the earlier tasks whose outputs it consumes; use [] for a task that can start immediately. A pipeline-shaped goal (gather → analyze → synthesize) must express those edges — do not mark every task independent — but never invent a dependency the task does not actually need.',
+ '- hypothesis marks a task as a candidate answer under test: one sentence stating what the direction bets on, which its result may confirm or refute, and from which later branches may be derived. Set it only for genuinely uncertain approaches that compete with or may replace an alternative. Certain delivery steps — gathering material, implementing a requested change, verifying a deliverable, writing a report — take null. Most goals have no hypothesis at all; never invent one to decorate an ordinary step.',
'- Write all fields in the language used by the goal.',
].join('\n'),
role: 'system',