🤯 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): recover pipeline failures instead of escalating them to a person (#19377)
Arvin Xuf6660c16661f
diff --git a/apps/server/src/services/aiAgent/helpers/heteroErrors.ts b/apps/server/src/services/aiAgent/helpers/heteroErrors.tsindex f58fe51ff01..68b91301777 100644--- a/apps/server/src/services/aiAgent/helpers/heteroErrors.ts+++ b/apps/server/src/services/aiAgent/helpers/heteroErrors.ts@@ -9,7 +9,12 @@ import { ChatErrorType, type ErrorType } from '@lobechat/types';* caller keeps for non-web surfaces (IM bots) while retaining the raw code in* `detail` for diagnostics. Web clients localize via the mapped error type below.*/-const HETERO_DISPATCH_ERROR_HEADLINES: Record<string, string> = {+/**+ * Exported so a consumer that reads a persisted `task.error` can recognise the same+ * failure it would have recognised from the raw code: dispatch failures reach storage+ * as a code on one path and as this headline on another.+ */+export const HETERO_DISPATCH_ERROR_HEADLINES: Record<string, string> = {DEVICE_CHANNEL_UNAVAILABLE:"The device this agent runs on isn't reachable right now — it went offline, went to sleep, or is reconnecting. Check that the LobeHub desktop app (or the `lh` CLI) is running and connected, then try again.",DEVICE_GATEWAY_ERROR:diff --git a/apps/server/src/services/goal/decideNextMove.test.ts b/apps/server/src/services/goal/decideNextMove.test.tsindex fc101fd82c0..a14ca6de28d 100644--- a/apps/server/src/services/goal/decideNextMove.test.ts+++ b/apps/server/src/services/goal/decideNextMove.test.ts@@ -10,6 +10,7 @@ import {needsBudget,needsMetricCriteria,selectFrontier,+ VERIFICATION_ERRORED_ERROR,VERIFICATION_FAILED_ERROR,} from './decideNextMove';@@ -177,6 +178,17 @@ describe('decideNextMove', () => {}).branch,).toBe('recover_verification');+ // A verifier that crashed never judged the delivery, so it recovers like a+ // rejection instead of stopping the goal on a verdict nobody reached.+ expect(+ decide(snapshot, {+ frontierTask: task({ error: VERIFICATION_ERRORED_ERROR, status: 'paused' }),+ }),+ ).toMatchObject({+ branch: 'recover_verification',+ message: 'Verification could not run for Task T-1',+ });+expect(decide(snapshot, { frontierTask: task({ error: 'Device offline', status: 'failed' }) }),).toMatchObject({ branch: 'failure_decision', message: 'Device offline' });diff --git a/apps/server/src/services/goal/decideNextMove.ts b/apps/server/src/services/goal/decideNextMove.tsindex f4a28c4f412..e293f90a21f 100644--- a/apps/server/src/services/goal/decideNextMove.ts+++ b/apps/server/src/services/goal/decideNextMove.ts@@ -5,7 +5,12 @@ import type {GoalTickBranch,GoalTickOutcome,} from '@lobechat/agent-tracing';-import { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';+import {+ GOAL_ACCEPTANCE_TASK_TITLE,+ LEASE_EXPIRED_ERROR,+ VERIFICATION_ERRORED_ERROR,+ VERIFICATION_FAILED_ERROR,+} from '@lobechat/const/goal';import type {GoalGraphNode,GoalGraphSnapshot,@@ -17,8 +22,7 @@ import { toMetricScale } from '@lobechat/types';export { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';/** Reason strings the recovery paths key off, written by the settle path. */-export const LEASE_EXPIRED_ERROR = 'Goal Task operation lease expired.';-export const VERIFICATION_FAILED_ERROR = 'Delivery did not pass verification.';+export { LEASE_EXPIRED_ERROR, VERIFICATION_ERRORED_ERROR, VERIFICATION_FAILED_ERROR };export const TERMINAL_NODE_STATUSES = new Set(['resolved', 'rejected', 'retired']);@@ -89,7 +93,11 @@ export const needsBudget = (task?: TaskItem | null): boolean => {if (task === null) return false;// A failure the coordinator can retry spends money too.if (task.status === 'paused') {- return task.error === LEASE_EXPIRED_ERROR || task.error === VERIFICATION_FAILED_ERROR;+ return (+ task.error === LEASE_EXPIRED_ERROR ||+ task.error === VERIFICATION_FAILED_ERROR ||+ task.error === VERIFICATION_ERRORED_ERROR+ );}return !['completed', 'failed', 'canceled', 'running', 'scheduled'].includes(task.status);};@@ -508,7 +516,9 @@ const decideForTask = (if (budget?.deadlinePassed &&task.status === 'paused' &&- (task.error === LEASE_EXPIRED_ERROR || task.error === VERIFICATION_FAILED_ERROR)+ (task.error === LEASE_EXPIRED_ERROR ||+ task.error === VERIFICATION_FAILED_ERROR ||+ task.error === VERIFICATION_ERRORED_ERROR)) {return {...base,@@ -526,12 +536,22 @@ const decideForTask = (outcome: 'waiting_external',};}- if (task.status === 'paused' && task.error === VERIFICATION_FAILED_ERROR) {+ // A verifier that could not run never evaluated the delivery, so it is an+ // infrastructure failure rather than a verdict. It recovers the same way a+ // rejection does; without a branch it fell through to the human gate, which+ // stopped the goal on a failure nobody needed to judge.+ if (+ task.status === 'paused' &&+ (task.error === VERIFICATION_FAILED_ERROR || task.error === VERIFICATION_ERRORED_ERROR)+ ) {if (!capacity) return 'needs-capacity';return {...base,branch: 'recover_verification',- message: `Task ${task.identifier} did not pass verification`,+ message:+ task.error === VERIFICATION_ERRORED_ERROR+ ? `Verification could not run for Task ${task.identifier}`+ : `Task ${task.identifier} did not pass verification`,outcome: 'waiting_external',};}diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.tsindex 5051dce0b78..019cae810e7 100644--- a/apps/server/src/services/goal/index.test.ts+++ b/apps/server/src/services/goal/index.test.ts@@ -35,10 +35,15 @@ import { TaskService } from '../task';import { TaskRunnerService } from '../taskRunner';import { VerifyPlanGeneratorService } from '../verify/planGenerator';import { GoalCriteriaGeneratorService } from './criteriaGenerator';-import { LEASE_EXPIRED_ERROR, VERIFICATION_FAILED_ERROR } from './decideNextMove';+import {+ LEASE_EXPIRED_ERROR,+ VERIFICATION_ERRORED_ERROR,+ VERIFICATION_FAILED_ERROR,+} from './decideNextMove';import { GoalExplorationPlanner } from './explorationPlanner';import { GoalService } from './index';import { VERIFY_SETTLE_GRACE_MS } from './recoveryPolicy';+import { TaskRecoveryCoordinator } from './taskRecoveryCoordinator';import type { GoalTickObservation } from './traceObservation';const serverDB: LobeChatDatabase = await getTestDB();@@ -397,6 +402,65 @@ describe('GoalService', () => {},);+ it.each([+ [LEASE_EXPIRED_ERROR, 'completed'],+ [LEASE_EXPIRED_ERROR, 'failed'],+ [VERIFICATION_ERRORED_ERROR, 'completed'],+ [VERIFICATION_ERRORED_ERROR, 'canceled'],+ ])('does not restart a Task settled during recovery (%s → %s)', async (error, settledAs) => {+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ title: `Settled during recovery ${error} ${settledAs}`,+ tasks: ['Do not restart'],+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'paused', { error });+ // The advance routed here holding the paused row; a person settled the Task+ // before the claim, which is the row the coordinator now reads.+ const stale = (await taskModel.findById(created.taskId!))!;+ await taskModel.updateStatus(created.taskId!, settledAs, { error: null });+ runSpy.mockClear();++ const recovery = await new TaskRecoveryCoordinator(serverDB, userId).recover({+ goal: (await service.graph(graph.goal.id)).goal,+ task: stale,+ });++ expect(recovery.outcome).toBe('settled');+ expect(runSpy).not.toHaveBeenCalled();+ expect((await taskModel.findById(created.taskId!))?.status).toBe(settledAs);+ });++ it('does not restart a Task a person paused themselves', async () => {+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ title: 'Actor paused during recovery',+ tasks: ['Do not restart'],+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'paused', { error: VERIFICATION_ERRORED_ERROR });+ // A manual round trip keeps the routing error, because the status update replaces+ // it only when a new one is supplied, so the final pause is the person's.+ const taskService = new TaskService(serverDB, userId);+ await taskService.updateStatus({ id: created.taskId!, status: 'failed' }, { userId });+ await taskService.updateStatus({ id: created.taskId!, status: 'paused' }, { userId });+ const stale = (await taskModel.findById(created.taskId!))!;+ runSpy.mockClear();++ const recovery = await new TaskRecoveryCoordinator(serverDB, userId).recover({+ goal: (await service.graph(graph.goal.id)).goal,+ task: stale,+ });++ expect(recovery.outcome).toBe('settled');+ expect(runSpy).not.toHaveBeenCalled();+ expect((await taskModel.findById(created.taskId!))?.status).toBe('paused');+ });+it('hands back a dispatch claim whose worker died before the run existed', async () => {// The claim is taken just before `runTask` creates the topic. If the worker// dies in that sliver the task is `running` with no operation to reclaim,diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.tsindex 4854b978086..e8de164e9b6 100644--- a/apps/server/src/services/goal/index.ts+++ b/apps/server/src/services/goal/index.ts@@ -62,6 +62,7 @@ import {VERIFY_SETTLE_GRACE_MS,} from './recoveryPolicy';import { GoalSupervisorService } from './supervisor';+import { claimGoalTask } from './taskClaim';import { TaskRecoveryCoordinator } from './taskRecoveryCoordinator';import {type GoalTickOptions,@@ -1715,6 +1716,17 @@ export class GoalService {};}+ // Nothing failed: somebody settled the Task while this advance was deciding.+ // Opening a gate would ask them to judge their own decision.+ if (recovery.outcome === 'settled') {+ return {+ goalId: graph.goal.id,+ message: `Task ${task.identifier} was settled while recovery was being decided`,+ nodeId,+ outcome: 'no_progress',+ taskId: task.id,+ };+ }const exhaustedReason =recovery.outcome === 'exhausted-cost'? 'Goal cost budget was exhausted'@@ -1779,12 +1791,10 @@ export class GoalService {).countRunningTasks(goalId);if (inFlight >= resolveMaxConcurrentTasks(graph.goal)) return 'at-capacity' as const;- return new TaskModel(tx, this.userId, this.workspaceId).updateStatusIfCurrent(- task.id,- task.status,- 'running',- { error: null, startedAt: new Date() },- );+ return claimGoalTask(new TaskModel(tx, this.userId, this.workspaceId), task, 'running', {+ error: null,+ startedAt: new Date(),+ });});if (claimed === 'stopped')@@ -1996,6 +2006,17 @@ export class GoalService {};}+ // Nothing failed: somebody settled the Task while this advance was deciding.+ // Opening a gate would ask them to judge their own decision.+ if (recovery.outcome === 'settled') {+ return {+ goalId: graph.goal.id,+ message: `Task ${task.identifier} was settled while recovery was being decided`,+ nodeId,+ outcome: 'no_progress',+ taskId: task.id,+ };+ }const reason =recovery.outcome === 'exhausted-cost'? 'Goal cost budget was exhausted after an operation was abandoned'diff --git a/apps/server/src/services/goal/supervisor/index.test.ts b/apps/server/src/services/goal/supervisor/index.test.tsindex 0e6f11e37cf..b5968da4161 100644--- a/apps/server/src/services/goal/supervisor/index.test.ts+++ b/apps/server/src/services/goal/supervisor/index.test.ts@@ -26,6 +26,7 @@ import {users,} from '@/database/schemas';import { AiAgentService } from '@/server/services/aiAgent';+import { TaskService } from '@/server/services/task';import { TaskRunnerService } from '@/server/services/taskRunner';import { GoalService } from '../index';@@ -116,6 +117,39 @@ const failedGoal = async (enabled = true, error = 'fetch failed: ECONNRESET') =>return { goalId: graph.goal.id, nodeId: created.nodeId!, operationId, taskId };};+/**+ * The run itself settled cleanly and something around it broke: the device link+ * dropped, or verification could not run. The Task is left `paused`, not `failed`,+ * and its operation is `done`, not `error`.+ */+const pipelineFailureGoal = async (+ error = '{"error":"DEVICE_OFFLINE","success":false}',+ withRun = true,+) => {+ const graph = await service().create({+ config: { supervision: { enabled: true } },+ tasks: ['Finish existing report'],+ title: 'Interrupted delivery',+ });+ const created = await service().tick(graph.goal.id);+ const taskId = created.taskId!;+ if (withRun) {+ const topicId = `topic-pipeline-${++sequence}`;+ const operationId = `op-pipeline-${sequence}`;+ await db.insert(topics).values({ id: topicId, userId });+ await operationModel.recordStart({ operationId, taskId, topicId });+ await operationModel.recordCompletion(operationId, {+ completionReason: 'done',+ status: 'done',+ });+ await db+ .insert(taskTopics)+ .values({ operationId, seq: 1, status: 'completed', taskId, topicId, userId });+ }+ await taskModel.update(taskId, { status: 'paused', error, totalTopics: withRun ? 1 : 0 });+ return { goalId: graph.goal.id, taskId };+};+const diagnose = async (goalId: string, action = 'retry') => {const state = (await goalModel.findById(goalId))!.config!.supervisorState!;const incident = state.incidents.at(-1)!;@@ -456,6 +490,78 @@ describe('Goal Supervisor integration', () => {);});+ it('recovers a paused pipeline failure instead of leaving it on the human Gate', async () => {+ const { goalId, taskId } = await pipelineFailureGoal();+ expect((await service().tick(goalId)).outcome).toBe('waiting_external');+ expect((await service().graph(goalId)).decisions).toHaveLength(0);+ await diagnose(goalId);+ expect((await service().tick(goalId)).outcome).toBe('advanced');+ // The Task holds `paused`, so a recovery that only accepted `failed` would+ // silently do nothing here and escalate the incident.+ expect((await taskModel.findById(taskId))?.status).toBe('backlog');+ const graph = await service().graph(goalId);+ expect(graph.goal.config?.supervisorState?.incidents.at(-1)?.status).not.toBe('escalated');+ });++ it('does not overwrite a completion a person recorded during the diagnosis', async () => {+ const { goalId, taskId } = await pipelineFailureGoal();+ expect((await service().tick(goalId)).outcome).toBe('waiting_external');+ await diagnose(goalId);+ // The person settled the Task while the supervisor was still deciding.+ await taskModel.update(taskId, { status: 'completed', error: null });+ await service().tick(goalId);+ expect((await taskModel.findById(taskId))?.status).toBe('completed');+ });++ it('loses the claim when the Task moved to another recoverable state mid-diagnosis', async () => {+ // Routed as `paused`; a person then marks it `failed` without supplying a new+ // error, so the run's transport reason survives and the policy still accepts it.+ // Only claiming against the status the incident was opened on keeps this decision.+ const { goalId, taskId } = await failedGoal(true, '{"error":"DEVICE_OFFLINE","success":false}');+ await taskModel.update(taskId, { status: 'paused' });+ expect((await service().tick(goalId)).outcome).toBe('waiting_external');+ await diagnose(goalId);+ await taskModel.update(taskId, { status: 'failed' });+ await service().tick(goalId);+ expect((await taskModel.findById(taskId))?.status).toBe('failed');+ });++ it('escalates a diagnosis persisted before the opening status was recorded', async () => {+ const { goalId, taskId } = await pipelineFailureGoal();+ expect((await service().tick(goalId)).outcome).toBe('waiting_external');+ await diagnose(goalId);+ // A rolling deploy leaves incidents from the previous version with no record of+ // what they opened on, so they cannot prove the row is still theirs to claim.+ const state = (await goalModel.findById(goalId))!.config!.supervisorState!;+ await goalModel.updateSupervisorState(goalId, state.revision, {+ ...state,+ incidents: state.incidents.map(({ taskStatus: _drop, ...rest }) => rest),+ });+ expect(+ (await goalModel.findById(goalId))!.config!.supervisorState!.incidents.at(-1)?.taskStatus,+ ).toBeUndefined();++ await service().tick(goalId);++ expect((await taskModel.findById(taskId))?.status).toBe('paused');+ const after = (await goalModel.findById(goalId))!.config!.supervisorState!;+ expect(after.incidents.at(-1)?.status).toBe('escalated');+ });++ it('leaves a paused transport failure alone once a person marks it failed', async () => {+ // The run errored with a recoverable transport error and the lifecycle paused the+ // Task. A person then marks it failed without supplying a new error, so the+ // transport text survives and only the transition's author tells them apart.+ const { goalId, taskId } = await failedGoal();+ await taskModel.update(taskId, { status: 'paused' });+ await new TaskService(db, userId).updateStatus({ id: taskId, status: 'failed' }, { userId });++ const move = await service().tick(goalId);++ expect((await taskModel.findById(taskId))?.status).toBe('failed');+ expect(move.outcome).not.toBe('waiting_external');+ });+it('without supervision the same transport failure opens a human Gate', async () => {const { goalId } = await failedGoal(false);expect((await service().tick(goalId)).outcome).toBe('waiting_human');diff --git a/apps/server/src/services/goal/supervisor/index.ts b/apps/server/src/services/goal/supervisor/index.tsindex 43fa57cd9d1..61a83b6964e 100644--- a/apps/server/src/services/goal/supervisor/index.ts+++ b/apps/server/src/services/goal/supervisor/index.ts@@ -21,7 +21,14 @@ import { AiAgentService } from '@/server/services/aiAgent';import { resolveGoalModelConfig } from '../modelConfig';import { scheduleGoalAdvance } from '../scheduler';-import { recoveryEligibility, supervisionLimit, SUPERVISOR_DIAGNOSIS_TIMEOUT_MS } from './policy';+import { claimGoalTask } from '../taskClaim';+import {+ RECOVERABLE_TASK_STATUSES,+ recoveryEligibility,+ statusAuthoredByActor,+ supervisionLimit,+ SUPERVISOR_DIAGNOSIS_TIMEOUT_MS,+} from './policy';/** Durable supervisor with a dedicated, incident-scoped tool set. */export class GoalSupervisorService {@@ -128,6 +135,9 @@ export class GoalSupervisorService {task.id,);const latest = runs[0];+ // A kickoff that threw before writing a run has no operation to key an incident on,+ // and settlement is anchored on that run's sequence. Supervising it needs incident+ // identity and settlement redesigned, so it still reaches a person for now.if (!latest?.operationId) return null;const failedOperation = await operations.findById(latest.operationId);const state = graph.goal.config.supervisorState ?? (await this.initialize(graph));@@ -146,7 +156,13 @@ export class GoalSupervisorService {}return null;}- let eligibility = recoveryEligibility(graph, task, failedOperation);+ const taskModel = new TaskModel(this.db, this.userId, this.workspaceId);+ let eligibility = recoveryEligibility(+ graph,+ task,+ failedOperation,+ statusAuthoredByActor(await taskModel.getActivities(task.id, 20), task.status),+ );if (eligibility.eligible && (await this.budgetBlocked(graph))) {eligibility = {eligible: false,@@ -162,6 +178,7 @@ export class GoalSupervisorService {reason: eligibility.reason,status: eligibility.eligible ? 'diagnosing' : 'escalated',taskId: task.id,+ taskStatus: task.status,};const claimed = await new GoalModel(this.db,@@ -312,15 +329,34 @@ export class GoalSupervisorService {!currentTask ||ownIncident?.status !== 'diagnosing' ||currentRuns[0]?.operationId !== incident.failedOperationId ||- !recoveryEligibility(currentGraph, currentTask, failedOperation).eligible ||+ !recoveryEligibility(+ currentGraph,+ currentTask,+ failedOperation,+ statusAuthoredByActor(+ await new TaskModel(tx, this.userId, this.workspaceId).getActivities(task.id, 20),+ currentTask.status,+ ),+ ).eligible ||(await new GoalSupervisorService(tx, this.userId, this.workspaceId).budgetBlocked(currentGraph,)))return false;- const changed = await new TaskModel(tx, this.userId, this.workspaceId).updateStatusIfCurrent(- task.id,- 'failed',+ // A diagnosis takes minutes, so claim against the status the incident was+ // opened on. Re-reading first and comparing against that would swap whatever+ // the person chose in the meantime.+ if (!RECOVERABLE_TASK_STATUSES.has(currentTask.status)) return false;+ // An incident persisted before this field existed cannot say what it opened+ // on, so it cannot show the row is unchanged. Claiming against a later read+ // would restore the race this closes; a rolling deploy leaves at most the+ // handful mid-diagnosis, and they escalate rather than retry silently.+ if (!ownIncident.taskStatus) return false;+ const changed = await claimGoalTask(+ new TaskModel(tx, this.userId, this.workspaceId),+ // The status this incident opened on, so anything a person did across the+ // whole diagnosis wins the race rather than only a change since this tick.+ { id: task.id, status: ownIncident.taskStatus },'backlog',{ error: null },);diff --git a/apps/server/src/services/goal/supervisor/policy.test.ts b/apps/server/src/services/goal/supervisor/policy.test.tsindex d6c9879f402..bbbf585d283 100644--- a/apps/server/src/services/goal/supervisor/policy.test.ts+++ b/apps/server/src/services/goal/supervisor/policy.test.ts@@ -3,8 +3,9 @@ import { summarizeGoalSupervision } from '@lobechat/types';import { describe, expect, it } from 'vitest';import type { AgentOperationItem } from '@/database/schemas/agentOperations';+import { humanizeHeteroDispatchError } from '@/server/services/aiAgent/helpers/heteroErrors';-import { recoveryEligibility } from './policy';+import { recoveryEligibility, statusAuthoredByActor } from './policy';const graph = {decisions: [],@@ -62,6 +63,74 @@ describe('supervisor recovery authority', () => {).toBe(false);});+ const settled = { completionReason: 'done', status: 'done' } as AgentOperationItem;++ it('recovers a dispatch the gateway says never started, in either stored shape', () => {+ // The run finished or never began and the device link broke around it, so there is+ // no errored operation to read: the dispatch failure is the only evidence. It+ // reaches storage as a raw code from the coordinator's dispatch and as the+ // humanized headline once the runtime finalizes it.+ for (const error of [+ '{"error":"DEVICE_OFFLINE","success":false}',+ 'DEVICE_GATEWAY_RATE_LIMITED',+ // A gateway 500 lands here, outside the transport regex's 502-504.+ 'DEVICE_GATEWAY_ERROR (HTTP 500)',+ humanizeHeteroDispatchError('DEVICE_OFFLINE'),+ humanizeHeteroDispatchError('DEVICE_GATEWAY_UNREACHABLE'),+ humanizeHeteroDispatchError('DEVICE_GATEWAY_ERROR'),+ ])+ expect(+ recoveryEligibility(graph, { ...task, error, status: 'paused' }, settled).eligible,+ ).toBe(true);+ });++ it('keeps a dispatch failure a retry cannot fix, or whose outcome is unknown, with a person', () => {+ for (const error of [+ 'DEVICE_GATEWAY_UNAUTHORIZED',+ 'GATEWAY_NOT_CONFIGURED',+ 'DEVICE_RESPONSE_TIMEOUT',+ humanizeHeteroDispatchError('DEVICE_RESPONSE_TIMEOUT'),+ humanizeHeteroDispatchError('GATEWAY_NOT_CONFIGURED'),+ ])+ expect(+ recoveryEligibility(graph, { ...task, error, status: 'paused' }, settled).eligible,+ ).toBe(false);+ });++ it('leaves a status a person wrote to the person, whatever the error says', () => {+ const errored = { ...operation, error: { message: 'ECONNRESET' } } as AgentOperationItem;+ // The run genuinely errored and the Task was paused with recoverable text; a+ // person then marked it failed without supplying a new error, so the text stayed.+ // Only the transition's author separates this from the failure it looks like.+ expect(recoveryEligibility(graph, task, errored, true).eligible).toBe(false);+ expect(recoveryEligibility(graph, task, errored, false).eligible).toBe(true);+ // Same for a dispatch failure a person closed out.+ const stalled = { ...task, error: '{"error":"DEVICE_OFFLINE","success":false}' };+ expect(recoveryEligibility(graph, stalled, settled, true).eligible).toBe(false);+ expect(recoveryEligibility(graph, { ...stalled, status: 'paused' }, settled).eligible).toBe(+ true,+ );+ });++ it('still refuses a pipeline failure that a person or a limit caused', () => {+ expect(+ recoveryEligibility(+ graph,+ { ...task, error: 'device unauthorized', status: 'paused' },+ settled,+ ).eligible,+ ).toBe(false);+ expect(+ recoveryEligibility(graph, { ...task, status: 'paused' }, {+ ...settled,+ completionReason: 'cost_limit',+ } as AgentOperationItem).eligible,+ ).toBe(false);+ expect(+ recoveryEligibility(graph, { ...task, totalTopics: 3, status: 'paused' }, settled).eligible,+ ).toBe(false);+ });+it('respects attempt exhaustion and explicit manual decisions', () => {expect(recoveryEligibility(graph, { ...task, totalTopics: 3 }, operation).eligible).toBe(false);expect(@@ -74,6 +143,48 @@ describe('supervisor recovery authority', () => {});});+describe('status provenance', () => {+ const act = (over: Record<string, unknown> = {}) => ({+ actorAgentId: null,+ actorUserId: null,+ payload: { to: 'failed' },+ type: 'status',+ ...over,+ });++ it('reads the author of the transition that produced the current status', () => {+ expect(statusAuthoredByActor([act({ actorUserId: 'u1' })], 'failed')).toBe(true);+ expect(statusAuthoredByActor([act({ actorAgentId: 'a1' })], 'failed')).toBe(true);+ // The pipeline writes without an actor.+ expect(statusAuthoredByActor([act()], 'failed')).toBe(false);+ // A later pipeline transition supersedes an earlier authored one.+ expect(+ statusAuthoredByActor(+ [act({ actorUserId: 'u1' }), act({ payload: { to: 'paused' } })],+ 'paused',+ ),+ ).toBe(false);+ // An authored move somewhere else does not speak for this status.+ expect(statusAuthoredByActor([act({ actorUserId: 'u1' })], 'paused')).toBe(false);+ expect(statusAuthoredByActor([], 'failed')).toBe(false);+ // Assignee changes are not status provenance.+ expect(+ statusAuthoredByActor([act({ actorUserId: 'u1', type: 'assignee_user' })], 'failed'),+ ).toBe(false);+ // Deleting the actor clears the id columns, so "someone who is gone" would read+ // as the system without the durable kind written beside them.+ expect(+ statusAuthoredByActor([act({ payload: { actorKind: 'agent', to: 'failed' } })], 'failed'),+ ).toBe(true);+ expect(+ statusAuthoredByActor([act({ payload: { actorKind: 'user', to: 'failed' } })], 'failed'),+ ).toBe(true);+ expect(+ statusAuthoredByActor([act({ payload: { actorKind: 'system', to: 'failed' } })], 'failed'),+ ).toBe(false);+ });+});+describe('effective recovery metric', () => {it('does not count a diagnosis, restart or human continuation as an effective recovery', () => {const state = {diff --git a/apps/server/src/services/goal/supervisor/policy.ts b/apps/server/src/services/goal/supervisor/policy.tsindex 6ab96e4c437..0dc29d32797 100644--- a/apps/server/src/services/goal/supervisor/policy.ts+++ b/apps/server/src/services/goal/supervisor/policy.ts@@ -1,6 +1,13 @@-import type { GoalGraphSnapshot, GoalItem, TaskItem } from '@lobechat/types';+import type {+ AgentOperationCompletionReason,+ AgentOperationStatus,+ GoalGraphSnapshot,+ GoalItem,+ TaskItem,+} from '@lobechat/types';import type { AgentOperationItem } from '@/database/schemas/agentOperations';+import { HETERO_DISPATCH_ERROR_HEADLINES } from '@/server/services/aiAgent/helpers/heteroErrors';import { resolveTaskAttemptBudget } from '../recoveryPolicy';@@ -10,30 +17,120 @@ export const MAX_SUPERVISION_INCIDENTS = 100;export const supervisionLimit = (goal: GoalItem) =>Math.min(MAX_SUPERVISION_INCIDENTS, Math.max(1, goal.config?.supervision?.maxIncidents ?? 10));-/** Recognised transport failures only. Unknown failures need a person in v1. */+/** A limit or a person stopped the run, so continuing is not the supervisor's call. */+const INTERVENTION_REASONS = new Set<AgentOperationCompletionReason>([+ 'cost_limit',+ 'interrupted',+ 'max_steps',+ 'waiting_for_human',+]);++/**+ * Only a Task the coordinator routed to recovery may be restarted. Anything else —+ * a cancellation, or a completion a person recorded while the diagnosis ran — is a+ * decision supervision must not overwrite.+ */+export const RECOVERABLE_TASK_STATUSES = new Set(['failed', 'paused']);++/**+ * Whether the Task's current status was written by a person or an agent tool rather+ * than by the pipeline. `updateWithLog` records an actor on every tracked transition,+ * which is the only way to tell an authored `failed` from a run that failed into one:+ * both can carry the same recoverable error text.+ */+export const statusAuthoredByActor = (+ activities: {+ actorAgentId?: string | null;+ actorUserId?: string | null;+ payload?: unknown;+ type: string;+ }[],+ status: string,+): boolean => {+ const latest = [...activities].reverse().find((item) => item.type === 'status');+ const payload = latest?.payload as { actorKind?: string; to?: string } | undefined;+ if (!latest || payload?.to !== status) return false;+ // The id columns are cleared when the actor is deleted, so a transition made by+ // someone who has since left would read as the system's. `actorKind` is written+ // beside them precisely so it survives that; fall back to the ids only for rows+ // written before it existed.+ if (payload?.actorKind) return payload.actorKind !== 'system';+ return Boolean(latest.actorUserId || latest.actorAgentId);+};++/** The run has not settled yet; the lease reclaim owns it, not recovery. */+const IN_FLIGHT_STATUSES = new Set<AgentOperationStatus>([+ 'idle',+ 'running',+ 'waiting_for_async_tool',+ 'waiting_for_human',+]);++/**+ * Gateway codes whose own message states the run never started, so a retry cannot+ * duplicate committed work. `DEVICE_GATEWAY_UNAUTHORIZED` and `GATEWAY_NOT_CONFIGURED`+ * say retrying will not help, `DEVICE_RESPONSE_TIMEOUT` says whether the run started is+ * unknown, and `DEVICE_NOT_FOUND` needs someone to reconnect or rebind; those stay with+ * a person.+ */+const RETRYABLE_DISPATCH_CODES = [+ 'DEVICE_OFFLINE',+ 'DEVICE_CHANNEL_UNAVAILABLE',+ // Any gateway 5xx, so it covers the 500 the transport regex's 502-504 misses.+ 'DEVICE_GATEWAY_ERROR',+ 'DEVICE_GATEWAY_UNREACHABLE',+ 'DEVICE_GATEWAY_RATE_LIMITED',+];++/**+ * The same failure reaches `task.error` as a raw code when the coordinator's own+ * dispatch fails, and as the humanized headline when the runtime finalizes it. Match+ * both, off the one map, so neither storage shape decides whether a person is needed.+ */+const isRetryableDispatchFailure = (error: string) =>+ RETRYABLE_DISPATCH_CODES.some(+ (code) =>+ error.includes(code) ||+ (HETERO_DISPATCH_ERROR_HEADLINES[code] &&+ error.includes(HETERO_DISPATCH_ERROR_HEADLINES[code])),+ );+export const recoveryEligibility = (graph: GoalGraphSnapshot,task: TaskItem,operation?: AgentOperationItem,+ /** Whether the Task's current status was written by a person or an agent tool. */+ actorAuthoredStatus = false,): { eligible: boolean; reason: string } => {if (!graph.goal.config?.supervision?.enabled && !graph.goal.config?.manager)return { eligible: false, reason: 'Supervision is disabled' };if (graph.goal.status !== 'running' || graph.decisions.some((d) => d.status === 'pending')) {return { eligible: false, reason: 'Goal is stopped or has a pending decision' };}- if (task.status !== 'failed' || !operation || operation.status !== 'error') {- return { eligible: false, reason: 'Only a confirmed failed operation can be recovered' };+ if (operation && IN_FLIGHT_STATUSES.has(operation.status)) {+ return { eligible: false, reason: 'The operation has not settled yet' };}if (- operation.interruption ||- (operation.completionReason && operation.completionReason !== 'error')+ operation?.interruption ||+ (operation?.completionReason && INTERVENTION_REASONS.has(operation.completionReason))) {return { eligible: false, reason: 'Operation stopped at an explicit intervention or limit' };}+ if (!RECOVERABLE_TASK_STATUSES.has(task.status)) {+ return { eligible: false, reason: `A ${task.status} Task is not supervision's to restart` };+ }+ // `TaskService.updateStatus` replaces `error` only when a new one is supplied, so a+ // person can move a Task the pipeline paused — or one whose run genuinely errored —+ // to `failed` and leave the recoverable text behind. Reading the error cannot tell+ // the two apart, so ask who wrote the status: `updateWithLog` records the actor on+ // every tracked transition, and a transition somebody made is theirs to undo.+ if (actorAuthoredStatus) {+ return { eligible: false, reason: 'Someone set this status themselves' };+ }if ((task.totalTopics ?? 0) >= resolveTaskAttemptBudget(graph.goal)) {return { eligible: false, reason: 'Task attempt budget exhausted' };}- const error = `${operation.error?.type ?? ''} ${operation.error?.message ?? ''} ${task.error ?? ''}`;+ const error = `${operation?.error?.type ?? ''} ${operation?.error?.message ?? ''} ${task.error ?? ''}`;if (/auth|credential|api.?key|permission|approv|forbidden|unauthor|usage.?limit|quota|billing|budget|cancel|用户|授权|凭据|额度/i.test(error,@@ -44,7 +141,13 @@ export const recoveryEligibility = (reason: 'Credentials, permission, cancellation or spending requires user action',};}+ // One allowlist for both origins, read off whatever error text exists. Inferring a+ // recoverable failure from the *absence* of a run error is an open set: every state+ // an actor can author — a Task marked failed through the API, a settled run someone+ // reopened — arrives looking exactly like a dropped dispatch. Recognising the+ // failures instead keeps an authored decision with the person who made it.if (+ !isRetryableDispatchFailure(error) &&!/ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|fetch failed|network error|socket hang up|service unavailable|bad gateway|gateway timeout|\b50[234]\b/i.test(error,)diff --git a/apps/server/src/services/goal/taskClaim.ts b/apps/server/src/services/goal/taskClaim.tsnew file mode 100644index 00000000000..8daca162d0f--- /dev/null+++ b/apps/server/src/services/goal/taskClaim.ts@@ -0,0 +1,21 @@+import type { TaskModel } from '@/database/models/task';++/**+ * The one place a Goal moves a Task back into work.+ *+ * Every such write competes with a person. Between the tick that decided to act and+ * the write that acts, someone can complete, cancel or fail the Task, and a+ * supervisor diagnosis can sit in between for minutes. So the claim is conditioned on+ * the status the decision was made against — never on a freshly re-read one, which+ * would swap whatever the person just chose and start paid work over their decision.+ *+ * Losing the compare-and-set is the correct outcome, not an error: it means the row+ * moved, so this decision is stale and belongs to whoever moved it.+ */+export const claimGoalTask = async (+ taskModel: TaskModel,+ /** The Task as the caller read it when it decided, not a fresh re-read. */+ decidedOn: { id: string; status: string },+ to: 'backlog' | 'running',+ extra?: { error?: string | null; startedAt?: Date },+) => taskModel.updateStatusIfCurrent(decidedOn.id, decidedOn.status, to, extra);diff --git a/apps/server/src/services/goal/taskRecoveryCoordinator.ts b/apps/server/src/services/goal/taskRecoveryCoordinator.tsindex f0a0a5ddf43..4affd3ea6d6 100644--- a/apps/server/src/services/goal/taskRecoveryCoordinator.ts+++ b/apps/server/src/services/goal/taskRecoveryCoordinator.ts@@ -7,6 +7,8 @@ import type { LobeChatDatabase } from '@/database/type';import { TaskRunnerService } from '@/server/services/taskRunner';import { resolveTaskAttemptBudget, resolveTaskMaxSteps } from './recoveryPolicy';+import { statusAuthoredByActor } from './supervisor/policy';+import { claimGoalTask } from './taskClaim';const log = debug('lobe-server:goal-task-recovery');@@ -15,6 +17,8 @@ export type TaskRecoveryOutcome =| 'started'/** Another overlapping advance owns the retry; this one started nothing. */| 'already-running'+ /** Someone settled the Task while this recovery was being decided. */+ | 'settled'| 'exhausted-cost'| 'exhausted-rounds'| 'spawn-failed';@@ -73,7 +77,26 @@ export class TaskRecoveryCoordinator {log('task %s recovery was already claimed by another advance', task.identifier);return { outcome: 'already-running' };}- const claimed = await taskModel.updateStatusIfCurrent(task.id, current.status, 'running', {+ // Both branches that route here require `paused`, so that is the only status this+ // claim may take. The tick read the Task before it decided; claiming whatever it+ // holds now would swap somebody's completion, cancellation or explicit failure to+ // `running` and start a paid run over their decision.+ if (current.status !== 'paused') {+ log(+ 'task %s moved to %s before the claim; leaving it alone',+ task.identifier,+ current.status,+ );+ return { outcome: 'settled' };+ }+ // A pause somebody made is theirs. The routing error survives a manual round trip+ // through another status, because the status update keeps the old error when none+ // is supplied, so the status alone cannot say whose pause this is.+ if (statusAuthoredByActor(await taskModel.getActivities(task.id, 20), current.status)) {+ log('task %s was paused by an actor; leaving it alone', task.identifier);+ return { outcome: 'settled' };+ }+ const claimed = await claimGoalTask(taskModel, { id: task.id, status: 'paused' }, 'running', {error: null,startedAt: new Date(),});@@ -94,7 +117,7 @@ export class TaskRecoveryCoordinator {log('task %s recovery spawn failed (non-fatal): %O', task.identifier, error);// We own the claim, so nothing else will put the task back.await taskModel- .updateStatusIfCurrent(task.id, 'running', current.status, { error: current.error })+ .updateStatusIfCurrent(task.id, 'running', 'paused', { error: current.error }).catch((releaseError) => {log('task %s failed to release the recovery claim: %O', task.identifier, releaseError);});diff --git a/apps/server/src/services/verify/settle.ts b/apps/server/src/services/verify/settle.tsindex 46949404a89..3c5e34d8468 100644--- a/apps/server/src/services/verify/settle.ts+++ b/apps/server/src/services/verify/settle.ts@@ -1,3 +1,4 @@+import { VERIFICATION_ERRORED_ERROR, VERIFICATION_FAILED_ERROR } from '@lobechat/const/goal';import debug from 'debug';import { AgentOperationModel } from '@/database/models/agentOperation';@@ -137,12 +138,11 @@ export const driveTaskFromVerify = async (// evaluated, so we must not claim it "did not pass".const isErrored = outcome === 'errored';- // `Delivery did not pass verification.` is a contract string, not just- // copy: the Goal coordinator matches on it to decide whether a paused- // Goal Task should start another attempt or open a decision gate.- const pauseSummary = isErrored- ? 'Verification could not run (internal error); the delivery was not evaluated.'- : 'Delivery did not pass verification.';+ // Both summaries are contract strings, not copy: the Goal coordinator+ // matches on them to decide whether a paused Goal Task starts another+ // attempt or opens a decision gate. They live in `@lobechat/const/goal`+ // so the writer and the reader cannot drift apart.+ const pauseSummary = isErrored ? VERIFICATION_ERRORED_ERROR : VERIFICATION_FAILED_ERROR;if (task.automationMode) {// Mirror of the pass branch: verify judges THIS tick, not the lifetime// schedule. Pausing here would permanently disarm the cron (thediff --git a/packages/const/src/goal.ts b/packages/const/src/goal.tsindex d7233cbf729..7f381a7c04f 100644--- a/packages/const/src/goal.ts+++ b/packages/const/src/goal.ts@@ -49,3 +49,18 @@ export const GOAL_COORDINATOR_ACTOR_ID = 'goal-coordinator';* recognize it and render the localized copy (`goalProcess.node.terminalAcceptance`).*/export const GOAL_ACCEPTANCE_TASK_TITLE = 'Complete full Goal acceptance';++/**+ * Task error strings the Goal coordinator matches on to route a paused Task.+ *+ * These are a contract between whoever pauses a Task and the coordinator that+ * reads it back, not user-facing copy. A string with no branch here falls+ * through to the human decision gate, so an unmatched infrastructure failure+ * stops a long-horizon goal until a person clicks retry.+ */+export const LEASE_EXPIRED_ERROR = 'Goal Task operation lease expired.';+/** The verifier ran and judged the delivery short of the criteria. */+export const VERIFICATION_FAILED_ERROR = 'Delivery did not pass verification.';+/** The verifier itself could not run, so the delivery was never evaluated. */+export const VERIFICATION_ERRORED_ERROR =+ 'Verification could not run (internal error); the delivery was not evaluated.';diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.tsindex 05a4b304c36..d32b26ec13f 100644--- a/packages/types/src/goal.ts+++ b/packages/types/src/goal.ts@@ -165,6 +165,12 @@ export interface GoalSupervisionIncident {status: 'diagnosing' | 'retrying' | 'recovered' | 'escalated' | 'unsuccessful' | 'human_resumed';supervisorOperationId?: string;taskId: string;+ /**+ * Status the Task held when this incident opened. A diagnosis runs for minutes, so+ * the recovery claims against this rather than a later read: anything a person did+ * in between must win, not be swapped back into work.+ */+ taskStatus?: string;}/** Server-owned state; never accepted as client configuration. */