π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(goal): retire stray task nodes from the CLI (#20166)
Arvin Xuc9b5b76ddff1
diff --git a/apps/cli/src/commands/goal.test.ts b/apps/cli/src/commands/goal.test.tsindex 8ef9ad66cff..38a6ec298ff 100644--- a/apps/cli/src/commands/goal.test.ts+++ b/apps/cli/src/commands/goal.test.ts@@ -17,6 +17,7 @@ const { mockClient } = vi.hoisted(() => ({submitReport: { mutate: vi.fn() },graph: { query: vi.fn() },resume: { mutate: vi.fn() },+ retireNodes: { mutate: vi.fn() },setBudget: { mutate: vi.fn() },supervision: { query: vi.fn() },tick: { mutate: vi.fn() },@@ -639,3 +640,40 @@ describe('goal delete', () => {expect(mockClient.goal.delete.mutate).not.toHaveBeenCalled();});});++describe('goal retire', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.spyOn(log, 'info').mockImplementation(() => {});+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('retires every listed node in one call', async () => {+ mockClient.goal.retireNodes.mutate.mockResolvedValue({+ message: 'Retired 2 node(s)',+ success: true,+ });++ await createProgram().parseAsync([+ 'node',+ 'test',+ 'goal',+ 'retire',+ 'goal-1',+ 'node-a',+ 'node-b',+ '--reason',+ 'duplicate branch',+ ]);++ expect(mockClient.goal.retireNodes.mutate).toHaveBeenCalledWith({+ id: 'goal-1',+ nodeIds: ['node-a', 'node-b'],+ reason: 'duplicate branch',+ });+ expect(log.info).toHaveBeenCalledWith('Retired 2 node(s)');+ });+});diff --git a/apps/cli/src/commands/goal.ts b/apps/cli/src/commands/goal.tsindex 9bab24b733f..58fea72b3e4 100644--- a/apps/cli/src/commands/goal.ts+++ b/apps/cli/src/commands/goal.ts@@ -728,6 +728,19 @@ export function registerGoalCommand(program: Command) {log.info(result.message);});+ goal+ .command('retire <id> <node-ids...>')+ .description(+ 'Retire task nodes that should not run; unfinished tasks depending on them must be retired together',+ )+ .option('--reason <text>', 'Why the nodes are retired')+ .action(async (id: string, nodeIds: string[], options) => {+ const result = await (+ await getTrpcClient()+ ).goal.retireNodes.mutate({ id, nodeIds, reason: options.reason });+ log.info(result.message);+ });+goal.command('add-node <id> <kind> <title>').description('Add a question, experiment container, task, finding, or decision node')diff --git a/apps/server/src/routers/lambda/__tests__/goal.metricCriteria.test.ts b/apps/server/src/routers/lambda/__tests__/goal.metricCriteria.test.tsindex 1ce6e3d1caf..9db602d2a8b 100644--- a/apps/server/src/routers/lambda/__tests__/goal.metricCriteria.test.ts+++ b/apps/server/src/routers/lambda/__tests__/goal.metricCriteria.test.ts@@ -25,12 +25,14 @@ const mockCreate = vi.fn();const mockSetMetricCriteria = vi.fn();const mockRecordObservation = vi.fn();const mockFindById = vi.fn();+const mockRetireNodes = vi.fn();vi.mock('@/server/services/goal', () => ({GoalService: vi.fn(function () {return {create: mockCreate,recordObservation: mockRecordObservation,+ retireNodes: mockRetireNodes,setMetricCriteria: mockSetMetricCriteria,};}),@@ -152,4 +154,57 @@ describe('goalRouter numeric acceptance', () => {expect(result.data).not.toHaveProperty('shouldAdvance');});});++ describe('retireNodes', () => {+ const nodeId = '00000000-0000-4000-8000-000000000001';++ it("refuses a workspace member retiring a colleague's goal nodes", async () => {+ // Retiring cancels the nodes' Tasks and recovery gates, so it is held to+ // the same creator-or-owner rule as restart and delete.+ mockFindById.mockResolvedValue({ id: 'goal_1', userId: 'colleague' });+ const memberCaller = goalRouter.createCaller({+ ...ctx,+ workspaceId: 'ws-1',+ workspaceRole: 'member',+ });++ await expect(memberCaller.retireNodes({ id: 'goal_1', nodeIds: [nodeId] })).rejects.toThrow(+ /Only the creator or a workspace owner/,+ );+ expect(mockRetireNodes).not.toHaveBeenCalled();+ expect(mockScheduleGoalAdvance).not.toHaveBeenCalled();+ });++ it('lets the creator retire nodes and wakes the coordinator', async () => {+ mockRetireNodes.mockResolvedValue({ retiredNodeIds: [nodeId] });+ const memberCaller = goalRouter.createCaller({+ ...ctx,+ workspaceId: 'ws-1',+ workspaceRole: 'member',+ });++ await memberCaller.retireNodes({ id: 'goal_1', nodeIds: [nodeId] });++ expect(mockRetireNodes).toHaveBeenCalledWith('goal_1', [nodeId], undefined);+ expect(mockScheduleGoalAdvance).toHaveBeenCalledWith(+ expect.objectContaining({ goalId: 'goal_1' }),+ );+ });++ it("advances as the goal's owner when a workspace owner retires a colleague's nodes", async () => {+ mockFindById.mockResolvedValue({ id: 'goal_1', userId: 'colleague' });+ mockRetireNodes.mockResolvedValue({ retiredNodeIds: [nodeId] });+ const ownerCaller = goalRouter.createCaller({+ ...ctx,+ workspaceId: 'ws-1',+ workspaceRole: 'owner',+ });++ await ownerCaller.retireNodes({ id: 'goal_1', nodeIds: [nodeId] });++ expect(mockScheduleGoalAdvance).toHaveBeenCalledWith(+ expect.objectContaining({ goalId: 'goal_1', userId: 'colleague', workspaceId: 'ws-1' }),+ );+ });+ });});diff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.tsindex 9300815cfb2..c0d763e6ebb 100644--- a/apps/server/src/routers/lambda/goal.ts+++ b/apps/server/src/routers/lambda/goal.ts@@ -490,6 +490,38 @@ export const goalRouter = router({}}),+ retireNodes: goalWriteProcedure+ .input(+ idInput.extend({+ nodeIds: z.array(z.string().uuid()).min(1),+ reason: z.string().optional(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ try {+ // Same ownership rule as restart/delete: retiring cancels the nodes'+ // Tasks and recovery gates, so visibility is not manageability.+ const goal = await ctx.goalModel.findById(input.id);+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ assertWorkspaceRowManageable(ctx, goal.userId, 'goal');++ const data = await ctx.goalService.retireNodes(input.id, input.nodeIds, input.reason);+ // Retiring can unpark the goal or clear the last unfinished task. Advance+ // as the goal's owner: a workspace owner retiring a colleague's nodes+ // cannot see that colleague's private Tasks, so an advance under the+ // caller would read their bound nodes as `missing_task`.+ await scheduleGoalAdvance({+ goalId: input.id,+ trigger: 'manual',+ userId: goal.userId,+ workspaceId: ctx.workspaceId ?? undefined,+ });+ return { data, message: `Retired ${data.retiredNodeIds.length} node(s)`, success: true };+ } catch (error) {+ mapGoalError(error, 'retireNodes');+ }+ }),+/** Declare or clear the numeric clauses gating this goal's acceptance. */setMetricCriteria: goalWriteProcedure.input(diff --git a/apps/server/src/services/goal/decideNextMove.ts b/apps/server/src/services/goal/decideNextMove.tsindex 0ef7aa0c6a5..25d2da64174 100644--- a/apps/server/src/services/goal/decideNextMove.ts+++ b/apps/server/src/services/goal/decideNextMove.ts@@ -150,6 +150,13 @@ export const frontierNeedsBudget = (*/export const MEASURED_ACCEPTANCE_PAUSE_REASON = 'Measured acceptance not met';+/**+ * Reason recorded when the coordinator parks a goal because nothing on the+ * frontier can run. Shared so a graph edit that removes the blocker (node+ * retirement) can recognise this park and lift it.+ */+export const NO_FRONTIER_PAUSE_REASON = 'no eligible task to advance';+/** Evaluate one numeric clause. Kept beside the gate that consumes it. */export const compareMetric = (rawValue: number,diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.tsindex 25a5f358fa2..e25cc128712 100644--- a/apps/server/src/services/goal/index.test.ts+++ b/apps/server/src/services/goal/index.test.ts@@ -29,6 +29,7 @@ import {taskTopics,topics,users,+ workspaces,} from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime/AgentRuntimeCoordinator';@@ -1096,6 +1097,204 @@ describe('GoalService', () => {expect(next.outcome).not.toBe('waiting_human');});+ it('retires a stray node only together with the unfinished tasks depending on it', async () => {+ // A duplicated plan branch never gets a Task, so nothing else ever closes it+ // and the goal can never reach acceptance.+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['First', 'Second', 'Keep'], title: 'Duplicates' });+ const [first, second, keep] = ['First', 'Second', 'Keep'].map((title) =>+ graph.nodes.find((node) => node.kind === 'task' && node.title === title)!,+ );+ await service.addEdge(graph.goal.id, second.id, first.id, 'depends_on');++ await expect(service.retireNodes(graph.goal.id, [first.id])).rejects.toThrow(second.id);++ const result = await service.retireNodes(graph.goal.id, [first.id, second.id], 'duplicate');++ expect(result.retiredNodeIds.sort()).toEqual([first.id, second.id].sort());+ const after = await service.graph(graph.goal.id);+ const status = (id: string) => after.nodes.find((node) => node.id === id)?.status;+ expect(status(first.id)).toBe('retired');+ expect(status(second.id)).toBe('retired');+ expect(status(keep.id)).not.toBe('retired');+ });++ it('retiring a dispatched node cancels its task and the gate parking the goal', async () => {+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({ tasks: ['Canceled elsewhere'], title: 'Stray gate' });+ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'paused', { error: 'Task canceled' });+ expect((await service.tick(graph.goal.id)).outcome).toBe('waiting_human');++ await service.retireNodes(graph.goal.id, [created.nodeId!]);++ expect((await taskModel.findById(created.taskId!))?.status).toBe('canceled');+ const after = await service.graph(graph.goal.id);+ expect(after.decisions[0].status).toBe('canceled');+ expect(after.goal.status).toBe('running');+ });++ it('retiring a node fences it against a coordinator still creating its task', async () => {+ const service = new GoalService(serverDB, userId);+ const graphModel = new GoalGraphModel(serverDB, userId);+ const graph = await service.create({ tasks: ['Stray', 'Keep'], title: 'Retire race' });+ const stray = graph.nodes.find((node) => node.kind === 'task' && node.title === 'Stray')!;+ // A tick has claimed the node and is creating its Task when retirement lands.+ expect(await graphModel.claimTaskNode(graph.goal.id, stray.id, new Date(0))).toBeDefined();++ await service.retireNodes(graph.goal.id, [stray.id]);++ const lateTask = await new TaskModel(serverDB, userId).create({ instruction: 'Late' });+ expect(await graphModel.bindTask(graph.goal.id, stray.id, lateTask.id)).toBeUndefined();+ const after = await service.graph(graph.goal.id);+ expect(after.nodes.find((node) => node.id === stray.id)?.status).toBe('retired');+ });++ it("stops a colleague's private task when a workspace owner retires its node", async () => {+ // The coordinator runs as the goal's owner, so its Tasks can be private to+ // that colleague. An owner retiring the node must still stop them β reads+ // under the owner's own visibility would silently miss them.+ const workspaceId = 'goal-retire-private-ws';+ const ownerId = 'goal-retire-private-owner';+ await serverDB.insert(users).values({ id: ownerId }).onConflictDoNothing();+ await serverDB+ .insert(workspaces)+ .values({ id: workspaceId, name: workspaceId, primaryOwnerId: ownerId, slug: workspaceId })+ .onConflictDoNothing();+ const colleague = new GoalService(serverDB, userId, workspaceId);+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const graph = await colleague.create({ tasks: ['Private', 'Keep'], title: 'Private retire' });+ const created = await colleague.tick(graph.goal.id);+ await serverDB+ .update(tasks)+ .set({ status: 'running', visibility: 'private' })+ .where(eq(tasks.id, created.taskId!));+ expect(+ await new TaskModel(serverDB, ownerId, workspaceId).findById(created.taskId!),+ ).toBeFalsy();++ await new GoalService(serverDB, ownerId, workspaceId).retireNodes(graph.goal.id, [+ created.nodeId!,+ ]);++ const [task] = await serverDB.select().from(tasks).where(eq(tasks.id, created.taskId!));+ expect(task.status).toBe('canceled');+ });++ it('cancels a running task before looking for its runs, fencing a run still being dispatched', async () => {+ // A runner that already flipped the Task to `running` but has not recorded+ // its topic yet is invisible to the run lookup. It checks the Task's status+ // under the row lock before recording, so the cancellation must already be+ // committed by the time retirement looks for runs to stop.+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({ tasks: ['Dispatching', 'Keep'], title: 'Fence runs' });+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'running');+ const statusAtLookup: (string | undefined)[] = [];+ const original = TaskTopicModel.prototype.findRunningByTaskIds;+ vi.spyOn(TaskTopicModel.prototype, 'findRunningByTaskIds').mockImplementation(async function (+ this: TaskTopicModel,+ ids: string[],+ ) {+ statusAtLookup.push((await taskModel.findById(created.taskId!))?.status);+ return original.call(this, ids);+ });++ await service.retireNodes(graph.goal.id, [created.nodeId!]);++ expect(statusAtLookup).toEqual(['canceled']);+ expect((await taskModel.findById(created.taskId!))?.status).toBe('canceled');+ });++ it('lets an interrupted retirement be finished by retrying it', async () => {+ // The fence lands before the run is stopped; when stopping it cannot be+ // confirmed the call fails with the node already retired. A retry must+ // still stop the task instead of rejecting the node as terminal.+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({ tasks: ['Running', 'Keep'], title: 'Retry retire' });+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const created = await service.tick(graph.goal.id);+ vi.spyOn(TaskTopicModel.prototype, 'findRunningByTaskIds').mockResolvedValue([+ { taskId: created.taskId!, topicId: 'tpc_running' },+ ] as never);+ const cancelTopic = vi+ .spyOn(TaskService.prototype, 'cancelTopic')+ .mockRejectedValueOnce(new Error('interrupt not confirmed'))+ .mockResolvedValue(undefined as never);++ await expect(service.retireNodes(graph.goal.id, [created.nodeId!])).rejects.toThrow(+ 'interrupt not confirmed',+ );+ expect(+ (await service.graph(graph.goal.id)).nodes.find((node) => node.id === created.nodeId)?.status,+ ).toBe('retired');++ const retried = await service.retireNodes(graph.goal.id, [created.nodeId!]);++ expect(retried.retiredNodeIds).toEqual([created.nodeId]);+ expect(cancelTopic).toHaveBeenCalledTimes(2);+ expect((await taskModel.findById(created.taskId!))?.status).toBe('canceled');+ });++ it('discards a stale tick outcome for a node retired while it ran', async () => {+ const service = new GoalService(serverDB, userId);+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const graph = await service.create({ tasks: ['Stray', 'Keep'], title: 'Stale tick' });+ const created = await service.tick(graph.goal.id);+ // The coordinator loaded this snapshot before the retirement landed.+ const stale = await service.graph(graph.goal.id);+ await service.retireNodes(graph.goal.id, [created.nodeId!]);++ const result = await (service as any).consumeCompletedTask(+ stale,+ created.nodeId!,+ created.taskId!,+ );++ expect(result.outcome).toBe('no_progress');+ const after = await service.graph(graph.goal.id);+ expect(after.nodes.find((node) => node.id === created.nodeId)?.status).toBe('retired');+ expect(after.nodes.some((node) => node.kind === 'finding')).toBe(false);+ });++ it('reopens a goal parked by no_frontier once the blocking nodes are retired', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['A', 'B', 'Keep'], title: 'Deadlocked branch' });+ const [a, b] = ['A', 'B'].map((title) =>+ graph.nodes.find((node) => node.kind === 'task' && node.title === title)!,+ );+ const graphModel = new GoalGraphModel(serverDB, userId);+ await graphModel.createEdge(graph.goal.id, a.id, b.id, 'depends_on');+ await graphModel.createEdge(graph.goal.id, b.id, a.id, 'depends_on');+ const keep = graph.nodes.find((node) => node.kind === 'task' && node.title === 'Keep')!;+ await graphModel.updateNodeStatus(graph.goal.id, keep.id, 'resolved');+ await service.tick(graph.goal.id); // deadlock β no_frontier β paused+ expect((await service.graph(graph.goal.id)).goal.status).toBe('paused');++ await service.retireNodes(graph.goal.id, [a.id, b.id]);++ expect((await service.graph(graph.goal.id)).goal.status).toBe('running');+ });++ it('leaves a user-paused goal paused when nodes are retired', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['A', 'B'], title: 'Paused by a person' });+ const [a, b] = graph.nodes.filter((node) => node.kind === 'task');+ const graphModel = new GoalGraphModel(serverDB, userId);+ await graphModel.createEdge(graph.goal.id, a.id, b.id, 'depends_on');+ await graphModel.createEdge(graph.goal.id, b.id, a.id, 'depends_on');+ await service.tick(graph.goal.id); // no_frontier park+ await service.pause(graph.goal.id); // the person takes the pause over++ await service.retireNodes(graph.goal.id, [a.id, b.id]);++ expect((await service.graph(graph.goal.id)).goal.status).toBe('paused');+ });+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.tsindex 8cb011dcd18..f40091b2244 100644--- a/apps/server/src/services/goal/index.ts+++ b/apps/server/src/services/goal/index.ts@@ -61,6 +61,7 @@ import {LEASE_EXPIRED_ERROR,MEASURED_ACCEPTANCE_PAUSE_REASON,needsMetricCriteria,+ NO_FRONTIER_PAUSE_REASON,selectFrontier,TERMINAL_NODE_STATUSES,} from './decideNextMove';@@ -1311,6 +1312,176 @@ export class GoalService {return { goal, restartedTaskIds };};+ /**+ * Task access under the goal owner's principal β the identity the goal's+ * coordinator creates and runs its Tasks as. Only for acting on Tasks already+ * bound to this goal's nodes, after the caller's right to manage the goal has+ * been checked.+ */+ private goalOwnerTaskScope = (goal: { userId: string }) =>+ goal.userId === this.userId+ ? {+ taskModel: this.taskModel,+ taskService: this.taskService,+ taskTopicModel: this.taskTopicModel,+ }+ : {+ taskModel: new TaskModel(this.db, goal.userId, this.workspaceId),+ taskService: new TaskService(this.db, goal.userId, this.workspaceId),+ taskTopicModel: new TaskTopicModel(this.db, goal.userId, this.workspaceId),+ };++ /**+ * Retire Task nodes a person no longer wants run β a duplicated plan branch,+ * work that landed elsewhere. Without this a stray node that never got a Task+ * stays unfinished forever and the coordinator can never reach acceptance.+ *+ * Nodes are retired as one set: any unfinished Task still depending on a node+ * in the set must be in the set too, otherwise it would wait on a+ * prerequisite that will never resolve.+ */+ retireNodes = async (+ goalId: string,+ nodeIds: string[],+ reason?: string,+ ): Promise<{ retiredNodeIds: string[] }> => {+ const graph = await this.requireGraph(goalId);+ const targetIds = new Set(nodeIds);++ const targets = [...targetIds].map((nodeId) => {+ const node = graph.nodes.find((item) => item.id === nodeId);+ if (!node) throw new TRPCError({ code: 'NOT_FOUND', message: `Node ${nodeId} not found` });+ if (node.kind !== 'task') {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: `Node ${nodeId} is a ${node.kind}; only task nodes can be retired`,+ });+ }+ // An already-retired node is accepted so an interrupted retirement (its+ // fence landed, stopping the run did not) can be finished by retrying.+ if (node.status !== 'retired' && TERMINAL_NODE_STATUSES.has(node.status)) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: `Node ${nodeId} is already ${node.status}`,+ });+ }+ // Retiring the terminal acceptance fails the whole Goal; that verdict+ // belongs to its decision gate, not to a graph edit.+ if (node.title === GOAL_ACCEPTANCE_TASK_TITLE) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'The Goal acceptance task cannot be retired',+ });+ }+ return node;+ });++ const strandedIds = graph.edges+ .filter(+ (edge) =>+ edge.kind === 'depends_on' &&+ targetIds.has(edge.targetNodeId) &&+ !targetIds.has(edge.sourceNodeId),+ )+ .map((edge) => graph.nodes.find((node) => node.id === edge.sourceNodeId))+ .filter(+ (node): node is NonNullable<typeof node> =>+ !!node && node.kind === 'task' && !TERMINAL_NODE_STATUSES.has(node.status),+ )+ .map((node) => node.id);+ if (strandedIds.length > 0) {+ throw new TRPCError({+ code: 'CONFLICT',+ message: `Unfinished tasks depend on these nodes; retire them together: ${[...new Set(strandedIds)].join(', ')}`,+ });+ }++ // Fence the nodes BEFORE looking for their Tasks. The snapshot above can+ // miss a Task a concurrent tick is creating for a proposed node; once the+ // node reads `retired`, `bindTask` (which only binds an `active` node) can+ // no longer attach that Task, and the creator discards it.+ for (const node of targets) {+ if (node.status === 'retired') continue;+ await this.graphModel.updateNodeStatus(goalId, node.id, 'retired', reason);+ }++ // Stop what the nodes are still running, so a retired node cannot keep+ // spending or deliver into the Goal afterwards. Bound Tasks are read after+ // the fence so a Task bound just before it is included.+ const fenced = await this.requireGraph(goalId);+ const taskIds = fenced.nodes.flatMap((node) =>+ targetIds.has(node.id) && node.taskId ? [node.taskId] : [],+ );+ if (taskIds.length > 0) {+ // The caller may be a workspace owner retiring a colleague's goal (the+ // router authorizes that). The nodes' Tasks were created by the goal's+ // coordinator, which runs as the goal's owner β and may be `private`,+ // inherited from that owner's private agent β so reads under the caller's+ // visibility would miss them and leave them running. Stop them under the+ // goal owner's principal instead, limited to the Tasks bound to the nodes+ // being retired.+ const { taskModel, taskService, taskTopicModel } = this.goalOwnerTaskScope(fenced.goal);+ const cancelTasks = async () => {+ for (const id of taskIds) {+ // CAS against the status just read; a runner flipping the Task to+ // `running` in between makes it miss, so re-read and try again.+ for (let attempt = 0; attempt < 3; attempt++) {+ const [task] = await taskModel.findByIds([id]);+ if (!task || ['canceled', 'completed', 'failed'].includes(task.status)) break;+ if (await taskModel.updateStatusIfCurrent(id, task.status, 'canceled')) break;+ }+ }+ };+ // Cancel the Tasks FIRST: that is the fence a run still being dispatched+ // checks under the Task's row lock before recording its operation, so a+ // run started from here on stops itself (TaskRunnerService.runTask).+ // Runs recorded before the fence are then found and stopped below.+ await cancelTasks();+ for (const topic of await taskTopicModel.findRunningByTaskIds(taskIds)) {+ if (topic.topicId) await taskService.cancelTopic(topic.topicId);+ }+ // `cancelTopic` parks its Task as `paused`; settle them back to canceled.+ await cancelTasks();+ }++ // A pending recovery gate on a retired node asks a question nobody needs+ // answered any more; left pending it keeps the Goal parked in review.+ for (const decision of fenced.decisions) {+ if (decision.status !== 'pending') continue;+ const gatedByTarget = fenced.edges.some(+ (edge) =>+ edge.kind === 'leads_to' &&+ edge.targetNodeId === decision.nodeId &&+ targetIds.has(edge.sourceNodeId),+ );+ if (gatedByTarget) {+ await this.graphModel.cancelDecision(goalId, decision.id, 'Superseded by node retirement');+ }+ }++ // Reopen a goal the coordinator parked because of what was just retired:+ // `review` held by the retired node's gate, or `paused` by `no_frontier`+ // (the stray branch left nothing runnable). A pause somebody chose β or+ // one the coordinator took for another reason, like a budget β is left.+ const after = await this.requireGraph(goalId);+ const lastTransition = after.events.find((event) => event.entityType === 'goal');+ const parkedOnNoFrontier =+ after.goal.status === 'paused' &&+ !after.goal.config?.pausedBy &&+ lastTransition?.actorType !== 'user' &&+ lastTransition?.reason === NO_FRONTIER_PAUSE_REASON;+ if (after.goal.status === 'review' || parkedOnNoFrontier) {+ const hasPendingDecision = after.decisions.some((decision) => decision.status === 'pending');+ if (!hasPendingDecision) {+ await this.transitionStatus(after.goal, 'running', 'nodes retired by user', 'user');+ } else if (parkedOnNoFrontier) {+ await this.transitionStatus(after.goal, 'review', 'nodes retired by user', 'user');+ }+ }++ return { retiredNodeIds: targets.map((node) => node.id) };+ };+setBudget = async (goalId: string,budget: {@@ -1800,7 +1971,7 @@ export class GoalService {// sweep's window. A `running` goal that always reports `no_progress` is// picked by every scan forever, and enough of them starve every other// stalled goal out of the newest-first limit.- await this.transitionStatus(graph.goal, 'paused', 'no eligible task to advance');+ await this.transitionStatus(graph.goal, 'paused', NO_FRONTIER_PAUSE_REASON);effects.push({ type: 'goal_status', detail: 'paused' });return observe({ goalId, message: move.message, outcome: move.outcome });}@@ -3000,6 +3171,18 @@ export class GoalService {taskId: string,effects: GoalAdvanceEffect[] = [],): Promise<GoalTickResult> => {+ // `graph` can predate a retirement that landed while this tick ran. A+ // retired node's late output must not enter the Goal as a finding or+ // deliverable (and `updateNodeStatus` refuses to revive the node).+ if ((await this.coordinatorGraph.getNodeStatus(graph.goal.id, nodeId)) === 'retired') {+ return {+ goalId: graph.goal.id,+ message: 'Node was retired; the task outcome is discarded',+ nodeId,+ outcome: 'no_progress',+ taskId,+ };+ }const existingFinding = graph.edges.some((edge) => edge.sourceNodeId === nodeId && edge.kind === 'produces',);diff --git a/apps/server/src/services/taskRunner/index.ts b/apps/server/src/services/taskRunner/index.tsindex 564f5de5456..d52d569b601 100644--- a/apps/server/src/services/taskRunner/index.ts+++ b/apps/server/src/services/taskRunner/index.ts@@ -303,12 +303,17 @@ export class TaskRunnerService {if (result.topicId) {const topicId = result.topicId;// Record the run under the task's row lock (see TaskService.deleteTask).- // If the task was deleted while this run was being dispatched, nobody- // is left to stop it β stop it here instead of orphaning it.+ // If the task was deleted β or canceled, e.g. by a Goal retiring its+ // node β while this run was being dispatched, whoever did it found no+ // topic to stop yet. Nobody else will stop it, so stop it here instead+ // of recording an operation that keeps running behind the cancellation.const recorded = await this.db.transaction(async (tx) => {const taskModel = new TaskModel(tx, this.userId, this.workspaceId);const taskTopicModel = new TaskTopicModel(tx, this.userId, this.workspaceId);- if (!(await taskModel.lockForUpdate(task.id))) return false;+ if (!(await taskModel.lockForUpdate(task.id))) return 'deleted' as const;+ if ((await taskModel.findById(task.id))?.status === 'canceled') {+ return 'canceled' as const;+ }if (continueTopicId) {await taskTopicModel.updateStatus(task.id, continueTopicId, 'running');await taskTopicModel.updateOperationId(task.id, continueTopicId, result.operationId);@@ -322,9 +327,9 @@ export class TaskRunnerService {trigger,});}- return true;+ return 'recorded' as const;});- if (!recorded) {+ if (recorded !== 'recorded') {const stop = await aiAgentService.interruptTask({ operationId: result.operationId }).catch((error) => {@@ -334,10 +339,14 @@ export class TaskRunnerService {// Same confirmation gate as TaskService.interruptTaskOperation.const stopped = !!stop?.success && stop.deviceCancellationConfirmed !== false;throw new TRPCError({- code: stopped ? 'NOT_FOUND' : 'INTERNAL_SERVER_ERROR',+ code: stopped+ ? recorded === 'deleted'+ ? 'NOT_FOUND'+ : 'CONFLICT'+ : 'INTERNAL_SERVER_ERROR',message: stopped- ? 'The task was deleted while its run was starting; the run was stopped.'- : `The task was deleted while its run was starting, and stopping that run (operation ${result.operationId}) could not be confirmed.`,+ ? `The task was ${recorded} while its run was starting; the run was stopped.`+ : `The task was ${recorded} while its run was starting, and stopping that run (operation ${result.operationId}) could not be confirmed.`,});}}diff --git a/apps/server/src/services/taskRunner/runTask.deleteRace.test.ts b/apps/server/src/services/taskRunner/runTask.deleteRace.test.tsindex 98903e5a26e..8673feb6313 100644--- a/apps/server/src/services/taskRunner/runTask.deleteRace.test.ts+++ b/apps/server/src/services/taskRunner/runTask.deleteRace.test.ts@@ -59,6 +59,7 @@ describe('TaskRunnerService.runTask vs. a concurrent delete', () => {getCheckpointConfig: vi.fn().mockReturnValue({}),getReviewConfig: vi.fn().mockReturnValue(undefined),incrementTopicCount: vi.fn(),+ findById: vi.fn().mockResolvedValue({ ...task, status: 'running' }),lockForUpdate: vi.fn().mockResolvedValue(true),resolve: vi.fn().mockResolvedValue({ ...task }),update: vi.fn(),@@ -109,6 +110,22 @@ describe('TaskRunnerService.runTask vs. a concurrent delete', () => {expect(taskTopicModel.add).not.toHaveBeenCalled();});+ it('stops the run it just dispatched when the task was canceled meanwhile', async () => {+ // e.g. a Goal retired the Task's node after the runner flipped it to+ // `running` but before this run's topic existed for retirement to stop.+ taskModel.findById.mockResolvedValue({ ...task, status: 'canceled' });++ await expect(+ new TaskRunnerService(db, 'user-1').runTask({ taskId: 'T-1' }),+ ).rejects.toMatchObject({+ code: 'CONFLICT',+ message: 'The task was canceled while its run was starting; the run was stopped.',+ });++ expect(mocks.interruptTask).toHaveBeenCalledWith({ operationId: 'op-new' });+ expect(taskTopicModel.add).not.toHaveBeenCalled();+ });+it.each([{ success: false }, { deviceCancellationConfirmed: false, success: true }])('does not claim the orphaned run stopped when the stop is unconfirmed (%j)',async (stop) => {diff --git a/packages/database/src/models/__tests__/goalGraph.test.ts b/packages/database/src/models/__tests__/goalGraph.test.tsindex d9a5e403582..d77f16e39a2 100644--- a/packages/database/src/models/__tests__/goalGraph.test.ts+++ b/packages/database/src/models/__tests__/goalGraph.test.ts@@ -178,6 +178,34 @@ describe('GoalGraphModel', () => {expect(graph?.events.filter((event) => event.entityType === 'task')).toHaveLength(1);});+ it('refuses to bind a task to a node retired while the task was being created', async () => {+ // Retirement fences the node before it looks for bound Tasks; a Task a+ // concurrent coordinator finishes creating afterwards must not flip the+ // retired node back to `active`.+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Retire race' });+ const node = await graphModel.createNode(goal.id, { kind: 'task', title: 'Stray' });+ const task = await new TaskModel(serverDB, userId).create({ instruction: 'Late task' });++ expect(await graphModel.claimTaskNode(goal.id, node!.id, new Date(0))).toBeDefined();+ await graphModel.updateNodeStatus(goal.id, node!.id, 'retired');++ expect(await graphModel.bindTask(goal.id, node!.id, task.id)).toBeUndefined();+ const [after] = (await graphModel.getGraph(goal.id))!.nodes;+ expect(after.status).toBe('retired');+ expect(after.taskId).toBeNull();+ });++ it('does not let a stale status write revive a retired node', async () => {+ // A coordinator tick that loaded the node before retirement would+ // otherwise write it back to `resolved`.+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'Stale write' });+ const node = await graphModel.createNode(goal.id, { kind: 'task', title: 'Stray' });+ await graphModel.updateNodeStatus(goal.id, node!.id, 'retired');++ expect(await graphModel.updateNodeStatus(goal.id, node!.id, 'resolved')).toBeUndefined();+ expect(await graphModel.getNodeStatus(goal.id, node!.id)).toBe('retired');+ });+it('refuses to bind a task to a node that is not a task node', async () => {// This used to be a CHECK constraint. It lives in `bindTask`'s WHERE now,// so the rule needs a test on the write path or nothing enforces it.diff --git a/packages/database/src/models/goalGraph.ts b/packages/database/src/models/goalGraph.tsindex 5742ebc1a3f..60cd246a651 100644--- a/packages/database/src/models/goalGraph.ts+++ b/packages/database/src/models/goalGraph.ts@@ -14,7 +14,20 @@ import type {GoalStatus,} from '@lobechat/types';import { experimentMembers, experimentOwner, experimentStatus } from '@lobechat/utils/goalGraph';-import { and, asc, count, desc, eq, inArray, isNull, lt, or, sql } from 'drizzle-orm';+import {+ and,+ asc,+ count,+ desc,+ eq,+ inArray,+ isNull,+ lt,+ ne,+ notInArray,+ or,+ sql,+} from 'drizzle-orm';import { goals } from '../schemas/goal';import {@@ -496,6 +509,10 @@ export class GoalGraphModel {eq(goalNodes.goalId, goalId),eq(goalNodes.id, nodeId),eq(goalNodes.kind, 'task'),+ // A node retired (or otherwise settled) while its Task was being+ // created must not be flipped back to `active` by the bind β that+ // is the fence `GoalService.retireNodes` relies on.+ notInArray(goalNodes.status, ['resolved', 'rejected', 'retired']),isNull(goalNodes.taskId),),)@@ -568,6 +585,17 @@ export class GoalGraphModel {return node;});+ /** Current status of one node, read fresh β for writers holding an older snapshot. */+ getNodeStatus = async (goalId: string, nodeId: string): Promise<GoalNodeStatus | undefined> => {+ const [row] = await this.db+ .select({ status: goalNodes.status })+ .from(goalNodes)+ .innerJoin(goals, eq(goals.id, goalNodes.goalId))+ .where(and(eq(goalNodes.goalId, goalId), eq(goalNodes.id, nodeId), this.ownership()))+ .limit(1);+ return row?.status as GoalNodeStatus | undefined;+ };+updateNodeStatus = async (goalId: string,nodeId: string,@@ -583,7 +611,17 @@ export class GoalGraphModel {status,updatedAt: new Date(),})- .where(and(eq(goalNodes.goalId, goalId), eq(goalNodes.id, nodeId)))+ .where(+ and(+ eq(goalNodes.goalId, goalId),+ eq(goalNodes.id, nodeId),+ // Retirement is a person's final word on a node. A coordinator tick+ // that loaded the node before it was retired must not write it back+ // to `resolved` / `active` afterwards; the goal row lock taken above+ // serializes this check with the retirement itself.+ status === 'retired' ? undefined : ne(goalNodes.status, 'retired'),+ ),+ ).returning();if (!node) return undefined;const eventType: GoalEventType =