π€― 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(verify): release acceptance rounds of task runs that never delivered (#22288)
Arvin Xuc718d50e5c14
diff --git a/apps/server/src/router-hono/workflows/verify/handlers/sweep.ts b/apps/server/src/router-hono/workflows/verify/handlers/sweep.tsindex e18ddc2932a..294f7339a19 100644--- a/apps/server/src/router-hono/workflows/verify/handlers/sweep.ts+++ b/apps/server/src/router-hono/workflows/verify/handlers/sweep.ts@@ -21,9 +21,10 @@ export async function sweep(c: Context) {const outcome = await sweepStuckVerifyRuns(db);log(- 'Verify sweep: settled=%d abandoned=%d skipped=%d',+ 'Verify sweep: settled=%d abandoned=%d released=%d skipped=%d',outcome.settled.length,outcome.abandoned.length,+ outcome.released.length,outcome.skipped,);return c.json({ ...outcome, success: true });diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.tsindex 7a6d0732464..d2acc1f830b 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts@@ -11,6 +11,7 @@ import type { LobeChatDatabase } from '@/database/type';import { formatErrorForState } from '@/server/modules/AgentRuntime/formatErrorForState';import {instantiateVerifyPlanOnStart,+ releaseUndeliveredRound,runVerifyOnCompletion,settleFailedRepair,} from '@/server/services/verify';@@ -489,12 +490,12 @@ export class CompletionLifecycle {if (reason === 'error' || reason === 'interrupted') {after(async () => {- await settleFailedRepair(- this.serverDB,- runOrigin.userId || this.userId,- operationId,- this.workspaceId,- );+ const userId = runOrigin.userId || this.userId;+ await settleFailedRepair(this.serverDB, userId, operationId, this.workspaceId);+ // A task run that failed before delivering leaves the round opened at+ // its start with nothing to verify. When planning is still under way,+ // `instantiateVerifyPlanOnStart` releases the round once it lands.+ await releaseUndeliveredRound(this.serverDB, userId, operationId, this.workspaceId);});}diff --git a/apps/server/src/services/agentRuntime/__tests__/completionTopicRunSettled.test.ts b/apps/server/src/services/agentRuntime/__tests__/completionTopicRunSettled.test.tsindex 85548a82ed7..a7e4920e215 100644--- a/apps/server/src/services/agentRuntime/__tests__/completionTopicRunSettled.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/completionTopicRunSettled.test.ts@@ -12,6 +12,7 @@ vi.mock('@/business/server/agent-run/notifyAgentRunCompleted', () => ({}));vi.mock('@/server/services/workRegistration', () => ({ registerWorksForOperation: vi.fn() }));vi.mock('@/server/services/verify', () => ({+ releaseUndeliveredRound: vi.fn(async () => {}),runVerifyOnCompletion: vi.fn(async () => {}),settleFailedRepair: vi.fn(async () => {}),}));diff --git a/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.ts b/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.tsindex ed72160cb78..48bbdb4e511 100644--- a/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.ts@@ -88,6 +88,7 @@ describe('CompletionLifecycle β verify gate scheduling', () => {vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});const settle = vi.spyOn(verifyServices, 'settleFailedRepair').mockResolvedValue(false);+ vi.spyOn(verifyServices, 'releaseUndeliveredRound').mockResolvedValue(false);await lifecycle.dispatchHooks('repair-op',@@ -97,4 +98,22 @@ describe('CompletionLifecycle β verify gate scheduling', () => {await Promise.all(after.mock.calls.map(([callback]) => callback()));expect(settle).toHaveBeenCalledWith(expect.anything(), 'user-1', 'repair-op', undefined);});++ it('releases the round of a task run that ended in error', async () => {+ vi.spyOn(verifyServices, 'settleFailedRepair').mockResolvedValue(false);+ const release = vi.spyOn(verifyServices, 'releaseUndeliveredRound').mockResolvedValue(true);+ const lifecycle = new CompletionLifecycle({} as any, 'user-1');+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);+ vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});++ await lifecycle.dispatchHooks(+ 'task-op',+ { host: { hooks: [] }, origin: {}, status: 'error' },+ 'error',+ );+ await Promise.all(after.mock.calls.map(([callback]) => callback()));++ expect(release).toHaveBeenCalledWith(expect.anything(), 'user-1', 'task-op', undefined);+ });});diff --git a/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts b/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.tsindex 9d35a689c7f..c1235190e21 100644--- a/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts+++ b/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts@@ -17,6 +17,8 @@ const mocks = vi.hoisted(() => ({carryPassedResultsForward: vi.fn(),confirmPlan: vi.fn(),+ detachUndeliveredRound: vi.fn(),+ recomputeStatus: vi.fn(),ensureForOperation: vi.fn(),generateDraftPlan: vi.fn(),operationFindById: vi.fn(),@@ -43,6 +45,7 @@ vi.mock('../acceptanceService', async (original) => ({acceptanceModel: { update: mocks.acceptanceUpdate },attachPolicyRun: mocks.acceptanceAttachPolicyRun,ensureForSubject: mocks.acceptanceEnsureForSubject,+ recomputeStatus: mocks.recomputeStatus,};}),}));@@ -79,6 +82,7 @@ vi.mock('@/database/models/verifyRun', () => ({VerifyRunModel: vi.fn(function () {return {confirmPlan: mocks.confirmPlan,+ detachUndeliveredRound: mocks.detachUndeliveredRound,ensureForOperation: mocks.ensureForOperation,findByOperation: mocks.runFindByOperation,setMetadata: mocks.setMetadata,@@ -156,6 +160,33 @@ describe('Verify acceptance lifecycle', () => {expect(mocks.acceptanceAttachPolicyRun).toHaveBeenCalledWith('run-1', 'acceptance-1');});+ /**+ * Regression: a run that failed at dispatch was over before its plan was+ * split, and in queue mode its completion ran in another process β the+ * round landed after the release had looked for it and stayed `planned`.+ */+ it('releases the round once it lands when the run already failed', async () => {+ mocks.taskAcceptanceResolve.mockResolvedValue({+ acceptance: { id: 'acceptance-1' },+ config: { enabled: true },+ requirement: 'The novel is complete and coherent',+ });+ mocks.taskFindById.mockResolvedValue({ name: 'Novel' });+ const round = { id: 'run-1', acceptanceId: 'acceptance-1', plan, status: 'planned' };+ mocks.runFindByOperation+ .mockResolvedValueOnce(null)+ .mockResolvedValueOnce({ id: 'run-1', plan })+ .mockResolvedValue(round);+ mocks.operationFindById.mockResolvedValue({ parentOperationId: null, status: 'error' });+ mocks.detachUndeliveredRound.mockResolvedValue(true);++ await instantiateVerifyPlanOnStart(db, 'user-1', { operationId: 'operation-1', taskId: 't' });++ expect(mocks.acceptanceAttachPolicyRun).toHaveBeenCalledWith('run-1', 'acceptance-1');+ expect(mocks.detachUndeliveredRound).toHaveBeenCalledWith('run-1');+ expect(mocks.recomputeStatus).toHaveBeenCalledWith('acceptance-1');+ });+/*** Regression: the builder authored and confirmed its own plan through the CLI,* so this function found a plan and returned before the attach below it. Thediff --git a/apps/server/src/services/verify/__tests__/sweep.test.ts b/apps/server/src/services/verify/__tests__/sweep.test.tsindex 2589c975016..b36926d049d 100644--- a/apps/server/src/services/verify/__tests__/sweep.test.ts+++ b/apps/server/src/services/verify/__tests__/sweep.test.ts@@ -5,6 +5,7 @@ import { VERIFY_ABANDONED_MS, VERIFY_ROLLUP_GRACE_MS } from '../staleness';import { sweepStuckVerifyRuns } from '../sweep';const {+ releaseUndeliveredRound,settleFailedRepair,claimVerifying,findStuckVerifying,@@ -14,6 +15,7 @@ const {upsertByCheckItem,finalizeVerifyRun,} = vi.hoisted(() => ({+ releaseUndeliveredRound: vi.fn(),settleFailedRepair: vi.fn(),claimVerifying: vi.fn(),finalizeVerifyRun: vi.fn(),@@ -48,6 +50,7 @@ vi.mock('../statusService', () => ({}),}));vi.mock('../repairTerminal', () => ({ settleFailedRepair }));+vi.mock('../undeliveredRound', () => ({ releaseUndeliveredRound }));vi.mock('../settle', () => ({ finalizeVerifyRun }));const db = {} as any;@@ -74,6 +77,7 @@ const singlePage = (runs: unknown[]) => {describe('sweepStuckVerifyRuns', () => {beforeEach(() => {[+ releaseUndeliveredRound,settleFailedRepair,claimVerifying,finalizeVerifyRun,@@ -300,6 +304,26 @@ describe('sweepStuckVerifyRuns', () => {settleFailedRepair.mockResolvedValue(true);expect((await sweepStuckVerifyRuns(db, { now: NOW })).abandoned).toEqual(['run-1']);expect(settleFailedRepair).toHaveBeenCalledWith(db, 'u1', 'op-1', undefined);+ expect(releaseUndeliveredRound).not.toHaveBeenCalled();expect(finalizeVerifyRun).not.toHaveBeenCalled();});++ it('releases the planned round of a task run that ended without a delivery', async () => {+ singlePage([stuckRun({ status: 'planned' })]);+ settleFailedRepair.mockResolvedValue(false);+ releaseUndeliveredRound.mockResolvedValue(true);+ const outcome = await sweepStuckVerifyRuns(db, { now: NOW });+ expect(outcome.released).toEqual(['run-1']);+ expect(outcome.abandoned).toEqual([]);+ expect(releaseUndeliveredRound).toHaveBeenCalledWith(db, 'u1', 'op-1', undefined);+ expect(claimVerifying).not.toHaveBeenCalled();+ expect(finalizeVerifyRun).not.toHaveBeenCalled();+ });++ it('skips a planned round neither path can close', async () => {+ singlePage([stuckRun({ status: 'planned' })]);+ settleFailedRepair.mockResolvedValue(false);+ releaseUndeliveredRound.mockResolvedValue(false);+ expect((await sweepStuckVerifyRuns(db, { now: NOW })).skipped).toBe(1);+ });});diff --git a/apps/server/src/services/verify/__tests__/undeliveredRound.test.ts b/apps/server/src/services/verify/__tests__/undeliveredRound.test.tsnew file mode 100644index 00000000000..300bf9e76ad--- /dev/null+++ b/apps/server/src/services/verify/__tests__/undeliveredRound.test.ts@@ -0,0 +1,78 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { releaseUndeliveredRound } from '../undeliveredRound';++const m = vi.hoisted(() => ({+ op: vi.fn(),+ run: vi.fn(),+ detach: vi.fn(),+ recompute: vi.fn(),+}));+vi.mock('@/database/models/agentOperation', () => ({+ AgentOperationModel: vi.fn(function () {+ return { findById: m.op };+ }),+}));+vi.mock('@/database/models/verifyRun', () => ({+ VerifyRunModel: vi.fn(function () {+ return { detachUndeliveredRound: m.detach, findByOperation: m.run };+ }),+}));+vi.mock('../acceptanceService', () => ({+ AcceptanceService: vi.fn(function () {+ return { recomputeStatus: m.recompute };+ }),+}));++const db = {} as any;+const round = { id: 'run', acceptanceId: 'acceptance', roundIndex: 9, status: 'planned' };++describe('releaseUndeliveredRound', () => {+ beforeEach(() => {+ Object.values(m).forEach((mock) => mock.mockReset());+ m.op.mockResolvedValue({ parentOperationId: null, status: 'error' });+ m.run.mockResolvedValue(round);+ m.detach.mockResolvedValue(true);+ });++ it.each(['error', 'abandoned', 'interrupted'])(+ 'takes the round of a task run that ended %s off the acceptance',+ async (status) => {+ m.op.mockResolvedValue({ parentOperationId: null, status });+ expect(await releaseUndeliveredRound(db, 'user', 'op', 'ws')).toBe(true);+ expect(m.detach).toHaveBeenCalledWith('run');+ // The acceptance follows its latest round, so it must be re-derived from+ // the rounds that remain.+ expect(m.recompute).toHaveBeenCalledWith('acceptance');+ },+ );++ it.each(['done', 'running', 'idle'])('keeps the round of a run that is %s', async (status) => {+ m.op.mockResolvedValue({ parentOperationId: null, status });+ expect(await releaseUndeliveredRound(db, 'user', 'op')).toBe(false);+ expect(m.detach).not.toHaveBeenCalled();+ });++ it('leaves repairs to settleFailedRepair', async () => {+ m.op.mockResolvedValue({ parentOperationId: 'parent', status: 'error' });+ expect(await releaseUndeliveredRound(db, 'user', 'op')).toBe(false);+ expect(m.run).not.toHaveBeenCalled();+ });++ it.each([+ ['no round', null],+ ['a round off any acceptance', { ...round, acceptanceId: null }],+ ['a round that already started judging', { ...round, status: 'verifying' }],+ ])('does nothing for %s', async (_, run) => {+ m.run.mockResolvedValue(run);+ expect(await releaseUndeliveredRound(db, 'user', 'op')).toBe(false);+ expect(m.detach).not.toHaveBeenCalled();+ });++ it('does not recompute when the round was judged in the meantime', async () => {+ m.detach.mockResolvedValue(false);+ expect(await releaseUndeliveredRound(db, 'user', 'op')).toBe(false);+ expect(m.recompute).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/verify/index.ts b/apps/server/src/services/verify/index.tsindex cd7001e8a73..550f31e0e8d 100644--- a/apps/server/src/services/verify/index.ts+++ b/apps/server/src/services/verify/index.ts@@ -67,4 +67,5 @@ export { VERIFY_ABANDONED_MS, VERIFY_ROLLUP_GRACE_MS } from './staleness';export { VerifyStatusService } from './statusService';export { sweepStuckVerifyRuns, type VerifySweepOutcome } from './sweep';export { resolveEvidenceMetadata } from './terminalEvidence';+export { releaseUndeliveredRound } from './undeliveredRound';export { settleVerifierCheckFromTerminal } from './verifierTerminal';diff --git a/apps/server/src/services/verify/planInstantiation.ts b/apps/server/src/services/verify/planInstantiation.tsindex 01850203b5a..b16c7530b9d 100644--- a/apps/server/src/services/verify/planInstantiation.ts+++ b/apps/server/src/services/verify/planInstantiation.ts@@ -8,6 +8,7 @@ import type { LobeChatDatabase } from '@/database/type';import { AcceptanceService, buildAcceptanceCheckUnion } from './acceptanceService';import { VerifyPlanGeneratorService } from './planGenerator';import { attachTaskRunToAcceptance, resolveTaskAcceptance } from './taskAcceptance';+import { releaseUndeliveredRound } from './undeliveredRound';const log = debug('lobe-server:verify-plan-instantiation');@@ -37,6 +38,25 @@ export const instantiateVerifyPlanOnStart = async (userId: string,params: InstantiateVerifyPlanParams,workspaceId?: string,+): Promise<void> => {+ await instantiatePlan(db, userId, params, workspaceId);++ // Planning can outlast the run: a run that fails at dispatch is over within a+ // second, while splitting the requirement takes several. In queue mode the+ // completion that would release the round runs in another process and cannot+ // wait for this one, so whichever side finishes last releases it.+ try {+ await releaseUndeliveredRound(db, userId, params.operationId, workspaceId);+ } catch (error) {+ log('releasing the round of op %s failed (non-fatal): %O', params.operationId, error);+ }+};++const instantiatePlan = async (+ db: LobeChatDatabase,+ userId: string,+ params: InstantiateVerifyPlanParams,+ workspaceId?: string,): Promise<void> => {try {const taskModel = new TaskModel(db, userId, workspaceId);diff --git a/apps/server/src/services/verify/sweep.ts b/apps/server/src/services/verify/sweep.tsindex f4c37ac4795..47212b79274 100644--- a/apps/server/src/services/verify/sweep.ts+++ b/apps/server/src/services/verify/sweep.ts@@ -13,6 +13,7 @@ import { planItemToPendingResult } from './resultSnapshot';import { finalizeVerifyRun } from './settle';import { VERIFY_ABANDONED_MS, VERIFY_ROLLUP_GRACE_MS } from './staleness';import { VerifyStatusService } from './statusService';+import { releaseUndeliveredRound } from './undeliveredRound';const log = debug('lobe-server:verify-sweep');@@ -25,6 +26,8 @@ const SWEEP_MAX_RUNS = 1000;export interface VerifySweepOutcome {/** Runs whose outstanding checks were closed as `errored` before the rollup. */abandoned: string[];+ /** Task rounds taken off their acceptance because the run never delivered. */+ released: string[];/** Runs whose checks had all landed and only needed the missing rollup. */settled: string[];/** Runs left alone β still plausibly mid-flight. */@@ -32,8 +35,9 @@ export interface VerifySweepOutcome {}/**- * Recover verification runs stranded in `verifying` and planned repairs whose- * operation has already failed or been interrupted.+ * Recover verification runs stranded in `verifying`, planned repairs whose+ * operation has already failed or been interrupted, and task rounds whose run+ * ended without a delivery (see {@link releaseUndeliveredRound}).** Entering `verifying` is a durable write; the judging that leaves it runs as* post-response work, so any host-level interruption β instance recycled,@@ -67,7 +71,7 @@ export const sweepStuckVerifyRuns = async (const now = options?.now ?? new Date();const pageSize = options?.pageSize ?? SWEEP_PAGE_SIZE;const staleBefore = new Date(now.getTime() - VERIFY_ROLLUP_GRACE_MS);- const outcome: VerifySweepOutcome = { abandoned: [], settled: [], skipped: 0 };+ const outcome: VerifySweepOutcome = { abandoned: [], released: [], settled: [], skipped: 0 };// Walk the whole stranded set, not just its oldest page: rows the sweep leaves// alone keep their timestamp, so a single fixed-size read would return the same@@ -111,16 +115,17 @@ const recoverRun = async (db: LobeChatDatabase,run: VerifyRunItem,now: Date,-): Promise<'abandoned' | 'settled' | 'skipped'> => {+): Promise<'abandoned' | 'released' | 'settled' | 'skipped'> => {const operationId = run.operationId;if (!operationId) return 'skipped';+ const workspaceId = run.workspaceId ?? undefined;if (run.status === 'planned') {- return (await settleFailedRepair(db, run.userId, operationId, run.workspaceId ?? undefined))- ? 'abandoned'+ if (await settleFailedRepair(db, run.userId, operationId, workspaceId)) return 'abandoned';+ return (await releaseUndeliveredRound(db, run.userId, operationId, workspaceId))+ ? 'released': 'skipped';}- const workspaceId = run.workspaceId ?? undefined;const plan = (run.plan ?? []) as VerifyCheckItem[];if (plan.length === 0) return 'skipped';diff --git a/apps/server/src/services/verify/undeliveredRound.ts b/apps/server/src/services/verify/undeliveredRound.tsnew file mode 100644index 00000000000..f2c62ab6be7--- /dev/null+++ b/apps/server/src/services/verify/undeliveredRound.ts@@ -0,0 +1,47 @@+import type { AgentOperationStatus } from '@lobechat/types';+import debug from 'debug';++import { AgentOperationModel } from '@/database/models/agentOperation';+import { VerifyRunModel } from '@/database/models/verifyRun';+import type { LobeChatDatabase } from '@/database/type';++import { AcceptanceService } from './acceptanceService';++const log = debug('lobe-server:verify-undelivered-round');++/** Terminal states of a run that produced nothing to verify. */+const UNDELIVERED_STATUSES = new Set<AgentOperationStatus>(['abandoned', 'error', 'interrupted']);++/**+ * Take a task run's round off its acceptance when the run ended without a+ * delivery.+ *+ * A task's round is opened when its run starts, before the run has done+ * anything. A run that then fails β the device is offline, the budget is+ * spent, the model is overloaded, the lease expires β never reaches the+ * verifier, so its round stays `planned` for good. Every retry opened+ * another one: the acceptance counted rounds that were never verified, and+ * because its status follows the latest round, it read "awaiting+ * verification" long after the task itself had settled.+ *+ * Repairs are not handled here: a repair's round is the next step of a+ * verification already under way and is closed by `settleFailedRepair`.+ */+export const releaseUndeliveredRound = async (+ db: LobeChatDatabase,+ userId: string,+ operationId: string,+ workspaceId?: string,+): Promise<boolean> => {+ const op = await new AgentOperationModel(db, userId, workspaceId).findById(operationId);+ if (!op || op.parentOperationId || !UNDELIVERED_STATUSES.has(op.status)) return false;++ const runModel = new VerifyRunModel(db, userId, workspaceId);+ const run = await runModel.findByOperation(operationId);+ if (!run?.acceptanceId || run.status !== 'planned') return false;+ if (!(await runModel.detachUndeliveredRound(run.id))) return false;++ await new AcceptanceService(db, userId, workspaceId).recomputeStatus(run.acceptanceId);+ log('released round %d of acceptance %s (op %s)', run.roundIndex, run.acceptanceId, operationId);+ return true;+};diff --git a/packages/database/src/models/__tests__/verifyRun.test.ts b/packages/database/src/models/__tests__/verifyRun.test.tsindex 135aff146a9..356a2fab587 100644--- a/packages/database/src/models/__tests__/verifyRun.test.ts+++ b/packages/database/src/models/__tests__/verifyRun.test.ts@@ -5,7 +5,7 @@ import { eq, sql } from 'drizzle-orm';import { beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';-import { acceptances, agentOperations, users, verifyRuns } from '../../schemas';+import { acceptances, agentOperations, users, verifyCheckResults, verifyRuns } from '../../schemas';import type { LobeChatDatabase } from '../../type';import { AgentOperationModel } from '../agentOperation';import { VerifyRunModel } from '../verifyRun';@@ -258,6 +258,44 @@ describe('VerifyRunModel.findStuckVerifying', () => {for (const name of ['live', 'done', 'draft']) expect(found).not.toContain(ids[name]);});+ it('finds a task round whose own run ended without delivering', async () => {+ const [acceptance] = await serverDB+ .insert(acceptances)+ .values({ userId, subjectType: 'task', subjectId: 'stuck-task' })+ .returning();+ const states = [+ ['offline', 'error', true],+ ['lease', 'abandoned', true],+ ['stopped', 'interrupted', true],+ ['running', 'running', true],+ ['done', 'done', true],+ ['unattached', 'error', false],+ ] as const;+ const ids: Record<string, string> = {};+ for (const [name, status, attached] of states) {+ const operationId = `op-task-${name}`;+ ids[name] = await buildRun(operationId);+ await new VerifyRunModel(serverDB, userId).confirmPlan(ids[name]);+ if (attached) {+ await new VerifyRunModel(serverDB, userId).attachToAcceptance(ids[name], acceptance.id);+ }+ await serverDB+ .update(agentOperations)+ .set({ status })+ .where(eq(agentOperations.id, operationId));+ await backdate(ids[name], 10 * 60 * 1000);+ }++ const stuck = await VerifyRunModel.findStuckVerifying(+ serverDB,+ new Date(Date.now() - 5 * 60 * 1000),+ { limit: 500 },+ );+ const found = stuck.map((run) => run.id);+ expect(found).toEqual(expect.arrayContaining([ids.offline, ids.lease, ids.stopped]));+ for (const name of ['running', 'done', 'unattached']) expect(found).not.toContain(ids[name]);+ });+it('ignores operation-less rounds β there is no rollup to address', async () => {const run = await new VerifyRunModel(serverDB, userId).create({ status: 'verifying' });await backdate(run.id, 10 * 60 * 1000);@@ -471,3 +509,60 @@ describe('VerifyRunModel.recordAutoRepair', () => {expect(state?.verifyAutoRepair).toBeNull();});});++describe('VerifyRunModel.detachUndeliveredRound', () => {+ const model = () => new VerifyRunModel(serverDB, userId);+ const attachedRound = async (operationId: string) => {+ const [acceptance] = await serverDB+ .insert(acceptances)+ .values({ userId, subjectType: 'task', subjectId: `detach-${operationId}` })+ .returning();+ const runId = await buildRun(operationId);+ await model().confirmPlan(runId);+ await model().attachToAcceptance(runId, acceptance.id);+ return { acceptanceId: acceptance.id, runId };+ };+ const addResult = (runId: string, status: 'failed' | 'pending') =>+ serverDB.insert(verifyCheckResults).values({+ checkItemId: 'item-1',+ status,+ userId,+ verifierType: 'llm',+ verifyRunId: runId,+ });++ it('takes a planned round off its acceptance and frees its index', async () => {+ const { acceptanceId, runId } = await attachedRound('op-detach-1');++ expect(await model().detachUndeliveredRound(runId)).toBe(true);+ expect(await model().listByAcceptance(acceptanceId)).toEqual([]);+ const [row] = await serverDB.select().from(verifyRuns).where(eq(verifyRuns.id, runId));+ expect(row).toMatchObject({ acceptanceId: null, roundIndex: null, status: 'planned' });+ });++ it('counts evidence the builder submitted mid-run as never verified', async () => {+ const { runId } = await attachedRound('op-detach-2');+ await addResult(runId, 'pending');++ expect(await model().detachUndeliveredRound(runId)).toBe(true);+ });++ it('keeps a round that has a judged result or left planned', async () => {+ const judged = await attachedRound('op-detach-3');+ await addResult(judged.runId, 'failed');+ const verifying = await attachedRound('op-detach-4');+ await model().updateStatus(verifying.runId, 'verifying');++ expect(await model().detachUndeliveredRound(judged.runId)).toBe(false);+ expect(await model().detachUndeliveredRound(verifying.runId)).toBe(false);+ expect(await model().listByAcceptance(judged.acceptanceId)).toHaveLength(1);+ });++ it("never touches another owner's round", async () => {+ const { runId } = await attachedRound('op-detach-5');++ expect(await new VerifyRunModel(serverDB, otherUserId).detachUndeliveredRound(runId)).toBe(+ false,+ );+ });+});diff --git a/packages/database/src/models/verifyRun.ts b/packages/database/src/models/verifyRun.tsindex 2a92d1e3f93..3609291d876 100644--- a/packages/database/src/models/verifyRun.ts+++ b/packages/database/src/models/verifyRun.ts@@ -352,6 +352,33 @@ export class VerifyRunModel {return run;};+ /**+ * Take a round its run never delivered off the acceptance. Only a `planned`+ * round with no judged result qualifies β evidence the builder submitted+ * mid-run sits in `pending` rows and was never verified β so a round that+ * has started judging keeps its place. The row stays, so a late finish of+ * the same run can attach it again as a new round.+ */+ detachUndeliveredRound = async (runId: string): Promise<boolean> => {+ const detached = await this.db+ .update(verifyRuns)+ .set({ acceptanceId: null, roundIndex: null })+ .where(+ and(+ eq(verifyRuns.id, runId),+ eq(verifyRuns.status, 'planned'),+ isNotNull(verifyRuns.acceptanceId),+ sql`not exists (select 1 from ${verifyCheckResults}+ where ${verifyCheckResults.verifyRunId} = ${verifyRuns.id}+ and ${verifyCheckResults.status} <> 'pending')`,+ this.ownership(),+ ),+ )+ .returning({ id: verifyRuns.id });++ return detached.length > 0;+ };+/*** A harness run arriving while the acceptance still holds a draft round must* not open another round: its plan folds into the draft, the draft becomes the@@ -666,8 +693,10 @@ export class VerifyRunModel {/*** One page of runs stranded in `verifying`, or confirmed `planned` rounds- * whose child operation aborted, since before `olderThan`, across- * all owners β the sweep's input (see `sweepStuckVerifyRuns`).+ * whose operation ended without a delivery (a child that aborted, or a+ * task's own run that errored or was abandoned while still on the+ * acceptance), since before `olderThan`, across all owners β the sweep's+ * input (see `sweepStuckVerifyRuns`).** No per-user scope, like `TaskModel.findStuckTasks`: this backs a global* cron, and each row carries the owner the recovery is then performed as.@@ -711,6 +740,14 @@ export class VerifyRunModel {and ${agentOperations.parentOperationId} is not nulland ${agentOperations.completionReason} in ('error', 'interrupted'))`,),+ and(+ eq(verifyRuns.status, 'planned'),+ isNotNull(verifyRuns.acceptanceId),+ sql`exists (select 1 from ${agentOperations}+ where ${agentOperations.id} = ${verifyRuns.operationId}+ and ${agentOperations.parentOperationId} is null+ and ${agentOperations.status} in ('error', 'abandoned', 'interrupted'))`,+ ),)!,lt(verifyRuns.updatedAt, olderThan),isNotNull(verifyRuns.operationId),