π€― 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: harden Goal acceptance runtime (#18670)
Arvin Xue1bc7e1bd629
diff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.mdindex d9a6f0f797f..6d594a64565 100644--- a/.agents/acceptance/common-mistakes.md+++ b/.agents/acceptance/common-mistakes.md@@ -773,3 +773,18 @@ because it installs from scratch.expectations, delete the hidden `node_modules/.pnpm/lock.yaml` (or the wholenode\_modules) in the affected workspace root and reinstall, then re-verify theactual resolved version via the importing package's symlink.++### L-S16 β Treating a listening dev-server process as a healthy long-run probe++**Wrong approach:** use process existence, an open TCP connection, or an unbounded+`curl` as the health signal for an unattended LobeHub soak.++**Why it fails:** Next dev can remain alive and accept a TCP connection while never+returning an HTTP response. An unbounded probe then blocks the monitor itself, so the+log stops exactly when the failure begins and makes the run look shorter rather than+recording an unhealthy interval.++**Correct approach:** give every HTTP and CLI probe explicit connect and total+timeouts, record timeout/`000` as an observation, and keep the monitor advancing.+Prove recovery with a successful application request after restarting the owned+server; neither a PID nor a listening socket is sufficient.diff --git a/.agents/acceptance/scripts/agent-gateway/local-device-gateway-setup.sh b/.agents/acceptance/scripts/agent-gateway/local-device-gateway-setup.shnew file mode 100644index 00000000000..f9ab706d01f--- /dev/null+++ b/.agents/acceptance/scripts/agent-gateway/local-device-gateway-setup.sh@@ -0,0 +1,25 @@+#!/usr/bin/env bash+set -euo pipefail++REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)"+GATEWAY_DIR="$(cd "$REPO_ROOT/.." && pwd)/device-gateway"+APP_ENV="${JWKS_SOURCE:-$REPO_ROOT/.records/env/gateway.env}"++[ -d "$GATEWAY_DIR" ] || { echo "device-gateway repo not found: $GATEWAY_DIR"; exit 1; }+[ -f "$APP_ENV" ] || { echo "gateway env not found: $APP_ENV"; exit 1; }++set -a+# shellcheck disable=SC1090+source "$APP_ENV"+set +a++node -e '+const fs = require("fs");+const jwks = JSON.parse(process.env.JWKS_KEY || "{}");+const serviceToken = process.env.DEVICE_GATEWAY_SERVICE_TOKEN;+if (!serviceToken || !Array.isArray(jwks.keys)) process.exit(1);+const publicKeys = jwks.keys.map(({ d, p, q, dp, dq, qi, ...key }) => key);+fs.writeFileSync(process.argv[1], `SERVICE_TOKEN=${serviceToken}\nJWKS_PUBLIC_KEY=${JSON.stringify({ keys: publicKeys })}\n`);+' "$GATEWAY_DIR/.dev.vars"++echo "configured local device gateway: $GATEWAY_DIR/.dev.vars"diff --git a/.agents/acceptance/scripts/agent-gateway/local-gateway-setup.sh b/.agents/acceptance/scripts/agent-gateway/local-gateway-setup.shindex 4b823f0d037..babe3d496c6 100755--- a/.agents/acceptance/scripts/agent-gateway/local-gateway-setup.sh+++ b/.agents/acceptance/scripts/agent-gateway/local-gateway-setup.sh@@ -41,12 +41,21 @@ fi[ -n "$APP_ENV" ] && [ -f "$APP_ENV" ] || { echo "β no env file with JWKS_KEY found (set JWKS_SOURCE=<file>, or create .records/env/gateway.env)"; exit 1; }echo "βΉοΈ reading JWKS_KEY + AGENT_GATEWAY_SERVICE_TOKEN from: $APP_ENV"+# Managed agent-testing env files are shell-escaped `export KEY=value` files.+# Source them instead of reparsing them as dotenv so JWKS JSON survives intact.+set -a+# shellcheck disable=SC1090+source "$APP_ENV"+set +a+# The app env also defines PORT for Next.js; keep the gateway on its own port.+PORT="${GATEWAY_PORT:-8787}"+node -e 'const fs = require("fs");const env = fs.readFileSync(process.argv[1], "utf8");const pick = (k) => { const m = env.match(new RegExp("^"+k+"=(.*)$","m")); return m ? m[1].trim().replace(/^['"'"'"]|['"'"'"]$/g,"") : ""; };-const jwksRaw = pick("JWKS_KEY");-const svc = pick("AGENT_GATEWAY_SERVICE_TOKEN");+const jwksRaw = process.env.JWKS_KEY || "";+const svc = process.env.AGENT_GATEWAY_SERVICE_TOKEN || "";if (!jwksRaw) { console.error("β JWKS_KEY missing in .env.local"); process.exit(1); }if (!svc) { console.error("β AGENT_GATEWAY_SERVICE_TOKEN missing in .env.local"); process.exit(1); }const jwks = JSON.parse(jwksRaw);diff --git a/.agents/acceptance/scripts/init-dev-env.sh b/.agents/acceptance/scripts/init-dev-env.shindex 3b8055222b0..1a4640552c1 100755--- a/.agents/acceptance/scripts/init-dev-env.sh+++ b/.agents/acceptance/scripts/init-dev-env.sh@@ -168,12 +168,14 @@ guard_no_root_env() {}apply_env() {+ export AGENT_GATEWAY_SERVICE_TOKEN="${AGENT_GATEWAY_SERVICE_TOKEN:-agent-testing-local-gateway-service-token}"export AGENT_RUNTIME_MODE="${AGENT_RUNTIME_MODE:-queue}"export APP_URL="${APP_URL:-http://localhost:${SERVER_PORT}}"export AUTH_EMAIL_VERIFICATION="${AUTH_EMAIL_VERIFICATION:-0}"export AUTH_SECRET="${AUTH_SECRET:-agent-testing-local-auth-secret-32chars}"export DATABASE_DRIVER="${DATABASE_DRIVER:-node}"export DATABASE_URL+ export DEVICE_GATEWAY_SERVICE_TOKEN="${DEVICE_GATEWAY_SERVICE_TOKEN:-agent-testing-local-device-gateway-token}"export FEATURE_FLAGS="${FEATURE_FLAGS:--agent_self_iteration}"export KEY_VAULTS_SECRET="${KEY_VAULTS_SECRET:-r2gbBPKyJ8ZRKCLKt+I3DImfcL+wGxaQyRC56xtm9Uk=}"export NEXT_PUBLIC_AUTH_EMAIL_VERIFICATION="${NEXT_PUBLIC_AUTH_EMAIL_VERIFICATION:-0}"@@ -212,12 +214,14 @@ apply_env() {env_keys() {printf '%s\n' \+ AGENT_GATEWAY_SERVICE_TOKEN \APP_URL \AGENT_RUNTIME_MODE \AUTH_EMAIL_VERIFICATION \AUTH_SECRET \DATABASE_DRIVER \DATABASE_URL \+ DEVICE_GATEWAY_SERVICE_TOKEN \FEATURE_FLAGS \KEY_VAULTS_SECRET \NEXT_PUBLIC_AUTH_EMAIL_VERIFICATION \diff --git a/apps/server/src/services/goal/criteriaGenerator.test.ts b/apps/server/src/services/goal/criteriaGenerator.test.tsindex 3ad34d49270..a5845ddf72b 100644--- a/apps/server/src/services/goal/criteriaGenerator.test.ts+++ b/apps/server/src/services/goal/criteriaGenerator.test.ts@@ -38,7 +38,7 @@ describe('GoalCriteriaGeneratorService', () => {}),expect.objectContaining({tracing: {- promptVersion: 'v2',+ promptVersion: 'v3',scenario: 'goal_criteria_gen',schemaName: 'goal_criteria_draft',},diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.tsindex 5151bdab33b..510201f40f7 100644--- a/apps/server/src/services/goal/index.test.ts+++ b/apps/server/src/services/goal/index.test.ts@@ -20,6 +20,7 @@ import {users,} from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';+import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime/AgentRuntimeCoordinator';import { TaskRunnerService } from '../taskRunner';import { GoalService } from './index';@@ -84,6 +85,9 @@ describe('GoalService', () => {expect(task?.instruction).toContain('Do not invoke Acceptance skills or Acceptance CLI commands',);+ expect(task?.instruction).toContain(+ 'Include the relevant artifact contents or exact excerpts and the raw outputs of decisive verification commands',+ );});it('gates every responsible task with a work-scoped Acceptance requirement', async () => {@@ -151,6 +155,9 @@ describe('GoalService', () => {message: 'Created Goal-level acceptance Work for the remaining contract',outcome: 'advanced',});+ const acceptanceWork = (await service.graph(graph.goal.id)).nodes.find(+ (node) => node.id === goalAcceptanceCreated.nodeId,+ );const acceptanceTaskCreated = await service.tick(graph.goal.id);expect(acceptanceTaskCreated).toMatchObject({ outcome: 'advanced' });@@ -167,6 +174,8 @@ describe('GoalService', () => {'An accurate gap analysis, a report that the Goal is not accepted',);expect(acceptance?.requirement).toContain('the verdict MUST be failed');+ expect(acceptanceWork?.description).toContain('Do not repeat expensive or destructive work');+ expect(acceptanceWork?.description).toContain('Run only the missing or stale checks');await taskModel.updateStatus(acceptanceTaskCreated.taskId!, 'completed');expect((await service.tick(graph.goal.id)).outcome).toBe('advanced');@@ -333,7 +342,7 @@ describe('GoalService', () => {const recovered = await service.tick(graph.goal.id);- expect(settleSpy).toHaveBeenCalledWith('op-stale', expect.any(Date));+ expect(settleSpy).toHaveBeenCalledWith('op-stale', expect.any(Date), undefined);expect(timeoutSpy).toHaveBeenCalledWith(created.taskId, 'topic-stale', 'timeout');expect(runSpy).toHaveBeenCalledWith({maxSteps: undefined,@@ -347,6 +356,52 @@ describe('GoalService', () => {});});+ it('charges stale Work usage before checking the replacement budget', async () => {+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ vi.spyOn(TaskTopicModel.prototype, 'findRunningByTaskIds').mockResolvedValue([+ { operationId: 'op-stale-cost', topicId: 'topic-stale-cost' } as never,+ ]);+ vi.spyOn(TaskTopicModel.prototype, 'updateStatus').mockResolvedValue(undefined);+ vi.spyOn(AgentRuntimeCoordinator.prototype, 'getOperationMetadata').mockResolvedValue({+ createdAt: new Date().toISOString(),+ lastActiveAt: new Date().toISOString(),+ status: 'running',+ totalCost: 0.75,+ totalSteps: 2,+ });++ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { maxAttemptsPerWork: 3, operationLeaseTimeoutMs: 60_000 } },+ maxTotalCost: 0.5,+ title: 'Respect abandoned Work cost',+ work: ['Run an expensive experiment'],+ });+ 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-stale-cost',+ taskId: created.taskId,+ });+ await serverDB+ .update(agentOperations)+ .set({ updatedAt: new Date('2026-01-01T00:00:00.000Z') })+ .where(eq(agentOperations.id, 'op-stale-cost'));++ const recovered = await service.tick(graph.goal.id);++ expect(runSpy).not.toHaveBeenCalled();+ expect(recovered).toMatchObject({ outcome: 'waiting_human', taskId: created.taskId });+ expect(await new AgentOperationModel(serverDB, userId).findById('op-stale-cost')).toMatchObject(+ {+ status: 'abandoned',+ totalCost: 0.75,+ },+ );+ });+it('does not reclaim a running Work operation without a persisted topic id', async () => {vi.spyOn(TaskTopicModel.prototype, 'findRunningByTaskIds').mockResolvedValue([{ operationId: 'op-without-topic', topicId: null } as never,diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.tsindex c2a33e75859..737d46635fb 100644--- a/apps/server/src/services/goal/index.ts+++ b/apps/server/src/services/goal/index.ts@@ -19,6 +19,7 @@ import { TaskTopicModel } from '@/database/models/taskTopic';import { WorkModel } from '@/database/models/work';import type { LobeChatDatabase } from '@/database/type';import { assertAgentUsableBy } from '@/database/utils/agent-access';+import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime/AgentRuntimeCoordinator';import { TaskService } from '../task';import { TaskRunnerService } from '../taskRunner';@@ -253,7 +254,8 @@ export class GoalService {const result = await this.graphModel.createNodeOnce(goalId, {description: [`Complete and prove the overall Goal acceptance requirement: ${graph.goal.requirement}`,- 'Use the existing Goal findings as prior evidence. Explicitly close every remaining acceptance gap instead of treating completed upstream Work as proof that the whole Goal is achieved.',+ 'Inspect and reuse existing Goal findings, artifacts, metrics, and command results as the primary evidence. Do not repeat expensive or destructive work when the existing evidence is sufficient and still auditable.',+ 'Explicitly close every remaining acceptance gap instead of treating completed upstream Work as proof that the whole Goal is achieved. Run only the missing or stale checks needed to close those gaps.','Return one auditable final delivery with evidence for every requirement. If a requirement cannot be satisfied, state the exact gap and the minimum next action; do not claim the Goal is complete.',].join('\n\n'),kind: 'work',@@ -545,12 +547,13 @@ export class GoalService {if (!operationId || !topicId) return undefined;const staleBefore = new Date(Date.now() - resolveOperationLeaseTimeout(graph.goal));+ const latestUsage = await new AgentRuntimeCoordinator().getOperationMetadata(operationId);const reclaimed = await this.db.transaction(async (tx) => {const settled = await new AgentOperationModel(tx,this.userId,this.workspaceId,- ).settleStaleRunning(operationId, staleBefore);+ ).settleStaleRunning(operationId, staleBefore, latestUsage?.totalCost);if (!settled) return false;await new TaskTopicModel(tx, this.userId, this.workspaceId).updateStatus(@@ -619,6 +622,7 @@ export class GoalService {'Execute only the Current Work contract. Do not implement, validate, or pre-empt any sibling or downstream Work node, even when the overall goal context describes it.','The complete requirements for this Work are included here. Do not inspect unrelated agent documents to recover requirements. Do not invoke Acceptance skills or Acceptance CLI commands during the main Work; a dedicated post-run phase will ask you to submit your evidence before an independent verifier judges it.','Create implementation-level subtasks when useful. Finish the operation once the Current Work deliverable and its concrete evidence are ready; Acceptance verification will decide whether this Task is complete.',+ 'Make the final delivery self-contained for an independent verifier that may not have workspace access. Include the relevant artifact contents or exact excerpts and the raw outputs of decisive verification commands; file paths and claims that checks passed are not sufficient evidence by themselves.','Return the produced artifacts, evidence, key findings, and the recommended next action. Do not mark the overall Goal complete.',].filter(Boolean)diff --git a/apps/server/src/services/verify/__tests__/evidenceSubmission.test.ts b/apps/server/src/services/verify/__tests__/evidenceSubmission.test.tsindex 62542f6a3f9..c3282e8c0d6 100644--- a/apps/server/src/services/verify/__tests__/evidenceSubmission.test.ts+++ b/apps/server/src/services/verify/__tests__/evidenceSubmission.test.ts@@ -1,17 +1,68 @@// @vitest-environment nodeimport { beforeEach, describe, expect, it, vi } from 'vitest';-import { startEvidenceSubmission } from '../evidenceSubmission';+import {+ recordHeterogeneousDeliverableEvidence,+ startEvidenceSubmission,+} from '../evidenceSubmission';-const { execAgent } = vi.hoisted(() => ({ execAgent: vi.fn() }));+const { createMany, execAgent, findByOperation, upsertByCheckItem } = vi.hoisted(() => ({+ createMany: vi.fn(),+ execAgent: vi.fn(),+ findByOperation: vi.fn(),+ upsertByCheckItem: vi.fn(),+}));vi.mock('@/server/services/aiAgent', () => ({AiAgentService: vi.fn(() => ({ execAgent })),}));+vi.mock('@/database/models/verifyCheckResult', () => ({+ VerifyCheckResultModel: vi.fn(() => ({ upsertByCheckItem })),+}));+vi.mock('@/database/models/verifyEvidence', () => ({+ VerifyEvidenceModel: vi.fn(() => ({ createMany })),+}));+vi.mock('@/database/models/verifyRun', () => ({+ VerifyRunModel: vi.fn(() => ({ findByOperation })),+}));describe('startEvidenceSubmission', () => {beforeEach(() => {execAgent.mockReset().mockResolvedValue({ operationId: 'evidence-op' });+ findByOperation.mockReset().mockResolvedValue({ id: 'run-1' });+ upsertByCheckItem.mockReset().mockResolvedValue({ id: 'result-1' });+ createMany.mockReset().mockResolvedValue(undefined);+ });++ it('records the heterogeneous builder deliverable as inline evidence for every criterion', async () => {+ await recordHeterogeneousDeliverableEvidence({+ db: {} as any,+ deliverable: 'artifact path and sha-256',+ operation: { id: 'work-op' } as any,+ plan: [+ {+ id: 'criterion-1',+ index: 0,+ onFail: 'manual',+ required: true,+ title: 'Artifact exists',+ verifierConfig: {},+ verifierType: 'llm',+ },+ ],+ userId: 'user-1',+ });++ expect(upsertByCheckItem).toHaveBeenCalledWith(+ expect.objectContaining({ operationId: 'work-op', verifyRunId: 'run-1' }),+ );+ expect(createMany).toHaveBeenCalledWith([+ expect.objectContaining({+ capturedBy: 'agent',+ content: 'artifact path and sha-256',+ type: 'text',+ }),+ ]);});it('continues as the original builder in the same topic with only the evidence tool', async () => {@@ -52,6 +103,8 @@ describe('startEvidenceSubmission', () => {);const call = execAgent.mock.calls[0][0];expect(call.ephemeralUserMessage).toContain('criterion-1: Model artifact exists');+ expect(call.prompt).toBe(call.ephemeralUserMessage);+ expect(call.prompt.trim()).not.toBe('');expect(call.userInterventionConfig).toEqual({ approvalMode: 'headless' });expect(call.hooks[0].webhook.body).toMatchObject({deliverable: 'artifact summary',diff --git a/apps/server/src/services/verify/__tests__/lifecycleClaim.test.ts b/apps/server/src/services/verify/__tests__/lifecycleClaim.test.tsindex 769e9a0bc47..142fe8856ff 100644--- a/apps/server/src/services/verify/__tests__/lifecycleClaim.test.ts+++ b/apps/server/src/services/verify/__tests__/lifecycleClaim.test.ts@@ -11,6 +11,7 @@ const {findByOperation,operationFindById,finalizeVerifyRun,+ recordHeterogeneousDeliverableEvidence,startEvidenceSubmission,updateStatus,} = vi.hoisted(() => ({@@ -20,6 +21,7 @@ const {finalizeVerifyRun: vi.fn(),findByOperation: vi.fn(),operationFindById: vi.fn(),+ recordHeterogeneousDeliverableEvidence: vi.fn(),startEvidenceSubmission: vi.fn(),updateStatus: vi.fn(),}));@@ -50,7 +52,10 @@ vi.mock('../modelConfig', () => ({resolveVerifyModelConfig: vi.fn().mockResolvedValue({ model: 'm', provider: 'p' }),}));vi.mock('../settle', () => ({ finalizeVerifyRun }));-vi.mock('../evidenceSubmission', () => ({ startEvidenceSubmission }));+vi.mock('../evidenceSubmission', () => ({+ recordHeterogeneousDeliverableEvidence,+ startEvidenceSubmission,+}));vi.mock('../taskAcceptance', () => ({resolveTaskAcceptance: vi.fn().mockResolvedValue({ config: { enabled: true } }),}));@@ -74,6 +79,7 @@ describe('runVerifyOnCompletion β verification claim', () => {finalizeVerifyRun,findByOperation,operationFindById,+ recordHeterogeneousDeliverableEvidence,startEvidenceSubmission,updateStatus,].forEach((m) => m.mockReset());@@ -102,6 +108,30 @@ describe('runVerifyOnCompletion β verification claim', () => {expect(execute).not.toHaveBeenCalled();});+ it('records a heterogeneous builder handoff directly and continues to verification', async () => {+ operationFindById.mockResolvedValue({+ agentId: 'builder',+ id: 'op-1',+ model: null,+ provider: 'kimi-code',+ taskId: 'task-1',+ topicId: 'topic-1',+ });+ claimEvidenceCollection.mockResolvedValue(true);++ await runVerifyOnCompletion(db, 'u1', params);++ expect(recordHeterogeneousDeliverableEvidence).toHaveBeenCalledWith(+ expect.objectContaining({+ deliverable: 'done',+ operation: expect.objectContaining({ id: 'op-1' }),+ }),+ );+ expect(startEvidenceSubmission).not.toHaveBeenCalled();+ expect(claimVerifying).toHaveBeenCalledTimes(1);+ expect(execute).toHaveBeenCalledTimes(1);+ });+it('does not let a redelivered task completion bypass active evidence collection', async () => {findByOperation.mockResolvedValue({ ...confirmedRun, status: 'collecting_evidence' });operationFindById.mockResolvedValue({ id: 'op-1', taskId: 'task-1' });diff --git a/apps/server/src/services/verify/evidenceSubmission.ts b/apps/server/src/services/verify/evidenceSubmission.tsindex 05ff8c539a8..6a8cf6c9b5d 100644--- a/apps/server/src/services/verify/evidenceSubmission.ts+++ b/apps/server/src/services/verify/evidenceSubmission.ts@@ -1,6 +1,9 @@import { AcceptanceEvidenceIdentifier } from '@lobechat/builtin-tool-acceptance-evidence';import type { VerifyCheckItem } from '@lobechat/types';+import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';+import { VerifyEvidenceModel } from '@/database/models/verifyEvidence';+import { VerifyRunModel } from '@/database/models/verifyRun';import type { AgentOperationItem } from '@/database/schemas/agentOperations';import type { LobeChatDatabase } from '@/database/type';import type { AgentHook } from '@/server/services/agentRuntime/hooks/types';@@ -14,6 +17,48 @@ ${items.map((item) => `- ${item.id}: ${item.title}${item.description ? ` β ${iCall submitEvidence once for each criterion. This is evidence collection only: do not assign verdicts and do not redo the implementation.`;+/**+ * External CLI agents cannot call server builtin tools. Preserve their final+ * handoff as inline evidence instead of starting an evidence-only hetero turn+ * that can never reach `submitEvidence`.+ */+export const recordHeterogeneousDeliverableEvidence = async (params: {+ db: LobeChatDatabase;+ deliverable: string;+ operation: AgentOperationItem;+ plan: VerifyCheckItem[];+ userId: string;+ workspaceId?: string;+}) => {+ const { db, deliverable, operation, plan, userId, workspaceId } = params;+ const run = await new VerifyRunModel(db, userId, workspaceId).findByOperation(operation.id);+ if (!run) throw new Error('Verification run is missing for heterogeneous evidence');++ for (const item of plan) {+ const result = await new VerifyCheckResultModel(db, userId, workspaceId).upsertByCheckItem({+ checkItemId: item.id,+ checkItemIndex: item.index,+ checkItemTitle: item.title,+ operationId: operation.id,+ required: item.required,+ verifierType: item.verifierType,+ verifyRunId: run.id,+ });+ await new VerifyEvidenceModel(db, userId, workspaceId).createMany([+ {+ capturedAt: new Date(),+ capturedBy: 'agent',+ checkResultId: result.id,+ content: deliverable,+ description: 'Final deliverable reported by the heterogeneous builder.',+ documentId: null,+ fileId: null,+ type: 'text',+ },+ ]);+ }+};+export const startEvidenceSubmission = async (params: {db: LobeChatDatabase;deliverable: string;@@ -29,6 +74,7 @@ export const startEvidenceSubmission = async (params: {}const parentOperationId = operation.id;+ const evidencePrompt = buildEvidencePrompt(plan);const hooks: AgentHook[] = [{handler: async () => {@@ -65,11 +111,15 @@ export const startEvidenceSubmission = async (params: {agentId: operation.agentId,appContext: { taskId: operation.taskId, topicId: operation.topicId },autoStart: true,- ephemeralUserMessage: buildEvidencePrompt(plan),+ ephemeralUserMessage: evidencePrompt,exclusivePluginIds: [AcceptanceEvidenceIdentifier],hooks,parentOperationId,- prompt: '',+ // Heterogeneous CLI adapters execute `prompt` directly, while the native+ // runtime also renders the ephemeral user message in the existing topic.+ // Keep both populated so this evidence-only continuation has an+ // instruction on every execution target.+ prompt: evidencePrompt,suppressUserMessage: true,userInterventionConfig: { approvalMode: 'headless' },});diff --git a/apps/server/src/services/verify/lifecycle.ts b/apps/server/src/services/verify/lifecycle.tsindex b54528e02c4..b250fac40f6 100644--- a/apps/server/src/services/verify/lifecycle.ts+++ b/apps/server/src/services/verify/lifecycle.ts@@ -1,3 +1,4 @@+import { isHeterogeneousAgentModelId } from '@lobechat/const';import debug from 'debug';import { AgentOperationModel } from '@/database/models/agentOperation';@@ -7,7 +8,10 @@ import { VerifyRunModel } from '@/database/models/verifyRun';import type { LobeChatDatabase } from '@/database/type';import { createVerifierAgentRunner } from './agentVerifier';-import { startEvidenceSubmission } from './evidenceSubmission';+import {+ recordHeterogeneousDeliverableEvidence,+ startEvidenceSubmission,+} from './evidenceSubmission';import { VerifyExecutorService } from './executor';import { resolveVerifyModelConfig } from './modelConfig';import { finalizeVerifyRun } from './settle';@@ -105,21 +109,33 @@ const executeVerifyLifecycle = async ().claimEvidenceCollection(run.id);if (evidenceClaimed) {try {- await startEvidenceSubmission({- db,- deliverable: params.deliverable,- goal: params.goal,- operation: op,- plan: run.plan,- userId,- workspaceId,- });+ if (isHeterogeneousAgentModelId(op.model) || isHeterogeneousAgentModelId(op.provider)) {+ await recordHeterogeneousDeliverableEvidence({+ db,+ deliverable: params.deliverable,+ operation: op,+ plan: run.plan,+ userId,+ workspaceId,+ });+ evidenceSubmitted = true;+ } else {+ await startEvidenceSubmission({+ db,+ deliverable: params.deliverable,+ goal: params.goal,+ operation: op,+ plan: run.plan,+ userId,+ workspaceId,+ });+ }} catch (error) {await new VerifyRunModel(db, userId, workspaceId).updateStatus(run.id, 'planned');throw error;}}- return;+ if (!evidenceSubmitted) return;}// Claim only after a task-bound builder has submitted evidence. Standalonediff --git a/package.json b/package.jsonindex 6de29341230..c5ed80ff942 100644--- a/package.json+++ b/package.json@@ -308,7 +308,7 @@"@lobehub/icons": "^5.15.0","@lobehub/market-sdk": "0.39.2","@lobehub/tts": "^5.1.2",- "@lobehub/ui": "^5.32.0",+ "@lobehub/ui": "^5.32.7","@modelcontextprotocol/sdk": "^1.30.0","@neondatabase/serverless": "^1.1.0","@next/third-parties": "^16.3.0",diff --git a/packages/database/src/models/__tests__/agentOperation.test.ts b/packages/database/src/models/__tests__/agentOperation.test.tsindex d6291020303..29663184776 100644--- a/packages/database/src/models/__tests__/agentOperation.test.ts+++ b/packages/database/src/models/__tests__/agentOperation.test.ts@@ -242,6 +242,24 @@ describe('AgentOperationModel', () => {});});+ it('persists the latest cost while reclaiming an expired lease', async () => {+ const model = new AgentOperationModel(serverDB, userId);+ const operationId = 'op-lease-cost';+ await model.recordStart({ operationId });+ await serverDB+ .update(agentOperations)+ .set({ updatedAt: new Date('2026-01-01T00:00:00.000Z') })+ .where(eq(agentOperations.id, operationId));++ expect(await model.settleStaleRunning(operationId, new Date(Date.now() - 60_000), 0.75)).toBe(+ true,+ );+ expect(await model.findById(operationId)).toMatchObject({+ status: 'abandoned',+ totalCost: 0.75,+ });+ });+it('does not let a late completion overwrite a reclaimed operation', async () => {const model = new AgentOperationModel(serverDB, userId);const operationId = 'op-reclaimed-completion-race';diff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.tsindex 1f1658699c4..a33c2b05cb2 100644--- a/packages/database/src/models/agentOperation.ts+++ b/packages/database/src/models/agentOperation.ts@@ -252,13 +252,26 @@ export class AgentOperationModel {* Atomically retire an operation whose liveness lease has expired. A concurrent* heartbeat wins by moving updatedAt past staleBefore, preventing false recovery.*/- async settleStaleRunning(operationId: string, staleBefore: Date): Promise<boolean> {+ async settleStaleRunning(+ operationId: string,+ staleBefore: Date,+ latestTotalCost?: number,+ ): Promise<boolean> {+ const totalCost =+ latestTotalCost !== undefined && Number.isFinite(latestTotalCost)+ ? Math.max(0, latestTotalCost)+ : undefined;const [row] = await this.db.update(agentOperations).set({completedAt: new Date(),completionReason: 'lease_expired',status: 'abandoned',+ ...(totalCost === undefined+ ? {}+ : {+ totalCost: sql`greatest(coalesce(${agentOperations.totalCost}, 0), ${totalCost})`,+ }),}).where(and(diff --git a/packages/prompts/src/chains/goal.test.ts b/packages/prompts/src/chains/goal.test.tsindex ca531c9e923..57830227546 100644--- a/packages/prompts/src/chains/goal.test.ts+++ b/packages/prompts/src/chains/goal.test.ts@@ -14,7 +14,7 @@ describe('chainGoalCriteriaDraft', () => {maxCriteria: 6,});- expect(GOAL_CRITERIA_DRAFT_PROMPT_VERSION).toBe('v2');+ expect(GOAL_CRITERIA_DRAFT_PROMPT_VERSION).toBe('v3');expect(GOAL_CRITERIA_DRAFT_JSON_SCHEMA.name).toBe('goal_criteria_draft');expect(chain.messages[0].content).toContain('persistent autonomous goal');expect(chain.messages[0].content).toContain('at most 6 criteria');@@ -24,6 +24,8 @@ describe('chainGoalCriteriaDraft', () => {expect(chain.messages[0].content).toContain('criteria[].instruction is the exact, detailed judging rubric',);+ expect(chain.messages[0].content).toContain('Preserve every explicit numeric threshold');+ expect(chain.messages[0].content).toContain('do not invent an arbitrary one');expect(GOAL_CRITERIA_DRAFT_JSON_SCHEMA.schema.required).toEqual(['title','instruction',diff --git a/packages/prompts/src/chains/goal.ts b/packages/prompts/src/chains/goal.tsindex 624b659968a..7ab51a262e8 100644--- a/packages/prompts/src/chains/goal.ts+++ b/packages/prompts/src/chains/goal.ts@@ -9,7 +9,7 @@ import {} from './verify';/** Bump when the create-goal criteria drafting prompt meaningfully changes. */-export const GOAL_CRITERIA_DRAFT_PROMPT_VERSION = 'v2';+export const GOAL_CRITERIA_DRAFT_PROMPT_VERSION = 'v3';export const GOAL_CRITERIA_DRAFT_JSON_SCHEMA = {name: 'goal_criteria_draft',@@ -87,6 +87,8 @@ export const chainGoalCriteriaDraft = ({`- Return at most ${maxCriteria} criteria. Prefer fewer independent criteria that together define success.`,'- Describe outcomes and delivered artifacts, not implementation steps or one particular execution plan.','- Criteria must remain valid across multiple attempts. Do not mention the current round, temporary progress, or how the agent should work.',+ '- Preserve every explicit numeric threshold, comparison operator, unit, time window, and stopping condition from the user exactly; never weaken or omit them.',+ '- When the user did not provide a numeric threshold, do not invent an arbitrary one. Define a measurable, domain-appropriate success condition from the stated outcome and make any assumption explicit for user review.','- Never use unit tests, test suites, coverage, type-checks, lint, or a clean build as user-facing acceptance criteria.','- List the evidence needed to judge each criterion. Use [] only when the final text answer alone is sufficient.','- Use verifierType="agent" when judging requires active investigation, opening files, or multiple evidence types; use "llm" only for inline text or a directly inspectable image; use "program" only for deterministic command checks.',diff --git a/patches/@upstash__qstash.patch b/patches/@upstash__qstash.patchindex b6a49d73ff5..17450e52da0 100644--- a/patches/@upstash__qstash.patch+++ b/patches/@upstash__qstash.patch@@ -1,7 +1,7 @@-diff --git a/chunk-T3Z5YUS4.mjs b/chunk-T3Z5YUS4.mjs---- a/chunk-T3Z5YUS4.mjs-+++ b/chunk-T3Z5YUS4.mjs-@@ -1488,6 +1488,20 @@ var HttpClient = class {+diff --git a/chunk-JYPXGFWX.mjs b/chunk-JYPXGFWX.mjs+--- a/chunk-JYPXGFWX.mjs++++ b/chunk-JYPXGFWX.mjs+@@ -1526,6 +1526,20 @@ var HttpClient = class {}if (response.status < 200 || response.status >= 300) {const body = await response.text();@@ -22,7 +22,7 @@ diff --git a/chunk-T3Z5YUS4.mjs b/chunk-T3Z5YUS4.mjsthrow new QstashError(body.length > 0 ? body : `Error: status=${response.status}`,response.status-@@ -2745,8 +2759,10 @@ var AutoExecutor = class _AutoExecutor {+@@ -2797,8 +2811,10 @@ var AutoExecutor = class _AutoExecutor {if (error instanceof QStashWorkflowAbort) {throw error;}