🤯 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 Task acceptance loops on stale review, repeated failures and silent spawn errors (#21564)
LiJian04c60cd113ef
diff --git a/apps/cli/src/api/workspace.test.ts b/apps/cli/src/api/workspace.test.tsindex a74b13b5993..90f420f1a0d 100644--- a/apps/cli/src/api/workspace.test.ts+++ b/apps/cli/src/api/workspace.test.ts@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { log } from '../utils/logger';import {__resetStaleScopeWarning,+ describeScopedNotFound,resolveWorkspaceId,resolveWorkspaceScope,withWorkspaceHeader,@@ -88,6 +89,37 @@ describe('api/workspace scope resolution', () => {expect(resolveWorkspaceScope()).toEqual({ source: 'env', workspaceId: 'ws_env' });});+ // `workspace use --personal` rewrites the machine-wide default, and an empty+ // env value falls through to it, so a single personal-space lookup had no way+ // to leave the saved workspace alone.+ it('runs one command in personal scope without touching the saved workspace', () => {+ process.env.LOBEHUB_WORKSPACE_ID = 'personal';+ mockLoadActiveWorkspace.mockReturnValue(stored());++ expect(resolveWorkspaceScope()).toEqual({ source: 'env' });+ expect(withWorkspaceHeader({ 'Oidc-Auth': 'token' })).toEqual({ 'Oidc-Auth': 'token' });+ });++ describe('describeScopedNotFound', () => {+ const notFound = { data: { code: 'NOT_FOUND' }, message: 'Goal not found' };++ it('says where it looked and how to look in personal space', () => {+ mockLoadActiveWorkspace.mockReturnValue(stored());++ expect(describeScopedNotFound(notFound)).toBe(+ 'Looked in workspace ws_stored. If it is in your personal space, rerun with LOBEHUB_WORKSPACE_ID=personal; for another workspace, set LOBEHUB_WORKSPACE_ID=<id>.',+ );+ });++ it('stays quiet in personal scope and for other errors', () => {+ expect(describeScopedNotFound(notFound)).toBeUndefined();++ mockLoadActiveWorkspace.mockReturnValue(stored());+ expect(describeScopedNotFound({ data: { code: 'FORBIDDEN' } })).toBeUndefined();+ expect(describeScopedNotFound(new Error('Goal not found'))).toBeUndefined();+ });+ });+it('prefers an explicit argument over everything else', () => {process.env.LOBEHUB_WORKSPACE_ID = 'ws_env';mockLoadActiveWorkspace.mockReturnValue(stored());diff --git a/apps/cli/src/api/workspace.ts b/apps/cli/src/api/workspace.tsindex fbf41431afa..ace8217a5dd 100644--- a/apps/cli/src/api/workspace.ts+++ b/apps/cli/src/api/workspace.ts@@ -1,9 +1,19 @@+import { toRecord } from '@lobechat/utils/object';+import { resolveIdentityFingerprint } from '../auth/identity';import { loadActiveWorkspace, resolveServerUrl } from '../settings';import { log } from '../utils/logger';export const WORKSPACE_ID_HEADER = 'X-Workspace-Id';+/**+ * `LOBEHUB_WORKSPACE_ID=personal` runs one command in personal scope. An empty+ * value falls through to the saved scope, and `workspace use --personal`+ * rewrites that scope for every later command, so there was no way to look+ * something up in personal space without changing the machine's default.+ */+export const PERSONAL_SCOPE_ENV_VALUE = 'personal';+export type WorkspaceScopeSource = 'explicit' | 'env' | 'settings' | 'stale' | 'personal';export interface WorkspaceScope {@@ -56,6 +66,7 @@ export function resolveWorkspaceScope(explicit?: string): WorkspaceScope {if (explicit) return { source: 'explicit', workspaceId: explicit };const fromEnv = process.env.LOBEHUB_WORKSPACE_ID;+ if (fromEnv === PERSONAL_SCOPE_ENV_VALUE) return { source: 'env' };if (fromEnv && fromEnv.length > 0) return { source: 'env', workspaceId: fromEnv };// A server-dispatched execution (operation-scoped `LOBEHUB_JWT`) carries its@@ -70,6 +81,20 @@ export function resolveWorkspaceScope(explicit?: string): WorkspaceScope {return resolvePersistedScope() ?? { source: 'personal' };}+/**+ * The hint a `NOT_FOUND` needs when the command ran in a workspace scope. The+ * server cannot tell "does not exist" from "lives in another space", so a bare+ * "Goal not found" sent callers hunting for a deleted goal that was sitting in+ * their personal space.+ */+export function describeScopedNotFound(error: unknown): string | undefined {+ const data = toRecord(toRecord(error)?.data);+ if (data?.code !== 'NOT_FOUND') return;+ const { workspaceId } = resolveWorkspaceScope();+ if (!workspaceId) return;+ return `Looked in workspace ${workspaceId}. If it is in your personal space, rerun with LOBEHUB_WORKSPACE_ID=${PERSONAL_SCOPE_ENV_VALUE}; for another workspace, set LOBEHUB_WORKSPACE_ID=<id>.`;+}+export function resolveWorkspaceId(explicit?: string): string | undefined {return resolveWorkspaceScope(explicit).workspaceId;}diff --git a/apps/cli/src/commands/acceptance/run/ingest.test.ts b/apps/cli/src/commands/acceptance/run/ingest.test.tsindex cff4d77e563..4012609cf28 100644--- a/apps/cli/src/commands/acceptance/run/ingest.test.ts+++ b/apps/cli/src/commands/acceptance/run/ingest.test.ts@@ -331,7 +331,7 @@ describe('verify ingest-report — every run is an immutable acceptance round',hint: 'LOBEHUB_WORKSPACE_ID=workspace-target',target: 'workspace-target',},- { current: 'workspace-current', hint: 'lh workspace use --personal', target: null },+ { current: 'workspace-current', hint: 'LOBEHUB_WORKSPACE_ID=personal', target: null },])('rejects scope $current → $target before any remote writes',async ({ current, target, hint }) => {diff --git a/apps/cli/src/commands/acceptance/run/ingest.ts b/apps/cli/src/commands/acceptance/run/ingest.tsindex 04ee696994e..5009bccd43c 100644--- a/apps/cli/src/commands/acceptance/run/ingest.ts+++ b/apps/cli/src/commands/acceptance/run/ingest.ts@@ -8,7 +8,7 @@ import type { Command } from 'commander';import pc from 'picocolors';import { getTrpcClient } from '../../../api/client';-import { resolveWorkspaceId } from '../../../api/workspace';+import { PERSONAL_SCOPE_ENV_VALUE, resolveWorkspaceId } from '../../../api/workspace';import { resolveServerUrl } from '../../../settings';import { ensureAcceptanceDirIgnoredFor } from '../../../utils/acceptanceDir';import { outputJson } from '../../../utils/format';@@ -325,7 +325,7 @@ export async function ingestReportAction(const target = targetWorkspaceId ? `workspace "${targetWorkspaceId}"` : 'personal space';const hint = targetWorkspaceId? `Set LOBEHUB_WORKSPACE_ID=${targetWorkspaceId} for this command and retry.`- : "Unset LOBEHUB_WORKSPACE_ID and run 'lh workspace use --personal', then retry.";+ : `Set LOBEHUB_WORKSPACE_ID=${PERSONAL_SCOPE_ENV_VALUE} for this command and retry.`;throw new Error(`Acceptance "${acceptance.id}" belongs to ${target}, but the CLI is using ${current}. ${hint} No run was created.`,);diff --git a/apps/cli/src/commands/workspace.ts b/apps/cli/src/commands/workspace.tsindex 5fd92d75c92..cca6dd3b136 100644--- a/apps/cli/src/commands/workspace.ts+++ b/apps/cli/src/commands/workspace.ts@@ -2,7 +2,11 @@ import type { Command } from 'commander';import pc from 'picocolors';import { getTrpcClient } from '../api/client';-import { resolveWorkspaceScope, type WorkspaceScope } from '../api/workspace';+import {+ PERSONAL_SCOPE_ENV_VALUE,+ resolveWorkspaceScope,+ type WorkspaceScope,+} from '../api/workspace';import { resolveIdentityFingerprint } from '../auth/identity';import { CLI_PRIMARY_BIN } from '../constants/identity';import { type ActiveWorkspaceRecord, resolveServerUrl, saveActiveWorkspace } from '../settings';@@ -31,7 +35,9 @@ const SCOPE_HINTS: Record<WorkspaceScope['source'], string> = {const describeScope = (scope: WorkspaceScope): string =>scope.workspaceId? `workspace ${scope.workspaceId} ${pc.dim(`(from ${SCOPE_HINTS[scope.source]})`)}`- : pc.dim(SCOPE_HINTS[scope.source === 'stale' ? 'stale' : 'personal']);+ : scope.source === 'env'+ ? pc.dim(`personal (from LOBEHUB_WORKSPACE_ID=${PERSONAL_SCOPE_ENV_VALUE})`)+ : pc.dim(SCOPE_HINTS[scope.source === 'stale' ? 'stale' : 'personal']);/*** Every workspace-scoped read goes through the workspace header, so a commanddiff --git a/apps/cli/src/doctor/checks/scope.test.ts b/apps/cli/src/doctor/checks/scope.test.tsindex b3bbc743d21..7c20e7bfa42 100644--- a/apps/cli/src/doctor/checks/scope.test.ts+++ b/apps/cli/src/doctor/checks/scope.test.ts@@ -37,6 +37,22 @@ describe('scope.workspace', () => {expect(outcome.detail).toContain('Personal scope');});+ it('reads LOBEHUB_WORKSPACE_ID=personal as personal scope, not a workspace id', async () => {+ process.env.LOBEHUB_WORKSPACE_ID = 'personal';+ state.stored = {+ identity: 'user:me',+ serverUrl: 'https://app.lobehub.com',+ workspaceId: 'ws_saved',+ };++ const outcome = await runCheck(scopeChecks, 'scope.workspace');++ expect(outcome.status).toBe('ok');+ expect(outcome.detail).toBe(+ 'Personal scope: LOBEHUB_WORKSPACE_ID=personal overrides the saved scope ws_saved for this run.',+ );+ });+it('redacts a basic-auth server URL before it reaches the report', async () => {// Found by sweeping every check's evidence for an injected credential.state.serverUrl = 'https://alice:[email protected]';diff --git a/apps/cli/src/doctor/checks/scope.ts b/apps/cli/src/doctor/checks/scope.tsindex 71b8464c017..bb205f89bd8 100644--- a/apps/cli/src/doctor/checks/scope.ts+++ b/apps/cli/src/doctor/checks/scope.ts@@ -1,3 +1,4 @@+import { PERSONAL_SCOPE_ENV_VALUE } from '../../api/workspace';import { resolveIdentityFingerprint } from '../../auth/identity';import { loadActiveWorkspace, resolveServerUrl, saveActiveWorkspace } from '../../settings';import { redactUrlCredentials } from '../redact';@@ -39,6 +40,15 @@ const workspaceScope: DoctorCheck = {storedWorkspaceId: stored?.workspaceId,};+ if (fromEnv === PERSONAL_SCOPE_ENV_VALUE)+ return {+ detail: stored+ ? `Personal scope: LOBEHUB_WORKSPACE_ID=${PERSONAL_SCOPE_ENV_VALUE} overrides the saved scope ${stored.workspaceId} for this run.`+ : `Personal scope, from LOBEHUB_WORKSPACE_ID=${PERSONAL_SCOPE_ENV_VALUE}.`,+ evidence,+ status: 'ok',+ };+if (fromEnv) {if (stored && stored.workspaceId !== fromEnv)return {diff --git a/apps/cli/src/index.ts b/apps/cli/src/index.tsindex de8a1b3e6e6..5a249c6bcd8 100644--- a/apps/cli/src/index.ts+++ b/apps/cli/src/index.ts@@ -1,3 +1,4 @@+import { describeScopedNotFound } from './api/workspace';import { hydrateJwtFromFile } from './auth/envJwt';import { reportDaemonStartupError } from './daemon/manager';import { createProgram } from './program';@@ -9,7 +10,8 @@ hydrateJwtFromFile();void createProgram().parseAsync(process.argv, { from: 'node' }).catch(async (error: unknown) => {- const message = formatError(error);+ const hint = describeScopedNotFound(error);+ const message = hint ? `${formatError(error)}. ${hint}` : formatError(error);await reportDaemonStartupError(message);log.error(message);process.exit(1);diff --git a/apps/server/src/services/goal/GoalService/__tests__/verificationRecovery.test.ts b/apps/server/src/services/goal/GoalService/__tests__/verificationRecovery.test.tsnew file mode 100644index 00000000000..e906b3358cf--- /dev/null+++ b/apps/server/src/services/goal/GoalService/__tests__/verificationRecovery.test.ts@@ -0,0 +1,142 @@+// @vitest-environment node+import { TRPCError } from '@trpc/server';+import { describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { AcceptanceModel } from '@/database/models/acceptance';+import { TaskModel } from '@/database/models/task';+import { verifyCheckResults, verifyRuns } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++import { TaskRunnerService } from '../../../taskRunner';+import { VERIFICATION_FAILED_ERROR } from '../../decideNextMove';+import { registerGoalServiceTestCleanup } from '../../testUtils';+import { GoalService } from '../index';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'goal-service-test-user';++registerGoalServiceTestCleanup(serverDB, userId);++const planItem = (id: string) => ({+ id,+ index: 0,+ onFail: 'auto_repair' as const,+ required: true,+ title: `Check ${id}`,+ verifierConfig: {},+ verifierType: 'agent' as const,+});++describe('GoalService recovery after a failed verification', () => {+ const setup = async (title: string) => {+ const runSpy = vi+ .spyOn(TaskRunnerService.prototype, 'runTask')+ .mockResolvedValue({ operationId: 'op-retry', success: true } as never);+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { maxAttemptsPerTask: 8 } },+ title,+ tasks: ['Measure input latency'],+ });+ const created = await service.tick(graph.goal.id);+ runSpy.mockClear();+ return { graph, runSpy, service, taskId: created.taskId!, taskModel };+ };++ /** One settled round per attempt, each leaving `failing` open. */+ const settleAttempts = async (taskId: string, failing: string[][]) => {+ // A Goal Task gets its Acceptance when the coordinator creates it.+ const acceptance = (await new AcceptanceModel(serverDB, userId).findBySubject('task', taskId))!;+ for (const [index, open] of failing.entries()) {+ const [run] = await serverDB+ .insert(verifyRuns)+ .values({+ acceptanceId: acceptance.id,+ metadata: { taskDrivenAt: new Date().toISOString() },+ plan: [planItem('input'), planItem('latency')],+ roundIndex: index + 1,+ status: 'failed',+ userId,+ } as never)+ .returning();+ await serverDB.insert(verifyCheckResults).values(+ ['input', 'latency'].map((checkItemId) => {+ const verdict = open.includes(checkItemId) ? ('failed' as const) : ('passed' as const);+ return {+ checkItemId,+ status: verdict,+ userId,+ verdict,+ verifierType: 'agent' as const,+ verifyRunId: run.id,+ };+ }),+ );+ }+ };++ const decisionReasons = async (service: GoalService, goalId: string) =>+ (await service.graph(goalId)).nodes+ .filter((node) => node.kind === 'decision')+ .map((node) => node.description);++ it('asks a person once two attempts fail verification the same way', async () => {+ const { graph, runSpy, service, taskId, taskModel } = await setup('Same failure twice');+ await settleAttempts(taskId, [['latency'], ['latency']]);+ await taskModel.update(taskId, { totalTopics: 2 });+ await taskModel.updateStatus(taskId, 'paused', { error: VERIFICATION_FAILED_ERROR });++ const gated = await service.tick(graph.goal.id);++ expect(runSpy).not.toHaveBeenCalled();+ expect(gated).toMatchObject({ outcome: 'waiting_human', taskId });+ const task = await taskModel.findById(taskId);+ expect(await decisionReasons(service, graph.goal.id)).toEqual([+ `Task ${task!.identifier} failed verification the same way 2 times in a row`,+ ]);+ });++ it('keeps retrying while each attempt fails on something else', async () => {+ const { graph, runSpy, service, taskId, taskModel } = await setup('Different failures');+ await settleAttempts(taskId, [['input'], ['latency']]);+ await taskModel.update(taskId, { totalTopics: 2 });+ await taskModel.updateStatus(taskId, 'paused', { error: VERIFICATION_FAILED_ERROR });++ await service.tick(graph.goal.id);++ expect(runSpy).toHaveBeenCalledOnce();+ });++ it('names why the next attempt could not start', async () => {+ const { graph, runSpy, service, taskId, taskModel } = await setup('Spawn refused');+ await taskModel.update(taskId, { totalTopics: 1 });+ await taskModel.updateStatus(taskId, 'paused', { error: VERIFICATION_FAILED_ERROR });+ runSpy.mockRejectedValue(+ new TRPCError({+ code: 'CONFLICT',+ message: 'Task already has a running topic (tpc_live). Cancel it first or use --continue.',+ }),+ );++ await service.tick(graph.goal.id);++ expect(await decisionReasons(service, graph.goal.id)).toEqual([+ 'Automatic recovery could not start the next attempt: Task already has a running topic (tpc_live). Cancel it first or use --continue',+ ]);+ });++ it('keeps an internal spawn error out of the gate', async () => {+ const { graph, runSpy, service, taskId, taskModel } = await setup('Spawn crashed');+ await taskModel.update(taskId, { totalTopics: 1 });+ await taskModel.updateStatus(taskId, 'paused', { error: VERIFICATION_FAILED_ERROR });+ runSpy.mockRejectedValue(new Error('duplicate key value violates unique constraint "x"'));++ await service.tick(graph.goal.id);++ expect(await decisionReasons(service, graph.goal.id)).toEqual([+ 'Automatic recovery could not start the next attempt',+ ]);+ });+});diff --git a/apps/server/src/services/goal/GoalService/completion.ts b/apps/server/src/services/goal/GoalService/completion.tsindex 4e531263744..5e21f032234 100644--- a/apps/server/src/services/goal/GoalService/completion.ts+++ b/apps/server/src/services/goal/GoalService/completion.ts@@ -8,6 +8,7 @@ import type {WorkVersionEventItem,} from '@lobechat/types';import { experimentOwner } from '@lobechat/utils/goalGraph';+import debug from 'debug';import { GoalGraphModel } from '@/database/models/goalGraph';import { GoalRepository } from '@/database/repositories/goal';@@ -17,10 +18,14 @@ import {type GoalMove,TERMINAL_NODE_STATUSES,} from '../decideNextMove';+import { lastAnsweredGateAt } from '../machineRecovery';import { GoalSupervisorService } from '../supervisor';import { TaskRecoveryCoordinator } from '../taskRecoveryCoordinator';+import { readVerificationStall, REPEATED_FAILURE_LIMIT } from '../verificationStall';import type { GoalServiceContext } from './types';+const log = debug('lobe-server:goal-completion');+/*** Version events read per task run when harvesting deliverables. Generous* because the cap applies to events rather than to Works: the newest N events@@ -181,6 +186,30 @@ export const recoverAfterVerification = async (effects: GoalAdvanceEffect[],): Promise<GoalTickResult> => {const goalId = graph.goal.id;++ // Attempts that keep failing the same way will not stop doing so because the+ // budget allows another: ask a person now, with that as the reason, instead of+ // spending the rest of the budget. An unreadable history keeps the retry.+ const stalled = await readVerificationStall(+ ctx.db,+ { userId: ctx.userId, workspaceId: ctx.workspaceId },+ task.id,+ lastAnsweredGateAt(graph, nodeId),+ ).catch((error) => {+ log('task %s verification history unavailable: %O', task.identifier, error);+ return false;+ });+ if (stalled) {+ return escalateVerificationFailure(+ ctx,+ graph,+ nodeId,+ task,+ `Task ${task.identifier} failed verification the same way ${REPEATED_FAILURE_LIMIT} times in a row`,+ effects,+ );+ }+const taskIds = graph.nodes.flatMap((node) => (node.taskId ? [node.taskId] : []));const runs = await ctx.taskTopicModel.findWithHandoffByTaskIds(taskIds, 10_000);const totalCost = runs.reduce((sum, run) => sum + Number(run.totalCost ?? 0), 0);@@ -259,26 +288,38 @@ export const recoverAfterVerification = async (? 'Goal cost budget was exhausted': recovery.outcome === 'exhausted-rounds'? 'Task attempt budget was exhausted'- : 'Automatic recovery could not start the next attempt';- // R6: a batch member that ran out of attempts to pass its own check breaks- // the class, like one that failed outright — revise the recipe and re-probe,- // not a standalone retry/retire gate (retiring a last-wave member would let- // the goal head for acceptance with the unit undone). A spent goal budget- // and a run that never started are not the recipe's fault: those keep the- // ordinary gate.- if (- recovery.outcome !== 'exhausted-cost' &&- recovery.outcome !== 'spawn-failed' &&- ctx.isBatchMember(graph, nodeId)- ) {+ : `Automatic recovery could not start the next attempt${recovery.error ? `: ${recovery.error}` : ''}`;+ if (recovery.outcome === 'spawn-failed') {+ return ctx.gateOrTakeOver(graph, nodeId, task.id, exhaustedReason, effects, { machine: true });+ }+ // A spent goal budget is not the recipe's fault either: the ordinary gate.+ if (recovery.outcome === 'exhausted-cost') {+ return ctx.gateOrTakeOver(graph, nodeId, task.id, exhaustedReason, effects);+ }+ return escalateVerificationFailure(ctx, graph, nodeId, task, exhaustedReason, effects);+};++/**+ * Hand a Task that cannot pass its verification on its own to a person.+ *+ * R6: a batch member that cannot pass its own check breaks the class, like one+ * that failed outright — revise the recipe and re-probe, not a standalone+ * retry/retire gate (retiring a last-wave member would let the goal head for+ * acceptance with the unit undone).+ */+const escalateVerificationFailure = (+ ctx: GoalServiceContext,+ graph: GoalGraphSnapshot,+ nodeId: string,+ task: TaskItem,+ reason: string,+ effects: GoalAdvanceEffect[],+): Promise<GoalTickResult> => {+ if (ctx.isBatchMember(graph, nodeId)) {const title = graph.nodes.find((node) => node.id === nodeId)?.title ?? task.identifier;- return ctx.openPatternBreakGate(graph, `${title}: ${exhaustedReason}`, effects, {- unitId: nodeId,- });+ return ctx.openPatternBreakGate(graph, `${title}: ${reason}`, effects, { unitId: nodeId });}- return ctx.gateOrTakeOver(graph, nodeId, task.id, exhaustedReason, effects, {- machine: recovery.outcome === 'spawn-failed',- });+ return ctx.gateOrTakeOver(graph, nodeId, task.id, reason, effects);};/**diff --git a/apps/server/src/services/goal/GoalService/recovery.ts b/apps/server/src/services/goal/GoalService/recovery.tsindex be9f548ded6..146fc1bdee8 100644--- a/apps/server/src/services/goal/GoalService/recovery.ts+++ b/apps/server/src/services/goal/GoalService/recovery.ts@@ -249,7 +249,7 @@ export const resumeAbandonedTaskRecovery = async (? 'Goal cost budget was exhausted after an operation was abandoned': recovery.outcome === 'exhausted-rounds'? 'Task attempt budget was exhausted after an operation was abandoned'- : 'Automatic recovery could not restart an abandoned operation';+ : `Automatic recovery could not restart an abandoned operation${recovery.error ? `: ${recovery.error}` : ''}`;return ctx.gateOrTakeOver(graph, nodeId, task.id, reason, effects, {machine: recovery.outcome === 'spawn-failed',});diff --git a/apps/server/src/services/goal/taskRecoveryCoordinator.ts b/apps/server/src/services/goal/taskRecoveryCoordinator.tsindex 1d2fed70a39..137182046b1 100644--- a/apps/server/src/services/goal/taskRecoveryCoordinator.ts+++ b/apps/server/src/services/goal/taskRecoveryCoordinator.ts@@ -1,4 +1,5 @@import type { GoalItem, TaskItem } from '@lobechat/types';+import { TRPCError } from '@trpc/server';import debug from 'debug';import { AgentOperationModel } from '@/database/models/agentOperation';@@ -50,11 +51,37 @@ export type TaskRecoveryOutcome =export interface TaskRecoveryResult {/** Present only on `spawn-failed` when the retry could not reach its device. */deviceUnavailable?: boolean;+ /**+ * Present only on `spawn-failed`: why the run did not start, when the cause is+ * one the person answering the gate can act on (see {@link describeSpawnFailure}).+ */+ error?: string;/** Present only on `started`. The drill-down link into `agent_operations`. */operationId?: string;outcome: TaskRecoveryOutcome;}+/** Longest spawn failure carried into a gate reason. */+const MAX_SPAWN_FAILURE_LENGTH = 300;++/**+ * The part of a spawn failure that may reach the person answering the gate.+ *+ * The gate used to say only that recovery "could not start the next attempt",+ * so its owner asked what had gone wrong and pressed Retry blind. `runTask`+ * refuses with a TRPC error written for its caller — a running topic it names,+ * a missing agent — and that sentence is what they need. Any other error may+ * carry SQL, identifiers or provider diagnostics; it stays in the server log.+ */+export const describeSpawnFailure = (error: unknown): string | undefined => {+ if (!(error instanceof TRPCError) || error.code === 'INTERNAL_SERVER_ERROR') return;+ const message = error.message.trim().replace(/\.$/, '');+ if (!message) return;+ return message.length > MAX_SPAWN_FAILURE_LENGTH+ ? `${message.slice(0, MAX_SPAWN_FAILURE_LENGTH - 1)}…`+ : message;+};+/** Retry budget and spawn boundary for a Goal Graph Task. */export class TaskRecoveryCoordinator {constructor(@@ -170,7 +197,11 @@ export class TaskRecoveryCoordinator {).catch((releaseError) => {log('task %s failed to release the recovery claim: %O', task.identifier, releaseError);});- return { deviceUnavailable, outcome: 'spawn-failed' };+ return {+ deviceUnavailable,+ error: deviceUnavailable ? undefined : describeSpawnFailure(error),+ outcome: 'spawn-failed',+ };}};}diff --git a/apps/server/src/services/goal/verificationStall.test.ts b/apps/server/src/services/goal/verificationStall.test.tsnew file mode 100644index 00000000000..b99516397ac--- /dev/null+++ b/apps/server/src/services/goal/verificationStall.test.ts@@ -0,0 +1,133 @@+import { describe, expect, it } from 'vitest';++import { failureSignature, isVerificationStalled } from './verificationStall';++const plan = [+ { id: 'c1', required: true, title: 'Input reaches the game' },+ { id: 'c2', required: true, title: 'Latency is measured' },+ { id: 'c3', required: false, title: 'Optional screenshot' },+];++let createdAt = Date.parse('2026-10-11T15:00:00Z');+const round = (+ status: string,+ metadata: Record<string, unknown> = { taskDrivenAt: 'settled' },+ id = `r${createdAt}`,+) => ({+ createdAt: new Date((createdAt += 60_000)),+ id,+ metadata,+ plan,+ status,+});+const passed = (checkItemId: string) => ({ checkItemId, status: 'passed', verdict: 'passed' });+const failed = (checkItemId: string) => ({ checkItemId, status: 'failed', verdict: 'failed' });++const rejectedByReview = (feedback: string) =>+ round('passed', {+ goalReview: { feedback, predictionIds: [], status: 'rejected' },+ taskDrivenAt: 'x',+ });++describe('failureSignature', () => {+ it('names the required checks a failed round left open', () => {+ expect(failureSignature(round('failed'), [passed('c1'), failed('c3')])).toBe('checks:c2');+ });++ it('reads a review rejection by its feedback', () => {+ expect(failureSignature(rejectedByReview(' C1: Submit current evidence. '), [])).toBe(+ 'review:C1: Submit current evidence.',+ );+ });++ it('has none for a delivery that passed or a verifier that could not run', () => {+ expect(failureSignature(round('passed'), [passed('c1'), passed('c2')])).toBeUndefined();+ expect(failureSignature(round('errored'), [])).toBeUndefined();+ });+});++describe('isVerificationStalled', () => {+ it('stops after two attempts fail on the same checks', () => {+ expect(+ isVerificationStalled([+ { results: [passed('c1'), failed('c2')], round: round('failed') },+ { results: [passed('c1'), failed('c2')], round: round('failed') },+ ]),+ ).toBe(true);+ });++ /** A Task loop seen in production: every attempt was sent back with the same canned feedback. */+ it('stops after two attempts the review sends back with the same feedback', () => {+ const feedback = 'Input reaches the game: Submit current evidence for this required check.';+ expect(+ isVerificationStalled([+ { results: [], round: rejectedByReview(feedback) },+ { results: [], round: rejectedByReview(feedback) },+ ]),+ ).toBe(true);+ });++ /**+ * A generated first plan keeps its own item ids next to `sourceCriterionId`;+ * the retry is re-planned from the acceptance union under the criterion id.+ * Comparing local ids let identical failures look different.+ */+ it('matches the first attempt to a retry re-planned under criterion ids', () => {+ const generated = {+ ...round('failed'),+ plan: plan.map((item) => ({ ...item, id: `gen-${item.id}`, sourceCriterionId: item.id })),+ };+ const retry = {+ ...round('failed'),+ plan: plan.map((item) => ({ ...item, sourceCriterionId: item.id })),+ };+ expect(+ isVerificationStalled([+ { results: [passed('gen-c1'), failed('gen-c2')], round: generated },+ { results: [passed('c1'), failed('c2')], round: retry },+ ]),+ ).toBe(true);+ });++ it('keeps retrying while each attempt fails on something else', () => {+ expect(+ isVerificationStalled([+ { results: [failed('c1'), passed('c2')], round: round('failed') },+ { results: [passed('c1'), failed('c2')], round: round('failed') },+ ]),+ ).toBe(false);+ });++ it('counts one round per attempt, not the repair rounds inside it', () => {+ expect(+ isVerificationStalled([+ { results: [failed('c2')], round: round('failed', {}) },+ { results: [failed('c2')], round: round('failed') },+ ]),+ ).toBe(false);+ });++ it('gives a Retry the person chose its own attempts', () => {+ const first = round('failed');+ const answeredAt = new Date((createdAt += 1000));+ const second = round('failed');+ expect(+ isVerificationStalled(+ [+ { results: [failed('c2')], round: first },+ { results: [failed('c2')], round: second },+ ],+ answeredAt,+ ),+ ).toBe(false);+ });++ it('does not read a verifier outage as a repeated failure', () => {+ expect(+ isVerificationStalled([+ { results: [], round: round('errored') },+ { results: [], round: round('errored') },+ ]),+ ).toBe(false);+ });+});diff --git a/apps/server/src/services/goal/verificationStall.ts b/apps/server/src/services/goal/verificationStall.tsnew file mode 100644index 00000000000..f5c9f18f8ef--- /dev/null+++ b/apps/server/src/services/goal/verificationStall.ts@@ -0,0 +1,102 @@+import type { VerifyCheckItem, VerifyRunMetadata } from '@lobechat/types';++import { AcceptanceModel } from '@/database/models/acceptance';+import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';+import { VerifyRunModel } from '@/database/models/verifyRun';+import type { VerifyCheckResultItem, VerifyRunItem } from '@/database/schemas/verify';+import type { LobeChatDatabase } from '@/database/type';++/** Consecutive attempts that may fail the same way before a person is asked. */+export const REPEATED_FAILURE_LIMIT = 2;++type StallRound = Pick<VerifyRunItem, 'createdAt' | 'id' | 'metadata' | 'plan' | 'status'>;+type StallResult = Pick<VerifyCheckResultItem, 'checkItemId' | 'status' | 'verdict'>;++/**+ * What a delivered attempt fell short on, or `undefined` when it did not fail on+ * its content (it passed, or the verifier could not run).+ *+ * - A failed round: the required checks it did not pass, by plan item id. Every+ * attempt of a Task re-instantiates the same plan item ids, so two attempts+ * that left the same checks open read the same.+ * - A round that passed verification but the Goal review sent back: the+ * review's feedback, verbatim. A deterministic rejection ("Submit current+ * evidence for this required check") repeats word for word; a model's own+ * comments rarely do, so those stay bounded by the attempt budget alone.+ */+export const failureSignature = (round: StallRound, results: StallResult[]): string | undefined => {+ const review = (round.metadata as VerifyRunMetadata | null)?.goalReview;+ if (round.status === 'passed') {+ return review?.status === 'rejected' ? `review:${review.feedback.trim()}` : undefined;+ }+ if (round.status !== 'failed') return;++ const resultByItem = new Map(results.map((result) => [result.checkItemId, result]));+ const open = ((round.plan ?? []) as VerifyCheckItem[])+ .filter((item) => item.required !== false)+ .filter((item) => {+ const result = resultByItem.get(item.id);+ return (result?.verdict ?? result?.status) !== 'passed';+ })+ // Named like the acceptance union names them: a generated first plan keeps+ // its own item ids, while every Goal retry is re-planned from the union+ // under the criterion id, so local ids differ between the first two attempts.+ .map((item) => (item.sourceFlowNode ? item.id : (item.sourceCriterionId ?? item.id)))+ .sort();+ return open.length > 0 ? `checks:${open.join(',')}` : undefined;+};++/**+ * Whether the Task's latest attempts all failed verification the same way.+ *+ * A failed verification used to start the next attempt straight away until the+ * attempt budget ran out, even when each attempt was sent back for the same+ * thing — the retries could not change the outcome, they only spent the budget+ * and left the person a gate that said nothing about why.+ *+ * Only the round that settled an attempt counts (it carries `taskDrivenAt`); the+ * repair rounds inside one attempt are that attempt's own business. A person's+ * answer to a gate starts the count again, so their Retry gets its own attempts.+ */+export const isVerificationStalled = (+ rounds: { results: StallResult[]; round: StallRound }[],+ since?: Date,+): boolean => {+ const settled = rounds.filter(+ ({ round }) =>+ !!(round.metadata as { taskDrivenAt?: string } | null)?.taskDrivenAt &&+ (!since || new Date(round.createdAt) > since),+ );+ const recent = settled.slice(-REPEATED_FAILURE_LIMIT);+ if (recent.length < REPEATED_FAILURE_LIMIT) return false;+ const signatures = recent.map(({ results, round }) => failureSignature(round, results));+ return signatures.every((signature) => !!signature && signature === signatures[0]);+};++/** Reads the Task's acceptance rounds and applies {@link isVerificationStalled}. */+export const readVerificationStall = async (+ db: LobeChatDatabase,+ owner: { userId: string; workspaceId?: string },+ taskId: string,+ since?: Date,+): Promise<boolean> => {+ const acceptance = await new AcceptanceModel(db, owner.userId, owner.workspaceId).findBySubject(+ 'task',+ taskId,+ );+ if (!acceptance) return false;+ const runs = await new VerifyRunModel(db, owner.userId, owner.workspaceId).listByAcceptance(+ acceptance.id,+ );+ if (runs.length < REPEATED_FAILURE_LIMIT) return false;+ const results = await new VerifyCheckResultModel(db, owner.userId, owner.workspaceId).listByRuns(+ runs.map((run) => run.id),+ );+ return isVerificationStalled(+ runs.map((round) => ({+ results: results.filter((result) => result.verifyRunId === round.id),+ round,+ })),+ since,+ );+};diff --git a/apps/server/src/services/verify/__tests__/goalReview.test.ts b/apps/server/src/services/verify/__tests__/goalReview.test.tsindex 68ee0074fb6..0eede79de31 100644--- a/apps/server/src/services/verify/__tests__/goalReview.test.ts+++ b/apps/server/src/services/verify/__tests__/goalReview.test.ts@@ -161,6 +161,7 @@ describe('Goal automatic Acceptance review', () => {});it('reviews supplementary checks across rounds, not only the bound run', async () => {+ mocks.run.mockResolvedValue({ id: 'r2', acceptanceId: 'a1', metadata: {} });mocks.rounds.mockResolvedValue({runs: [{ id: 'r1', roundIndex: 1, plan: [check] },@@ -186,6 +187,7 @@ describe('Goal automatic Acceptance review', () => {});it('ignores a result filed under an id that no round ever planned', async () => {+ mocks.run.mockResolvedValue({ id: 'r2', acceptanceId: 'a1', metadata: {} });mocks.rounds.mockResolvedValue({runs: [{ id: 'r1', roundIndex: 1, plan: [check] },@@ -332,6 +334,25 @@ describe('Goal automatic Acceptance review', () => {expect(mocks.predict).toHaveBeenCalledTimes(1);});+ /**+ * A concurrent attempt opened its round while this delivery was being judged.+ * Task rounds confirm their plan when they open, so the empty newer round+ * planned every check and flagged this round's evidence as carried forward —+ * a passing delivery was sent back for "current evidence" it had just filed.+ */+ it('ignores a round opened after the one under review', async () => {+ mocks.rounds.mockResolvedValue({+ runs: [+ { id: 'r1', plan: [check], planConfirmedAt: new Date(), roundIndex: 1, status: 'passed' },+ { id: 'r2', plan: [check], planConfirmedAt: new Date(), roundIndex: 2, status: 'running' },+ ],+ results: [result],+ });++ expect(await reviewGoalDelivery(db, 'u1', 't1', 'op1')).toMatchObject({ status: 'passed' });+ expect(mocks.predict).toHaveBeenCalledTimes(1);+ });+/*** The feedback is persisted on the run and quoted into the escalation, so an* unexpected backend failure must not carry SQL, identifiers or providerdiff --git a/apps/server/src/services/verify/goalReview.ts b/apps/server/src/services/verify/goalReview.tsindex 769098e25f3..9f2de18442c 100644--- a/apps/server/src/services/verify/goalReview.ts+++ b/apps/server/src/services/verify/goalReview.ts@@ -62,7 +62,18 @@ export const reviewGoalDelivery = async (// draft, or one a CLI-driven verification was appended past — and its// result-less items would otherwise each read as missing evidence and turn a// passing delivery into a rejection.- const confirmed = runs.filter((round) => !isDraftVerifyRun(round));+ //+ // A round opened after the one under review belongs to a later attempt that+ // has not delivered yet. Task rounds confirm their plan as they open, so it+ // would plan every check with no results and mark this delivery's evidence as+ // carried forward — a passing delivery rejected for "current evidence" it had+ // just submitted. Judge the chain up to the round that settled.+ const reviewedRoundIndex = runs.find((round) => round.id === run.id)?.roundIndex;+ const confirmed = runs.filter(+ (round) =>+ !isDraftVerifyRun(round) &&+ (reviewedRoundIndex == null || (round.roundIndex ?? 0) <= reviewedRoundIndex),+ );// A result filed under an id its round never planned surfaces as a row of its// own, required by default. No later round plans it, so the builder is never// asked to re-answer it and it is never flagged as carried forward — itsdiff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex d5015f8270b..39b32c202c0 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -894,6 +894,7 @@"goalProcess.gate.reason.quotaFarReset": "The usage limit ({{error}}) does not reset until {{at}}, more than a day away. Switch the agent to another account or provider, or retry after the reset.","goalProcess.gate.reason.quotaRetriesSpent": "Still over the usage limit ({{error}}) after {{count}} automatic retries over {{duration}}. Check the plan, or switch the agent to another account or provider.","goalProcess.gate.reason.recoveryFailed": "Automatic recovery could not start the next attempt",+ "goalProcess.gate.reason.recoveryFailedWithError": "Automatic recovery could not start the next attempt: {{error}}","goalProcess.gate.reason.runError": "The run stopped with an error ({{code}})","goalProcess.gate.reason.setupCli": "The run could not start ({{error}}). Install the CLI on the device the agent runs on and make sure it is on PATH.","goalProcess.gate.reason.setupCredentials": "The provider refused the run ({{error}}). Update the credentials, plan or model in the agent settings.",@@ -903,6 +904,7 @@"goalProcess.gate.reason.transientRetriesSpent": "The run failed the same way {{count}} times over {{duration}} ({{error}}). Check the device, its network and the agent gateway.","goalProcess.gate.reason.verifyFailed": "Task {{id}} did not pass verification","goalProcess.gate.reason.verifyInternalError": "Verification could not run (internal error); this delivery was not evaluated",+ "goalProcess.gate.reason.verifyStalled": "Task {{id}} failed verification the same way {{count}} times in a row, so it was not retried again","goalProcess.gate.recommended": "recommended","goalProcess.gate.releaseReports": "reports the experiment results and needs your decision","goalProcess.gate.title.agentQuestion": "Answer the main Agent's question",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 3a681d822bc..cc562e28c63 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -894,6 +894,7 @@"goalProcess.gate.reason.quotaFarReset": "用量额度({{error}})要到 {{at}} 才恢复,超过一天。可以把 Agent 换到别的账号或服务商,或等额度恢复后再重试。","goalProcess.gate.reason.quotaRetriesSpent": "自动重试 {{count}} 次、历时 {{duration}},仍然超出用量额度({{error}})。请检查套餐,或把 Agent 换到别的账号或服务商。","goalProcess.gate.reason.recoveryFailed": "自动恢复未能启动下一次尝试",+ "goalProcess.gate.reason.recoveryFailedWithError": "自动恢复未能启动下一次尝试:{{error}}","goalProcess.gate.reason.runError": "任务运行出错({{code}})","goalProcess.gate.reason.setupCli": "运行没能启动({{error}})。请在 Agent 所在的设备上安装对应 CLI,并确认它在 PATH 里。","goalProcess.gate.reason.setupCredentials": "服务商拒绝了这次运行({{error}})。请在 Agent 设置里更新凭证、套餐或模型。",@@ -903,6 +904,7 @@"goalProcess.gate.reason.transientRetriesSpent": "运行在 {{duration}} 内以同样的方式失败了 {{count}} 次({{error}})。请检查设备、网络和 Agent 网关。","goalProcess.gate.reason.verifyFailed": "任务 {{id}} 未通过验证","goalProcess.gate.reason.verifyInternalError": "验证未能运行(内部错误),这次交付没有被评估",+ "goalProcess.gate.reason.verifyStalled": "任务 {{id}} 连续 {{count}} 次因相同原因未通过验证,已停止自动重试","goalProcess.gate.recommended": "推荐","goalProcess.gate.releaseReports": "向你汇报实验结果,等你决定","goalProcess.gate.title.agentQuestion": "回答主 Agent 的问题",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 4295551d954..c76eaa0d0ad 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -2542,10 +2542,14 @@ export default {'goalProcess.gate.reason.verifyInternalError':'Verification could not run (internal error); this delivery was not evaluated','goalProcess.gate.reason.verifyFailed': 'Task {{id}} did not pass verification',+ 'goalProcess.gate.reason.verifyStalled':+ 'Task {{id}} failed verification the same way {{count}} times in a row, so it was not retried again','goalProcess.gate.reason.goalAcceptanceFailed': 'Goal-level acceptance did not pass','goalProcess.gate.reason.attemptBudgetExhausted': 'The attempt budget for this work is used up','goalProcess.gate.reason.costBudgetExhausted': 'The goal cost budget is used up','goalProcess.gate.reason.recoveryFailed': 'Automatic recovery could not start the next attempt',+ 'goalProcess.gate.reason.recoveryFailedWithError':+ 'Automatic recovery could not start the next attempt: {{error}}','goalProcess.gate.reason.batchReleaseProbes':'The v{{revision}} experiments finished; start batch execution with wave {{wave}} ({{count}} units)','goalProcess.gate.reason.batchReleaseRevised':diff --git a/packages/utils/src/goalCopy.ts b/packages/utils/src/goalCopy.tsindex 5e261cc50d3..b1984afaf2a 100644--- a/packages/utils/src/goalCopy.ts+++ b/packages/utils/src/goalCopy.ts@@ -93,6 +93,11 @@ const REASON_PATTERNS: Array<{param: 'id',pattern: /^Task (\S+) did not pass verification$/,},+ {+ key: 'goalProcess.gate.reason.verifyStalled',+ params: ['id', 'count'],+ pattern: /^Task (\S+) failed verification the same way (\d+) times in a row$/,+ },{key: 'goalProcess.gate.reason.goalAcceptanceFailed',pattern: /^Goal-level acceptance did not pass$/,@@ -109,6 +114,13 @@ const REASON_PATTERNS: Array<{key: 'goalProcess.gate.reason.deviceStayedOffline',pattern: /^Task device stayed offline$/,},+ {+ // The spawn failure `runTask` refused with, when it is one a person can act on.+ key: 'goalProcess.gate.reason.recoveryFailedWithError',+ param: 'error',+ pattern:+ /^Automatic recovery could not (?:start the next attempt|restart an abandoned operation): (.+)$/,+ },{key: 'goalProcess.gate.reason.recoveryFailed',pattern:diff --git a/src/features/AgentGoals/ProcessControl/coordinatorCopy.test.ts b/src/features/AgentGoals/ProcessControl/coordinatorCopy.test.tsindex b88e3a2eb4b..f5492cb7980 100644--- a/src/features/AgentGoals/ProcessControl/coordinatorCopy.test.ts+++ b/src/features/AgentGoals/ProcessControl/coordinatorCopy.test.ts@@ -119,6 +119,22 @@ describe('coordinatorReasonCopy', () => {expect(coordinatorReasonCopy('Automatic recovery could not start the next attempt')).toEqual({key: 'goalProcess.gate.reason.recoveryFailed',});+ expect(+ coordinatorReasonCopy(+ 'Automatic recovery could not start the next attempt: Task already has a running topic (tpc_1). Cancel it first or use --continue',+ ),+ ).toEqual({+ key: 'goalProcess.gate.reason.recoveryFailedWithError',+ params: {+ error: 'Task already has a running topic (tpc_1). Cancel it first or use --continue',+ },+ });+ expect(+ coordinatorReasonCopy('Task T-12 failed verification the same way 2 times in a row'),+ ).toEqual({+ key: 'goalProcess.gate.reason.verifyStalled',+ params: { count: '2', id: 'T-12' },+ });});it('wraps a bare runtime error type in a localized sentence', () => {