π€― 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
π fix(goal): stop re-dispatching a Task while its verify repair is still running (#21080)
Arvin Xu1793e3b5b525
diff --git a/apps/server/src/services/goal/abandonedRun.ts b/apps/server/src/services/goal/abandonedRun.tsnew file mode 100644index 00000000000..8c7636e35d7--- /dev/null+++ b/apps/server/src/services/goal/abandonedRun.ts@@ -0,0 +1,125 @@+import { isAgentOperationInFlight } from '@lobechat/types';++import { AgentOperationModel } from '@/database/models/agentOperation';+import { TopicModel } from '@/database/models/topic';+import type { LobeChatDatabase } from '@/database/type';+import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime/AgentRuntimeCoordinator';+import { AiAgentService } from '@/server/services/aiAgent';++/**+ * Whether a Task topic is still `running` although its run has already ended.+ *+ * The run's terminal normally moves the topic through the task lifecycle hook,+ * but that delivery can be lost β a watchdog-abandoned device run had none at+ * all, and a dropped webhook has no retry. The lease reclaim cannot see these:+ * it only settles an operation that is itself still `running`, so the Task+ * stays in flight forever and its goal with it. Once the run has been over for+ * longer than the lease, nothing is left to report it and the topic is lost.+ *+ * A missing operation row proves nothing β a run executed on the client never+ * writes one β so only a row that says the run ended counts.+ */+export const isOrphanedRun = async (+ operationModel: AgentOperationModel,+ operationId: string,+ staleBefore: Date,+): Promise<boolean> => {+ const operation = await operationModel.findById(operationId);+ // Still-owned states (including a run parked for a client) are the lease+ // path's to reclaim, not this.+ if (!operation || isAgentOperationInFlight(operation.status)) return false;+ const endedAt = operation.completedAt ?? operation.updatedAt;+ return new Date(endedAt) < staleBefore;+};++/**+ * The metadata of a Task run's topic. A `task_topics` row carries no topic+ * metadata, so the device a run is bound to or hosted on is read from here.+ */+export const readRunTopicMetadata = async (+ db: LobeChatDatabase,+ owner: { userId: string; workspaceId?: string },+ topicId: string,+) => (await new TopicModel(db, owner.userId, owner.workspaceId).findById(topicId))?.metadata;++/** Whether the runtime still holds the run's state, or a device hosts its process. */+const hasLiveExecutor = async (+ db: LobeChatDatabase,+ owner: { userId: string; workspaceId?: string },+ run: { operationId: string; topicId: string },+): Promise<boolean> => {+ if (await new AgentRuntimeCoordinator().loadAgentState(run.operationId)) return true;+ const marker = (await readRunTopicMetadata(db, owner, run.topicId))?.runningOperation;+ const target =+ marker?.operationId === run.operationId+ ? marker+ : marker?.childOperations?.find((child) => child.operationId === run.operationId);+ return !!target?.deviceId;+};++/**+ * Claim a run whose lease expired and stop it, before its replacement starts.+ *+ * The lease reclaim only settles the operation row. A run stuck on a tool call+ * stops heartbeating, but it is not gone: when the call finally returns it+ * carries on, working the same branch as the attempt that replaced it. So a run+ * something still executes is stopped first, and only a confirmed stop lets the+ * reclaim proceed.+ *+ * The lease is claimed before the interrupt, with the same compare-and-set the+ * reclaim uses: it moves the row out of `running`, so a heartbeat landing after+ * the staleness read can no longer revive it β and a heartbeat that landed first+ * makes the claim fail, leaving the healthy run untouched.+ *+ * - `not_running`: no stale run with a live executor β the reclaim decides on its+ * own, in its transaction, as before.+ * - `fresh`: the run heartbeated before the claim; it is alive, reclaim nothing.+ * - `stopped`: claimed, and the runtime (and the device, for a device-hosted+ * process) acknowledged the stop β or nothing executes it any more.+ * - `unconfirmed`: claimed, but the stop was refused, unconfirmed or failed; the+ * run may still be writing. `interruptTask` reports this as a resolved result,+ * not a throw. The next tick finds the claimed row and retries the stop.+ */+export const stopStaleRun = async (+ db: LobeChatDatabase,+ owner: { userId: string; workspaceId?: string },+ run: { latestTotalCost?: number; operationId: string; staleBefore: Date; topicId: string },+): Promise<'fresh' | 'not_running' | 'stopped' | 'unconfirmed'> => {+ const operationModel = new AgentOperationModel(db, owner.userId, owner.workspaceId);+ const operation = await operationModel.findById(run.operationId);+ // A row this reclaim already claimed on an earlier tick, whose stop was not+ // confirmed then.+ const claimedEarlier =+ operation?.status === 'abandoned' && operation.completionReason === 'lease_expired';+ // Only a `running` row is the lease's to reclaim; a run parked for a person or+ // a client is legitimately quiet and must not be stopped.+ const stale = operation?.status === 'running' && new Date(operation.updatedAt) < run.staleBefore;+ if (!claimedEarlier && !stale) return 'not_running';++ // With no runtime state and no device hosting it, nothing executes the run any+ // more. Interrupting it then would only retire the row outside the reclaim's+ // transaction, skipping its cost charge and its rollback.+ if (!(await hasLiveExecutor(db, owner, run))) return claimedEarlier ? 'stopped' : 'not_running';++ if (+ stale &&+ !(await operationModel.settleStaleRunning(+ run.operationId,+ run.staleBefore,+ run.latestTotalCost,+ ))+ )+ return 'fresh';++ try {+ const result = await new AiAgentService(db, owner.userId, {+ workspaceId: owner.workspaceId,+ }).interruptTask({ operationId: run.operationId, topicId: run.topicId });+ return result.success && result.deviceCancellationConfirmed !== false+ ? 'stopped'+ : 'unconfirmed';+ } catch (error) {+ console.error('[GoalService] failed to interrupt stale run %s:', run.operationId, error);+ return 'unconfirmed';+ }+};diff --git a/apps/server/src/services/goal/deliverySettle.ts b/apps/server/src/services/goal/deliverySettle.tsnew file mode 100644index 00000000000..ffd380f2922--- /dev/null+++ b/apps/server/src/services/goal/deliverySettle.ts@@ -0,0 +1,59 @@+import { isAgentOperationInFlight } from '@lobechat/types';++import type { AgentOperationModel } from '@/database/models/agentOperation';++import { VERIFY_SETTLE_GRACE_MS } from './recoveryPolicy';++/**+ * Bound on the delivered topic's operations read when dating its last activity.+ * A repair spawns child operations into the same topic, so a small newest-first+ * sample could miss the long-lived root that is still heartbeating; a topic+ * never holds anywhere near this many runs.+ */+const MAX_TOPIC_OPERATIONS = 500;++interface DeliveredTopic {+ completedAt: Date | null;+ createdAt: Date;+ status: string | null;+ topicId: string | null;+}++/**+ * Whether a delivered Task may still be settling its verification, so the+ * coordinator must not re-dispatch it.+ *+ * A verify-bound Task keeps its task `running` with a *completed* topic until+ * the verify run settles. That settle is not one judgment: a failed check sends+ * an auto-repair operation back into the same delivered topic, and the repaired+ * round is judged again after it. The topic row stays `completed` throughout, so+ * the grace window counts from the delivery's last sign of life β the newest+ * operation heartbeat or completion in that topic β not from the original+ * delivery. Counting from the delivery re-dispatched a second attempt an hour+ * in, beside a repair that was still running.+ */+export const isDeliverySettling = async (+ operationModel: AgentOperationModel,+ topic: DeliveredTopic | undefined,+): Promise<boolean> => {+ if (topic?.status !== 'completed') return false;++ let lastActivity = new Date(topic.completedAt ?? topic.createdAt).getTime();+ if (topic.topicId) {+ const recent = await operationModel.listByTopic(topic.topicId, MAX_TOPIC_OPERATIONS);+ const operations = await operationModel.findByIds(recent.map((operation) => operation.id));+ for (const operation of operations) {+ if (!isAgentOperationInFlight(operation.status)) {+ const endedAt = operation.completedAt ?? operation.updatedAt;+ lastActivity = Math.max(lastActivity, new Date(endedAt).getTime());+ continue;+ }+ // A repair parked for a person, a client or an async tool is legitimately+ // quiet and can still resume: its stale heartbeat says nothing about it.+ if (operation.status.startsWith('waiting_for_')) return true;+ lastActivity = Math.max(lastActivity, new Date(operation.updatedAt).getTime());+ }+ }++ return lastActivity >= Date.now() - VERIFY_SETTLE_GRACE_MS;+};diff --git a/apps/server/src/services/goal/index.abandonedRun.test.ts b/apps/server/src/services/goal/index.abandonedRun.test.tsnew file mode 100644index 00000000000..54bbbf0adb7--- /dev/null+++ b/apps/server/src/services/goal/index.abandonedRun.test.ts@@ -0,0 +1,334 @@+// @vitest-environment node+import type { ChatTopicMetadata } from '@lobechat/types';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { AgentOperationModel } from '@/database/models/agentOperation';+import { TaskModel } from '@/database/models/task';+import { TaskTopicModel } from '@/database/models/taskTopic';+import {+ agentOperations,+ goalEdges,+ goalEvents,+ goalNodeDecisions,+ goalNodes,+ goals,+ tasks,+ taskTopics,+ topics,+ users,+} from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';+import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime/AgentRuntimeCoordinator';+import { AiAgentService } from '@/server/services/aiAgent';++import { deviceGateway } from '../deviceGateway';+import { TaskRunnerService } from '../taskRunner';+import { GoalService } from './index';+import { VERIFY_SETTLE_GRACE_MS } from './recoveryPolicy';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'goal-verify-repair-test-user';++beforeEach(async () => {+ await serverDB.insert(users).values({ id: userId }).onConflictDoNothing();+});++afterEach(async () => {+ vi.restoreAllMocks();+ await serverDB.delete(goalNodeDecisions);+ await serverDB.delete(goalEdges);+ await serverDB.delete(goalEvents);+ await serverDB.delete(goalNodes);+ await serverDB.delete(goals);+ await serverDB.delete(agentOperations);+ await serverDB.delete(taskTopics);+ await serverDB.delete(topics);+ await serverDB.delete(tasks);+ await serverDB.delete(users);+});++/**+ * A Task delivered over an hour ago whose verify run failed a check and sent+ * an auto-repair operation back into the delivered topic. The topic row stays+ * `completed` the whole time, so the coordinator sees no running topic.+ */+const seedRepairedDelivery = async (title: string) => {+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { operationLeaseTimeoutMs: 60_000 } },+ tasks: [title],+ title,+ });+ const created = await service.tick(graph.goal.id);+ const deliveredAt = new Date(Date.now() - VERIFY_SETTLE_GRACE_MS - 5 * 60_000);+ await serverDB.insert(topics).values({ id: 'tpc_delivered', userId });+ await serverDB.insert(taskTopics).values({+ completedAt: deliveredAt,+ createdAt: deliveredAt,+ operationId: 'op-delivered',+ seq: 1,+ status: 'completed',+ taskId: created.taskId!,+ topicId: 'tpc_delivered',+ userId,+ });+ await taskModel.updateStatus(created.taskId!, 'running');+ await serverDB+ .update(tasks)+ .set({ updatedAt: new Date(Date.now() - 10 * 60_000) })+ .where(eq(tasks.id, created.taskId!));+ await new AgentOperationModel(serverDB, userId).recordStart({+ operationId: 'op-repair',+ startedAt: new Date(Date.now() - 55 * 60_000),+ topicId: 'tpc_delivered',+ });+ return { goalId: graph.goal.id, service, taskId: created.taskId!, taskModel };+};++describe('GoalService verify repair in a delivered topic', () => {+ it('does not re-dispatch while the repair run in the delivered topic is alive', async () => {+ // The repair runs inside the completed topic, so the coordinator found no+ // running topic, measured the grace window from the original delivery, and+ // dispatched a second attempt beside the live repair β two agents pushing+ // the same branch, and the retry's round shadowing the repair's.+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const { goalId, service, taskId, taskModel } = await seedRepairedDelivery('Repair is alive');++ const waiting = await service.tick(goalId);++ expect(waiting).toMatchObject({ outcome: 'waiting_external', taskId });+ expect((await taskModel.findById(taskId))?.status).toBe('running');+ expect(runSpy).not.toHaveBeenCalled();+ });++ it('gives the verdict on a finished repair its own grace window', async () => {+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const { goalId, service, taskId, taskModel } = await seedRepairedDelivery('Repair finished');+ await serverDB+ .update(agentOperations)+ .set({ completedAt: new Date(Date.now() - 5 * 60_000), status: 'done' })+ .where(eq(agentOperations.id, 'op-repair'));++ const waiting = await service.tick(goalId);++ expect(waiting).toMatchObject({ outcome: 'waiting_external', taskId });+ expect((await taskModel.findById(taskId))?.status).toBe('running');+ expect(runSpy).not.toHaveBeenCalled();+ });++ it('still reclaims the Task once a dead repair has been silent past the grace window', async () => {+ const { goalId, service, taskId, taskModel } = await seedRepairedDelivery('Repair died');+ await serverDB+ .update(agentOperations)+ .set({ updatedAt: new Date(Date.now() - VERIFY_SETTLE_GRACE_MS - 60_000) })+ .where(eq(agentOperations.id, 'op-repair'));++ const released = await service.tick(goalId);++ expect(released.outcome).toBe('advanced');+ expect((await taskModel.findById(taskId))?.status).toBe('backlog');+ });+ it('holds while the repair is parked, however long it has been quiet', async () => {+ // A repair waiting for a person or a client stops heartbeating on purpose+ // and can still resume; its old heartbeat must not read as a dead repair.+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const { goalId, service, taskId, taskModel } = await seedRepairedDelivery('Repair parked');+ await serverDB+ .update(agentOperations)+ .set({+ status: 'waiting_for_human',+ updatedAt: new Date(Date.now() - VERIFY_SETTLE_GRACE_MS - 60_000),+ })+ .where(eq(agentOperations.id, 'op-repair'));++ const waiting = await service.tick(goalId);++ expect(waiting).toMatchObject({ outcome: 'waiting_external', taskId });+ expect((await taskModel.findById(taskId))?.status).toBe('running');+ expect(runSpy).not.toHaveBeenCalled();+ });++ it('finds a live repair root behind more than five newer child runs', async () => {+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const { goalId, service, taskId } = await seedRepairedDelivery('Repair with children');+ const longAgo = new Date(Date.now() - 3 * VERIFY_SETTLE_GRACE_MS);+ await serverDB+ .update(agentOperations)+ .set({ createdAt: longAgo })+ .where(eq(agentOperations.id, 'op-repair'));+ const operationModel = new AgentOperationModel(serverDB, userId);+ for (let i = 0; i < 6; i++) {+ const operationId = `op-repair-child-${i}`;+ await operationModel.recordStart({+ operationId,+ parentOperationId: 'op-repair',+ topicId: 'tpc_delivered',+ });+ await serverDB+ .update(agentOperations)+ .set({+ completedAt: new Date(longAgo.getTime() + 60_000),+ createdAt: new Date(longAgo.getTime() + (i + 1) * 1000),+ status: 'done',+ })+ .where(eq(agentOperations.id, operationId));+ }++ const waiting = await service.tick(goalId);++ expect(waiting).toMatchObject({ outcome: 'waiting_external', taskId });+ expect(runSpy).not.toHaveBeenCalled();+ });+});++describe('GoalService lease reclaim of a running topic', () => {+ const seedStaleRun = async (title: string, metadata?: ChatTopicMetadata) => {+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({+ operationId: 'op-next',+ success: true,+ } as never);+ // A `task_topics` row carries no topic metadata; the device lives on the topic.+ await serverDB.insert(topics).values({ id: 'tpc_stuck', metadata, userId });+ const stuckTopic = { operationId: 'op-stuck', topicId: 'tpc_stuck' } as never;+ vi.spyOn(TaskTopicModel.prototype, 'findRunningByTaskIds').mockResolvedValue([stuckTopic]);+ vi.spyOn(TaskTopicModel.prototype, 'findWithHandoff').mockResolvedValue([+ { ...(stuckTopic as object), status: 'timeout' } as never,+ ]);+ vi.spyOn(TaskTopicModel.prototype, 'updateStatus').mockResolvedValue(undefined);+ vi.spyOn(AgentRuntimeCoordinator.prototype, 'getOperationMetadata').mockResolvedValue(+ undefined as never,+ );+ // The runtime still holds the stuck step: something is executing the run.+ vi.spyOn(AgentRuntimeCoordinator.prototype, 'loadAgentState').mockResolvedValue({+ status: 'running',+ } as never);+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { maxAttemptsPerTask: 3, operationLeaseTimeoutMs: 60_000 } },+ tasks: [title],+ title,+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.update(created.taskId!, { totalTopics: 1 });+ await taskModel.updateStatus(created.taskId!, 'running');+ await new AgentOperationModel(serverDB, userId).recordStart({+ operationId: 'op-stuck',+ taskId: created.taskId,+ topicId: null,+ });+ await serverDB+ .update(agentOperations)+ .set({ updatedAt: new Date(Date.now() - 10 * 60_000) })+ .where(eq(agentOperations.id, 'op-stuck'));+ return { goalId: graph.goal.id, runSpy, service, taskId: created.taskId!, taskModel };+ };++ it('stops the stale run before reclaiming it', async () => {+ // A run stuck on a tool call stops heartbeating, so its lease expires and+ // the next attempt starts. Settling only the row left the stuck run alive:+ // when its tool call returned it kept working beside its replacement.+ const interruptSpy = vi+ .spyOn(AiAgentService.prototype, 'interruptTask')+ .mockResolvedValue({ success: true });+ const { goalId, service } = await seedStaleRun('Stuck on a tool call');++ await service.tick(goalId);++ expect(interruptSpy).toHaveBeenCalledWith({ operationId: 'op-stuck', topicId: 'tpc_stuck' });+ expect(await new AgentOperationModel(serverDB, userId).findById('op-stuck')).toMatchObject({+ status: 'abandoned',+ });+ });++ it.each([+ ['refused', () => Promise.resolve({ success: false })],+ [+ 'device exit unconfirmed',+ () => Promise.resolve({ deviceCancellationConfirmed: false, success: true }),+ ],+ ['unreachable', () => Promise.reject(new Error('gateway down'))],+ ])('starts no replacement while the stale run may still be writing (%s)', async (_, outcome) => {+ // `interruptTask` reports an unconfirmed stop as a resolved result. Reading+ // only a throw as failure dispatched the replacement beside a live writer.+ vi.spyOn(AiAgentService.prototype, 'interruptTask').mockImplementation(outcome as never);+ vi.spyOn(console, 'error').mockImplementation(() => {});+ const { goalId, runSpy, service, taskId, taskModel } = await seedStaleRun('Still writing');++ await service.tick(goalId);++ expect(runSpy).not.toHaveBeenCalled();+ expect((await taskModel.findById(taskId))?.status).toBe('running');+ expect(TaskTopicModel.prototype.updateStatus).not.toHaveBeenCalled();+ });++ it('retries the stop on the next tick and reclaims once it is confirmed', async () => {+ const interruptSpy = vi+ .spyOn(AiAgentService.prototype, 'interruptTask')+ .mockResolvedValueOnce({ success: false })+ .mockResolvedValueOnce({ success: true });+ const { goalId, service } = await seedStaleRun('Stop confirmed later');++ await service.tick(goalId);+ expect(TaskTopicModel.prototype.updateStatus).not.toHaveBeenCalled();++ await service.tick(goalId);++ expect(interruptSpy).toHaveBeenCalledTimes(2);+ expect(TaskTopicModel.prototype.updateStatus).toHaveBeenCalledWith(+ expect.any(String),+ 'tpc_stuck',+ 'timeout',+ );+ });++ it('leaves a run alone when it heartbeats between the staleness read and the claim', async () => {+ // Interrupting on a stale read alone cancelled a run whose heartbeat landed+ // a moment later; the claim's compare-and-set must decide, before the stop.+ const interruptSpy = vi.spyOn(AiAgentService.prototype, 'interruptTask');+ const { goalId, runSpy, service } = await seedStaleRun('Heartbeat wins');+ vi.spyOn(AgentRuntimeCoordinator.prototype, 'loadAgentState').mockImplementation(async () => {+ await new AgentOperationModel(serverDB, userId).touchRunning('op-stuck');+ return { status: 'running' } as never;+ });++ await service.tick(goalId);++ expect(interruptSpy).not.toHaveBeenCalled();+ expect(runSpy).not.toHaveBeenCalled();+ expect(TaskTopicModel.prototype.updateStatus).not.toHaveBeenCalled();+ expect(await new AgentOperationModel(serverDB, userId).findById('op-stuck')).toMatchObject({+ status: 'running',+ });+ });++ it('still reclaims a run whose device is offline', async () => {+ // An offline device can never confirm the stop; holding for it would strand+ // the goal. The reclaim proceeds and the offline-device recovery takes over.+ vi.spyOn(deviceGateway, 'isConfigured', 'get').mockReturnValue(true);+ vi.spyOn(deviceGateway, 'queryDeviceList').mockResolvedValue([]);+ vi.spyOn(AiAgentService.prototype, 'interruptTask').mockResolvedValue({ success: false });+ // As in production: only the topic's running marker knows the device.+ const { goalId, service } = await seedStaleRun('Device asleep', {+ runningOperation: {+ assistantMessageId: 'msg-stuck',+ deviceId: 'device-laptop',+ operationId: 'op-stuck',+ },+ });++ await service.tick(goalId);++ expect(TaskTopicModel.prototype.updateStatus).toHaveBeenCalledWith(+ expect.any(String),+ 'tpc_stuck',+ 'timeout',+ );+ expect(await new AgentOperationModel(serverDB, userId).findById('op-stuck')).toMatchObject({+ status: 'abandoned',+ });+ });+});diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.tsindex d8b31245429..a6d41f11f6a 100644--- a/apps/server/src/services/goal/index.ts+++ b/apps/server/src/services/goal/index.ts@@ -42,7 +42,6 @@ import type {TaskTopicHandoff,WorkVersionEventItem,} from '@lobechat/types';-import { isAgentOperationInFlight } from '@lobechat/types';import { experimentOwner, provenanceParentId } from '@lobechat/utils/goalGraph';import { goalSeedDependencyProblem, type GoalSeedTask } from '@lobechat/utils/goalSeeds';import { TRPCError } from '@trpc/server';@@ -70,6 +69,7 @@ import { TaskService } from '../task';import { TaskRunnerService } from '../taskRunner';import { AcceptanceService } from '../verify/acceptanceService';import { VerifyPlanGeneratorService } from '../verify/planGenerator';+import { isOrphanedRun, readRunTopicMetadata, stopStaleRun } from './abandonedRun';import { BatchPlanSkillService, learnedRulesClause, planSkillIdentifier } from './batchPlanSkill';import { GoalCriteriaGeneratorService, type GoalDecompositionDraft } from './criteriaGenerator';import {@@ -85,6 +85,7 @@ import {selectFrontier,TERMINAL_NODE_STATUSES,} from './decideNextMove';+import { isDeliverySettling } from './deliverySettle';import { experimentResults, exploreGraph } from './exploreGraph';import { classifyGoalFailure, isMachineFailureClass } from './failureClass';import { GoalBriefService } from './goalBriefs';@@ -102,7 +103,6 @@ import {resolveMaxConcurrentTasks,resolveOperationLeaseTimeout,resolveTaskMaxSteps,- VERIFY_SETTLE_GRACE_MS,} from './recoveryPolicy';import { GoalReleaseReview } from './releaseReview';import { isGoalReportNode, withoutGoalReport } from './report';@@ -3261,27 +3261,22 @@ export class GoalService {const staleBefore = new Date(Date.now() - resolveOperationLeaseTimeout(graph.goal));if (!operationId || !topicId) {- // No running topic covers two very different shapes. A verify-bound Task- // that delivered keeps its task `running` with a *completed* topic until- // the verify run settles, and that judgment β a full agent run β outlives- // the operation lease routinely. Re-dispatching there pays for a duplicate- // attempt the verify settle path will cancel, and the canceled retry then- // becomes the newest topic and shadows the delivered one. Hold off while- // the delivery is fresh; past the grace window, fall through to the- // release below so a verify run that died silently cannot strand the- // goal forever.+ // No running topic covers two very different shapes. A delivered Task+ // waiting on its verification (and any repair it sends back) outlives the+ // operation lease routinely; re-dispatching there pays for a duplicate+ // attempt that shadows the delivered one. Hold off while the delivery is+ // settling; past its grace window, fall through to the release below so+ // a verify run that died silently cannot strand the goal forever.const [lastTopic] = await this.taskTopicModel.findWithHandoff(task.id, 1);- if (lastTopic?.status === 'completed') {- const deliveredAt = lastTopic.completedAt ?? lastTopic.createdAt;- if (new Date(deliveredAt).getTime() >= Date.now() - VERIFY_SETTLE_GRACE_MS) {- return {- goalId: graph.goal.id,- message: `Task ${task.identifier} delivered; waiting for verification to settle`,- nodeId,- outcome: 'waiting_external',- taskId: task.id,- };- }+ const operationModel = new AgentOperationModel(this.db, this.userId, this.workspaceId);+ if (await isDeliverySettling(operationModel, lastTopic)) {+ return {+ goalId: graph.goal.id,+ message: `Task ${task.identifier} delivered; waiting for verification to settle`,+ nodeId,+ outcome: 'waiting_external',+ taskId: task.id,+ };}// A task claimed for dispatch but with no run behind it. Normally this is@@ -3301,15 +3296,37 @@ export class GoalService {};}+ // A run that may still be writing must not get a replacement beside it; only+ // a device known to be offline is left to the offline-device recovery below.const latestUsage = await new AgentRuntimeCoordinator().getOperationMetadata(operationId);+ const owner = { userId: this.userId, workspaceId: this.workspaceId };+ const latestTotalCost = latestUsage?.totalCost;+ const stop = await stopStaleRun(this.db, owner, {+ latestTotalCost,+ operationId,+ staleBefore,+ topicId,+ });+ if (stop === 'fresh') return undefined;+ if (stop === 'unconfirmed') {+ const metadata = await readRunTopicMetadata(this.db, owner, topicId);+ if ((await this.readRunDevicePresence({ metadata, operationId })) !== 'offline')+ return undefined;+ }+const reclaimed = await this.db.transaction(async (tx) => {const operationModel = new AgentOperationModel(tx, this.userId, this.workspaceId);const settled = await operationModel.settleStaleRunning(operationId,staleBefore,- latestUsage?.totalCost,+ latestTotalCost,);- if (!settled && !(await isOrphanedRun(operationModel, operationId, staleBefore)))+ // `stopStaleRun` already claimed the lease atomically when it had to stop.+ if (+ !settled &&+ stop === 'not_running' &&+ !(await isOrphanedRun(operationModel, operationId, staleBefore))+ )return false;await new TaskTopicModel(tx, this.userId, this.workspaceId).updateStatus(@@ -5061,29 +5078,3 @@ interface FailureGateOptions {const MACHINE_HOLD_SCHEDULE_WINDOW_MS = 15 * 60 * 1000;/** Queue delays are bounded; the sweep covers anything further out. */const MAX_ADVANCE_DELAY_S = 86_400;--/**- * Whether a Task topic is still `running` although its run has already ended.- *- * The run's terminal normally moves the topic through the task lifecycle hook,- * but that delivery can be lost β a watchdog-abandoned device run had none at- * all, and a dropped webhook has no retry. The lease reclaim cannot see these:- * it only settles an operation that is itself still `running`, so the Task- * stays in flight forever and its goal with it. Once the run has been over for- * longer than the lease, nothing is left to report it and the topic is lost.- *- * A missing operation row proves nothing β a run executed on the client never- * writes one β so only a row that says the run ended counts.- */-const isOrphanedRun = async (- operationModel: AgentOperationModel,- operationId: string,- staleBefore: Date,-): Promise<boolean> => {- const operation = await operationModel.findById(operationId);- // Still-owned states (including a run parked for a client) are the lease- // path's to reclaim, not this.- if (!operation || isAgentOperationInFlight(operation.status)) return false;- const endedAt = operation.completedAt ?? operation.updatedAt;- return new Date(endedAt) < staleBefore;-};diff --git a/apps/server/src/services/taskRunner/buildTaskPrompt.test.ts b/apps/server/src/services/taskRunner/buildTaskPrompt.test.tsindex 1cd65a07300..6e4d5ea4b2f 100644--- a/apps/server/src/services/taskRunner/buildTaskPrompt.test.ts+++ b/apps/server/src/services/taskRunner/buildTaskPrompt.test.ts@@ -17,6 +17,8 @@ import {goals,tasks,users,+ verifyCheckResults,+ verifyRuns,} from '@/database/schemas';import { buildTaskPrompt } from './buildTaskPrompt';@@ -92,6 +94,190 @@ describe('buildTaskPrompt Goal loop context', () => {});});+describe('buildTaskPrompt unresolved checks', () => {+ const planItem = (id: string) => ({+ id,+ index: 0,+ onFail: 'auto_repair' as const,+ required: true,+ title: `Check ${id}`,+ verifierConfig: {},+ verifierType: 'agent' as const,+ });++ it('carries the last judged failure when the newest round is still unjudged', async () => {+ // A repair round re-plans every check and leaves them pending until the+ // verifier runs. A retry dispatched meanwhile read only that newest round,+ // found nothing failed, and was told to "close the gaps below" with no gaps.+ const taskModel = new TaskModel(db, userId);+ const task = await taskModel.create({ instruction: 'Land the file tree PR.' });+ await taskModel.update(task.id, { totalTopics: 2 });+ const goal = await new GoalModel(db, userId).create({+ subjectType: 'standalone',+ title: 'Unjudged repair round',+ });+ const graphModel = new GoalGraphModel(db, userId);+ const taskNode = await graphModel.createNode(goal.id, { kind: 'task', title: 'Land it' });+ await graphModel.bindTask(goal.id, taskNode!.id, task.id);+ const acceptance = await new AcceptanceModel(db, userId).create({+ subjectId: task.id,+ subjectType: 'task',+ });+ const [judged, unjudged] = await db+ .insert(verifyRuns)+ .values(+ [1, 2].map((roundIndex) => ({+ acceptanceId: acceptance.id,+ plan: [planItem('rebased'), planItem('evidence')],+ roundIndex,+ userId,+ })),+ )+ .returning();+ await db.insert(verifyCheckResults).values(+ [+ { checkItemId: 'rebased', status: 'passed', verdict: 'passed', verifyRunId: judged.id },+ {+ checkItemId: 'evidence',+ status: 'failed',+ suggestion: 'Capture the account switch run and the no-data loading contrast.',+ verdict: 'failed',+ verifyRunId: judged.id,+ },+ { checkItemId: 'rebased', status: 'pending', verifyRunId: unjudged.id },+ { checkItemId: 'evidence', status: 'pending', verifyRunId: unjudged.id },+ ].map((row) => ({ ...row, userId, verifierType: 'agent' as const })),+ );++ const result = await buildTaskPrompt((await taskModel.findById(task.id))!, {+ briefModel: new BriefModel(db, userId),+ db,+ taskModel,+ taskTopicModel: new TaskTopicModel(db, userId),+ userId,+ });++ expect(result.prompt).toContain('Unresolved checks from the last round:');+ expect(result.prompt).toContain(+ '1. Check evidence β Capture the account switch run and the no-data loading contrast.',+ );+ expect(result.prompt).not.toContain('Check rebased');+ });+ it('keeps flow nodes that reuse one criterion as separate checks', async () => {+ // Two flow nodes can point at the same criterion asset; folding them onto+ // the criterion id let one node's failure stand in for the node that passed.+ const taskModel = new TaskModel(db, userId);+ const task = await taskModel.create({ instruction: 'Verify both branches.' });+ await taskModel.update(task.id, { totalTopics: 1 });+ const goal = await new GoalModel(db, userId).create({+ subjectType: 'standalone',+ title: 'Repeated flow asset',+ });+ const graphModel = new GoalGraphModel(db, userId);+ const taskNode = await graphModel.createNode(goal.id, { kind: 'task', title: 'Verify' });+ await graphModel.bindTask(goal.id, taskNode!.id, task.id);+ const acceptance = await new AcceptanceModel(db, userId).create({+ subjectId: task.id,+ subjectType: 'task',+ });+ const flowItem = (id: string, node: string) => ({+ ...planItem(id),+ sourceCriterionId: 'shared-criterion',+ sourceFlowNode: { flowId: 'flow-1', nodeId: node },+ title: `Branch ${node}`,+ });+ const [run] = await db+ .insert(verifyRuns)+ .values({+ acceptanceId: acceptance.id,+ plan: [flowItem('occurrence-a', 'a'), flowItem('occurrence-b', 'b')],+ roundIndex: 1,+ userId,+ } as never)+ .returning();+ await db.insert(verifyCheckResults).values(+ [+ { checkItemId: 'occurrence-a', status: 'passed' as const, verdict: 'passed' as const },+ {+ checkItemId: 'occurrence-b',+ status: 'failed' as const,+ suggestion: 'Branch b never reached the confirmation step.',+ verdict: 'failed' as const,+ },+ ].map((row) => ({ ...row, userId, verifierType: 'agent' as const, verifyRunId: run.id })),+ );++ const result = await buildTaskPrompt((await taskModel.findById(task.id))!, {+ briefModel: new BriefModel(db, userId),+ db,+ taskModel,+ taskTopicModel: new TaskTopicModel(db, userId),+ userId,+ });++ expect(result.prompt).toContain('1. Branch b β Branch b never reached the confirmation step.');+ expect(result.prompt).not.toContain('Branch a');+ });+ it('carries a failed check into the unjudged successor that supersedes it', async () => {+ // A repair round may reword a failed check as a new item that `supersedes`+ // it. Looking up only the successor id lost the failure it inherits.+ const taskModel = new TaskModel(db, userId);+ const task = await taskModel.create({ instruction: 'Reword and retry.' });+ await taskModel.update(task.id, { totalTopics: 2 });+ const goal = await new GoalModel(db, userId).create({+ subjectType: 'standalone',+ title: 'Superseded check',+ });+ const graphModel = new GoalGraphModel(db, userId);+ const taskNode = await graphModel.createNode(goal.id, { kind: 'task', title: 'Retry' });+ await graphModel.bindTask(goal.id, taskNode!.id, task.id);+ const acceptance = await new AcceptanceModel(db, userId).create({+ subjectId: task.id,+ subjectType: 'task',+ });+ const [judged, reworded] = await db+ .insert(verifyRuns)+ .values([+ { acceptanceId: acceptance.id, plan: [planItem('old-wording')], roundIndex: 1, userId },+ {+ acceptanceId: acceptance.id,+ plan: [{ ...planItem('new-wording'), supersedes: ['old-wording'] }],+ roundIndex: 2,+ userId,+ },+ ] as never)+ .returning();+ await db.insert(verifyCheckResults).values([+ {+ checkItemId: 'old-wording',+ status: 'failed' as const,+ suggestion: 'The export still drops the table.',+ userId,+ verdict: 'failed' as const,+ verifierType: 'agent' as const,+ verifyRunId: judged.id,+ },+ {+ checkItemId: 'new-wording',+ status: 'pending' as const,+ userId,+ verifierType: 'agent' as const,+ verifyRunId: reworded.id,+ },+ ]);++ const result = await buildTaskPrompt((await taskModel.findById(task.id))!, {+ briefModel: new BriefModel(db, userId),+ db,+ taskModel,+ taskTopicModel: new TaskTopicModel(db, userId),+ userId,+ });++ expect(result.prompt).toContain('1. Check new-wording β The export still drops the table.');+ });+});+describe('buildTaskPrompt owner change request', () => {it('keeps the owner reject comment when the rework already opened a new round', async () => {const taskModel = new TaskModel(db, userId);diff --git a/apps/server/src/services/taskRunner/buildTaskPrompt.ts b/apps/server/src/services/taskRunner/buildTaskPrompt.tsindex 6189313fce9..e211760f5eb 100644--- a/apps/server/src/services/taskRunner/buildTaskPrompt.ts+++ b/apps/server/src/services/taskRunner/buildTaskPrompt.ts@@ -23,6 +23,15 @@ import { resolveTaskAcceptance } from '@/server/services/verify/taskAcceptance';/** Cap on unresolved checks carried into the next round's prompt. */const MAX_GOAL_FAILED_CHECKS = 8;+/**+ * Whether the verifier actually judged this result. `pending` / `running` rows+ * are planned checks, and `errored` means the verifier never ran β neither says+ * anything about the delivery.+ */+const isJudgedResult = (result: { status: string; verdict: string | null }) =>+ result.status !== 'errored' &&+ (!!result.verdict || result.status === 'passed' || result.status === 'failed');+/*** For a goal task that already ran at least one round, collect what the next* round must know: the previous round's unresolved checks (with the verifier's@@ -76,22 +85,66 @@ const resolveGoalLoopContext = async (context.automaticReviewFeedback = automaticReview.feedback;}- const plan = (last.plan ?? []) as Array<{ id: string; title: string }>;- const results = await new VerifyCheckResultModel(db, userId, workspaceId).listByRun(last.id);- const byItem = new Map(results.map((r) => [r.checkItemId, r]));- const failed = plan- .filter((item) => {- const r = byItem.get(item.id);- return (- !!r &&- r.status !== 'errored' &&- (r.status === 'failed' || r.verdict === 'failed' || r.verdict === 'uncertain')- );- })- .map((item) => {- const r = byItem.get(item.id);- return { title: item.title, why: r?.suggestion || r?.toulmin?.reasoning || undefined };- });+ // A round is planned (every check `pending`) before its verifier runs, so+ // the newest round is often still unjudged when the next attempt starts. Take+ // each check's newest JUDGED result across the chain instead; reading only+ // the newest round handed that attempt "close the gaps below" with no gaps.+ // Keyed like the acceptance union: a flow node's check is its own occurrence+ // even when several nodes reuse one criterion asset.+ type PlanItem = {+ id: string;+ sourceCriterionId?: string | null;+ sourceFlowNode?: unknown;+ supersedes?: string[];+ title: string;+ };+ const logicalId = (item: PlanItem) =>+ item.sourceFlowNode ? item.id : (item.sourceCriterionId ?? item.id);+ const logicalByCheckItem = new Map<string, string>();+ for (const run of runs) {+ for (const item of (run.plan ?? []) as PlanItem[]) {+ logicalByCheckItem.set(item.id, logicalId(item));+ }+ }+ const roundByRun = new Map(runs.map((run) => [run.id, run.roundIndex ?? 0]));+ const results = await new VerifyCheckResultModel(db, userId, workspaceId).listByRuns(+ runs.map((run) => run.id),+ );+ type JudgedEntry = { result: (typeof results)[number]; round: number };+ const latestJudged = new Map<string, JudgedEntry>();+ for (const result of results) {+ if (!isJudgedResult(result)) continue;+ const id = logicalByCheckItem.get(result.checkItemId) ?? result.checkItemId;+ const round = roundByRun.get(result.verifyRunId ?? '') ?? 0;+ const current = latestJudged.get(id);+ if (!current || round >= current.round) latestJudged.set(id, { result, round });+ }++ // As in the acceptance union, a successor that never ran inherits the verdict+ // of the checks it `supersedes` (and of what those superseded, in turn).+ const supersedesById = new Map<string, string[]>();+ for (const run of runs) {+ for (const item of (run.plan ?? []) as PlanItem[]) {+ if (item.supersedes?.length) supersedesById.set(logicalId(item), item.supersedes);+ }+ }+ const judgedFor = (id: string, seen = new Set<string>()): JudgedEntry | undefined => {+ if (seen.has(id)) return undefined;+ seen.add(id);+ const own = latestJudged.get(id);+ if (own) return own;+ const inherited = (supersedesById.get(id) ?? [])+ .map((oldId) => judgedFor(logicalByCheckItem.get(oldId) ?? oldId, seen))+ .filter((entry): entry is JudgedEntry => !!entry);+ return inherited.sort((a, b) => b.round - a.round)[0];+ };++ const failed = ((last.plan ?? []) as PlanItem[]).flatMap((item) => {+ const r = judgedFor(logicalId(item))?.result;+ if (!r || (r.status !== 'failed' && r.verdict !== 'failed' && r.verdict !== 'uncertain'))+ return [];+ return [{ title: item.title, why: r.suggestion || r.toulmin?.reasoning || undefined }];+ });if (failed.length > 0) context.failedChecks = failed.slice(0, MAX_GOAL_FAILED_CHECKS);return context;} catch {