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): add set-agent and restart commands (#19181)

Arvin Xue7c0a831f700
diff --git a/apps/cli/src/commands/goal.ts b/apps/cli/src/commands/goal.ts
index 9ab4e2fcf74..4cbed96774e 100644
--- a/apps/cli/src/commands/goal.ts
+++ b/apps/cli/src/commands/goal.ts
@@ -425,6 +425,28 @@ export function registerGoalCommand(program: Command) {
},
);
+ goal
+ .command('set-agent <id> <agent>')
+ .description('Hand the goal to a different responsible agent (unfinished tasks follow)')
+ .option('--goal-only', 'Only change the goal-level agent; leave existing tasks as assigned')
+ .action(async (id: string, agentId: string, options: { goalOnly?: boolean }) => {
+ const result = await (
+ await getTrpcClient()
+ ).goal.setAgent.mutate({ agentId, goalOnly: options.goalOnly, id });
+ log.info(result.message);
+ });
+
+ goal
+ .command('restart <id>')
+ .description('Start every unfinished task over (cancel stale runs, reset to backlog)')
+ .option('--agent <id>', 'Also hand the goal and restarted tasks to this agent')
+ .action(async (id: string, options: { agent?: string }) => {
+ const result = await (
+ await getTrpcClient()
+ ).goal.restart.mutate({ agentId: options.agent, id });
+ log.info(`${result.message}. Resume ticking with: lh goal run ${id}`);
+ });
+
goal
.command('decisions <id>')
.description('List durable decision gates')
diff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.ts
index 2ce52f6b872..e9985796ea8 100644
--- a/apps/server/src/routers/lambda/goal.ts
+++ b/apps/server/src/routers/lambda/goal.ts
@@ -390,6 +390,39 @@ export const goalRouter = router({
}
}),
+ /**
+ * Start every unfinished Task node over (cancel stale runs, back to
+ * `backlog`), optionally under a different agent, and kick the coordinator
+ * so the goal begins moving without a second gesture.
+ */
+ restart: goalWriteProcedure
+ .input(idInput.extend({ agentId: z.string().min(1).optional() }))
+ .mutation(async ({ ctx, input: { id, agentId } }) => {
+ try {
+ // `agent:update` says the member may change goals; it does not say
+ // whose. Without this any member could restart a colleague's visible
+ // goal β€” cancel its live runs and reset its tasks.
+ const goal = await ctx.goalModel.findById(id);
+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
+ assertWorkspaceRowManageable(ctx, goal.userId, 'goal');
+
+ const data = await ctx.goalService.restart(id, { agentId });
+ await scheduleGoalAdvance({
+ goalId: id,
+ trigger: 'restart',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+ return {
+ data,
+ message: `Restarted ${data.restartedTaskIds.length} task(s)`,
+ success: true,
+ };
+ } catch (error) {
+ mapGoalError(error, 'restart');
+ }
+ }),
+
/** Rebind which persisted verify criteria gate this goal's terminal acceptance. */
setAcceptanceCriteria: goalWriteProcedure
.input(idInput.extend({ criteriaIds: z.array(z.string()) }))
@@ -402,6 +435,34 @@ export const goalRouter = router({
}
}),
+ /**
+ * Hand the goal to a different responsible agent. Unfinished Tasks follow by
+ * default (`goalOnly` keeps them); Tasks mid-run switch on their next attempt.
+ */
+ setAgent: goalWriteProcedure
+ .input(idInput.extend({ agentId: z.string().min(1), goalOnly: z.boolean().optional() }))
+ .mutation(async ({ ctx, input: { id, agentId, goalOnly } }) => {
+ try {
+ // Same ownership rule as restart/delete: visibility is not
+ // manageability, so only the goal's owner may hand it to a new agent.
+ const goal = await ctx.goalModel.findById(id);
+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
+ assertWorkspaceRowManageable(ctx, goal.userId, 'goal');
+
+ const data = await ctx.goalService.setAgent(id, agentId, { goalOnly });
+ const reassigned = data.reassignedTaskIds.length;
+ return {
+ data,
+ message: reassigned
+ ? `Goal agent updated; ${reassigned} task(s) reassigned`
+ : 'Goal agent updated',
+ success: true,
+ };
+ } catch (error) {
+ mapGoalError(error, 'setAgent');
+ }
+ }),
+
setBudget: goalWriteProcedure
.input(
idInput.extend({
diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.ts
index 84aad492ba8..ecb786ca507 100644
--- a/apps/server/src/services/goal/index.test.ts
+++ b/apps/server/src/services/goal/index.test.ts
@@ -667,6 +667,94 @@ describe('GoalService', () => {
await expect(service.updateRequirement('goal_missing', 'x')).rejects.toThrow();
});
+ it('hands the goal and its unfinished tasks to a new agent', async () => {
+ await serverDB.insert(agents).values([
+ { id: 'agt_old', slug: 'agt-old', userId },
+ { id: 'agt_new', slug: 'agt-new', userId },
+ ]);
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({
+ agentId: 'agt_old',
+ tasks: ['Only task'],
+ title: 'Handover',
+ });
+ const created = await service.tick(graph.goal.id);
+ expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_old');
+
+ const handed = await service.setAgent(graph.goal.id, 'agt_new');
+
+ expect(handed.goal.agentId).toBe('agt_new');
+ expect(handed.reassignedTaskIds).toEqual([created.taskId]);
+ expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_new');
+
+ // A finished task keeps the agent that did the work, and `goalOnly` limits
+ // the change to future coordinator-created tasks.
+ await taskModel.updateStatus(created.taskId!, 'completed');
+ const back = await service.setAgent(graph.goal.id, 'agt_old');
+ expect(back.reassignedTaskIds).toEqual([]);
+ expect((await taskModel.findById(created.taskId!))?.assigneeAgentId).toBe('agt_new');
+
+ await expect(service.setAgent(graph.goal.id, 'agt_missing')).rejects.toThrow();
+ });
+
+ it('restarts unfinished tasks under a new agent and cancels the stale runs they hold', async () => {
+ const cancelSpy = vi.spyOn(TaskService.prototype, 'cancelTopic').mockResolvedValue();
+ await serverDB.insert(agents).values({ id: 'agt_restart', slug: 'agt-restart', userId });
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({ tasks: ['Stuck task'], title: 'Restartable' });
+ const created = await service.tick(graph.goal.id);
+ await serverDB.insert(topics).values({ id: 'tpc_restart', userId });
+ await new TaskTopicModel(serverDB, userId).add(created.taskId!, 'tpc_restart', { seq: 1 });
+ await new TaskTopicModel(serverDB, userId).updateStatus(
+ created.taskId!,
+ 'tpc_restart',
+ 'running',
+ );
+ await taskModel.update(created.taskId!, { error: 'lease expired', status: 'running' });
+
+ const result = await service.restart(graph.goal.id, { agentId: 'agt_restart' });
+
+ expect(cancelSpy).toHaveBeenCalledWith('tpc_restart');
+ expect(result.goal.agentId).toBe('agt_restart');
+ expect(result.restartedTaskIds).toEqual([created.taskId]);
+ expect(await taskModel.findById(created.taskId!)).toMatchObject({
+ assigneeAgentId: 'agt_restart',
+ error: null,
+ status: 'backlog',
+ });
+
+ // "Start over" on a parked goal must begin ticking again without a second
+ // Resume gesture.
+ await service.pause(graph.goal.id);
+ const resumed = await service.restart(graph.goal.id);
+ expect(resumed.goal.status).not.toBe('paused');
+ });
+
+ it('cancels the failure gate a restart supersedes so the goal starts moving again', async () => {
+ // A restarted task's pending recovery gate is answered by the restart
+ // itself. Left pending, it keeps winning the coordinator's
+ // pending-decision branch and the goal sits waiting_human with every task
+ // freshly reset.
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({ tasks: ['Risky task'], title: 'Restart clears gate' });
+ const created = await service.tick(graph.goal.id);
+ await taskModel.updateStatus(created.taskId!, 'paused', { error: 'Verifier rejected output' });
+ expect((await service.tick(graph.goal.id)).outcome).toBe('waiting_human');
+
+ const result = await service.restart(graph.goal.id);
+
+ expect(result.restartedTaskIds).toEqual([created.taskId]);
+ const after = await service.graph(graph.goal.id);
+ expect(after.decisions[0].status).toBe('canceled');
+ // The freed coordinator dispatches the reset task instead of re-parking.
+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);
+ const next = await service.tick(graph.goal.id);
+ expect(next.outcome).not.toBe('waiting_human');
+ });
+
it('leaves a deliberately paused goal paused when its budget changes', async () => {
// Nothing distinguishes a user pause from a budget pause on the row, so the
// reopen is limited to goals whose budget was actually binding.
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index 665f6dd90ad..850a427c426 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -859,6 +859,130 @@ export class GoalService {
return goal;
};
+ /**
+ * Hand the goal to a different responsible agent. Every Task the
+ * coordinator creates from here on is assigned to the new agent, and β€”
+ * unless the caller opts out β€” the graph's unfinished Tasks move with it.
+ * A Task mid-run keeps its current operation; the reassignment takes effect
+ * on its next dispatched attempt, because `runTask` reads the assignee at
+ * dispatch time.
+ */
+ setAgent = async (
+ goalId: string,
+ agentId: string,
+ options?: { goalOnly?: boolean },
+ ): Promise<{ goal: GoalItem; reassignedTaskIds: string[] }> => {
+ await assertAgentUsableBy(this.db, agentId, {
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ });
+ const goal = await this.goalModel.update(goalId, { agentId });
+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
+
+ const reassignedTaskIds: string[] = [];
+ if (!options?.goalOnly) {
+ // Snapshot the graph AFTER the goal row moved: a task the coordinator
+ // binds later inherits the new agent from the goal, and a task bound
+ // before is in this snapshot β€” so no concurrently created task can slip
+ // through the handoff still pointing at the previous agent.
+ const graph = await this.requireGraph(goalId);
+ const taskIds = graph.nodes.flatMap((node) => (node.taskId ? [node.taskId] : []));
+ for (const task of await this.taskModel.findByIds(taskIds)) {
+ if (task.status === 'completed' || task.status === 'canceled') continue;
+ if (task.assigneeAgentId === agentId) continue;
+ await this.taskModel.update(task.id, { assigneeAgentId: agentId });
+ reassignedTaskIds.push(task.id);
+ }
+ }
+ return { goal, reassignedTaskIds };
+ };
+
+ /**
+ * Start every unfinished Task node over: interrupt the run it may still be
+ * holding, clear the failure it may be parked on, and return the Task to
+ * `backlog` so the next coordinator tick dispatches it afresh. Optionally
+ * hands the goal (and the restarted Tasks) to a different agent in the same
+ * gesture. Resolved nodes and their completed Tasks are left untouched.
+ */
+ restart = async (
+ goalId: string,
+ options?: { agentId?: string },
+ ): Promise<{ goal: GoalItem; restartedTaskIds: string[] }> => {
+ if (options?.agentId) {
+ await assertAgentUsableBy(this.db, options.agentId, {
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ });
+ }
+ const graph = await this.requireGraph(goalId);
+
+ const unfinishedNodes = graph.nodes.filter(
+ (node) => node.kind === 'task' && node.taskId && !TERMINAL_NODE_STATUSES.has(node.status),
+ );
+ const unfinishedNodeIds = new Set(unfinishedNodes.map((node) => node.id));
+ const unfinishedTaskIds = unfinishedNodes.flatMap((node) => (node.taskId ? [node.taskId] : []));
+
+ // A restarted task's pending failure gate is answered by the restart
+ // itself. Left pending, it would keep winning the coordinator's
+ // pending-decision branch and the goal would sit `waiting_human` with
+ // every task freshly reset. Gates on untouched nodes keep parking the
+ // goal β€” they ask something this restart does not answer.
+ // Gate edges run task-node β†’ decision-node (see openFailureDecision).
+ const staleGates = graph.decisions.filter(
+ (decision) =>
+ decision.status === 'pending' &&
+ graph.edges.some(
+ (edge) =>
+ edge.kind === 'leads_to' &&
+ edge.targetNodeId === decision.nodeId &&
+ unfinishedNodeIds.has(edge.sourceNodeId),
+ ),
+ );
+ for (const gate of staleGates) {
+ await this.graphModel.cancelDecision(goalId, gate.id, 'Superseded by goal restart');
+ }
+
+ const restartedTaskIds: string[] = [];
+ if (unfinishedTaskIds.length > 0) {
+ const runningTopics = await this.taskTopicModel.findRunningByTaskIds(unfinishedTaskIds);
+ for (const topic of runningTopics) {
+ if (topic.topicId) await this.taskService.cancelTopic(topic.topicId);
+ }
+ // Re-read after the cancels and reset via compare-and-swap: a coordinator
+ // tick dispatching concurrently moves the row between our read and the
+ // write, the CAS loses, and that task is skipped instead of yanked out
+ // from under a freshly claimed run (which would double-dispatch it).
+ for (const task of await this.taskModel.findByIds(unfinishedTaskIds)) {
+ if (task.status === 'completed') continue;
+ const reset = await this.taskModel.updateStatusIfCurrent(task.id, task.status, 'backlog', {
+ error: null,
+ });
+ if (!reset) continue;
+ if (options?.agentId) {
+ await this.taskModel.update(task.id, { assigneeAgentId: options.agentId });
+ }
+ restartedTaskIds.push(task.id);
+ }
+ }
+
+ // The handoff lands only after the interrupts succeeded β€” a cancelTopic
+ // failure above must not leave the goal pointing at the new agent while
+ // its tasks and live runs still belong to the old one.
+ let goal = graph.goal;
+ if (options?.agentId) {
+ const updated = await this.goalModel.update(goalId, { agentId: options.agentId });
+ if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });
+ goal = updated;
+ }
+
+ // A restart is an explicit "start over": a goal parked by a budget stop or
+ // a manual pause must begin ticking again without a second gesture.
+ if (goal.status === 'paused') {
+ goal = (await this.resume(goalId)) ?? goal;
+ }
+ return { goal, restartedTaskIds };
+ };
+
setBudget = async (
goalId: string,
budget: {
diff --git a/packages/agent-tracing/src/goal/types.ts b/packages/agent-tracing/src/goal/types.ts
index d2ca8f83e39..ae9284a1b61 100644
--- a/packages/agent-tracing/src/goal/types.ts
+++ b/packages/agent-tracing/src/goal/types.ts
@@ -21,6 +21,7 @@ export type GoalAdvanceTrigger =
| 'settle'
| 'sweep'
| 'resume'
+ | 'restart'
| 'budget'
| 'manual'
/** A measurement landed β€” the goal moves on observation, not only on work. */
diff --git a/packages/database/src/models/goalGraph.ts b/packages/database/src/models/goalGraph.ts
index 767518d4e6b..b8ffc3b42d9 100644
--- a/packages/database/src/models/goalGraph.ts
+++ b/packages/database/src/models/goalGraph.ts
@@ -661,4 +661,47 @@ export class GoalGraphModel {
});
return decision;
});
+
+ /**
+ * Cancel a still-pending decision whose question a later action made moot β€”
+ * nobody picked an option, so this is distinct from `resolveDecision`. The
+ * decision node retires with it; a canceled gate must not keep parking the
+ * goal on the pending-decision branch.
+ */
+ cancelDecision = async (goalId: string, decisionId: string, reason?: string) =>
+ this.db.transaction(async (tx) => {
+ if (!(await this.ownedGoal(goalId, tx))) return undefined;
+ const [ownedDecision] = await tx
+ .select({ id: goalNodeDecisions.id })
+ .from(goalNodeDecisions)
+ .innerJoin(goalNodes, eq(goalNodeDecisions.nodeId, goalNodes.id))
+ .where(
+ and(
+ eq(goalNodeDecisions.id, decisionId),
+ eq(goalNodeDecisions.status, 'pending'),
+ eq(goalNodes.goalId, goalId),
+ ),
+ )
+ .limit(1);
+ if (!ownedDecision) return undefined;
+ const [decision] = await tx
+ .update(goalNodeDecisions)
+ .set({ canceledAt: new Date(), status: 'canceled', updatedAt: new Date() })
+ .where(
+ and(eq(goalNodeDecisions.id, ownedDecision.id), eq(goalNodeDecisions.status, 'pending')),
+ )
+ .returning();
+ if (!decision) return undefined;
+ await tx
+ .update(goalNodes)
+ .set({ status: 'retired', updatedAt: new Date() })
+ .where(eq(goalNodes.id, decision.nodeId));
+ await this.appendEvent(tx, goalId, {
+ entityId: decision.id,
+ entityType: 'decision',
+ eventType: 'retired',
+ reason,
+ });
+ return decision;
+ });
}