Skip to content

🀯 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.

πŸ› fix(verify): bind a builder-authored verification round to its Task Acceptance (#19800)

Arvin Xue2197131c5de
diff --git a/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts b/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts
index 9b2e21493c4..4c24897a03e 100644
--- a/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts
+++ b/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts
@@ -13,6 +13,7 @@ const mocks = vi.hoisted(() => ({
findRunById: vi.fn(),
foldIntoRound: vi.fn(),
ensureForSubject: vi.fn(),
+ listResultsByRun: vi.fn(),
listByAcceptance: vi.fn(),
setDecision: vi.fn(),
taskResolve: vi.fn(),
@@ -42,7 +43,11 @@ vi.mock('@/database/models/verifyRun', () => ({
};
}),
}));
-vi.mock('@/database/models/verifyCheckResult', () => ({ VerifyCheckResultModel: vi.fn() }));
+vi.mock('@/database/models/verifyCheckResult', () => ({
+ VerifyCheckResultModel: vi.fn(function () {
+ return { listByRun: mocks.listResultsByRun };
+ }),
+}));
vi.mock('@/database/models/verifyEvidence', () => ({ VerifyEvidenceModel: vi.fn() }));
vi.mock('@/database/models/verifyReport', () => ({
VerifyReportModel: vi.fn(function () {
@@ -77,6 +82,8 @@ const acceptance = (status: string) => ({
describe('AcceptanceService decision gating', () => {
beforeEach(() => {
vi.clearAllMocks();
+ // A run that has not executed yet β€” the only kind that may fold into a draft.
+ mocks.listResultsByRun.mockResolvedValue([]);
mocks.findPolicyById.mockImplementation(function (...args) {
return mocks.findById(...args);
});
@@ -225,6 +232,30 @@ describe('AcceptanceService decision gating', () => {
expect(mocks.attachToAcceptance).not.toHaveBeenCalled();
});
+ /**
+ * Regression: a verification driven through the CLI writes its results before the
+ * Task drive binds the round. `foldIntoRound` refuses any source with results, so
+ * picking the fold path for it threw, the binder swallowed the throw, and the round
+ * stayed orphaned β€” the Goal review then errored on "no Acceptance" anyway.
+ */
+ it('appends an executed run after the draft instead of trying to fold it', async () => {
+ mocks.findById.mockResolvedValue(acceptance('planned'));
+ mocks.findRunById.mockResolvedValue({ acceptanceId: null, id: 'run-2', plan: [] });
+ mocks.listByAcceptance.mockResolvedValue([
+ { id: 'run-1', planConfirmedAt: null, roundIndex: 1, status: 'planned', userDecision: null },
+ ]);
+ mocks.listResultsByRun.mockResolvedValue([{ id: 'result-1', verifyRunId: 'run-2' }]);
+ mocks.attachToAcceptance.mockResolvedValue({
+ acceptanceId: 'acc-1',
+ id: 'run-2',
+ roundIndex: 2,
+ });
+
+ await expect(service().attachRun('run-2', 'acc-1')).resolves.toMatchObject({ id: 'run-2' });
+ expect(mocks.foldIntoRound).not.toHaveBeenCalled();
+ expect(mocks.attachToAcceptance).toHaveBeenCalledWith('run-2', 'acc-1', undefined);
+ });
+
it('opens a new round when the newest one is no longer a draft', async () => {
mocks.findById.mockResolvedValue(acceptance('planned'));
mocks.findRunById.mockResolvedValue({ acceptanceId: null, id: 'run-3', plan: [] });
diff --git a/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts b/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts
index b2adef5de72..cb2fc9a0957 100644
--- a/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts
+++ b/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts
@@ -21,6 +21,7 @@ const mocks = vi.hoisted(() => ({
setMetadata: vi.fn(),
setPlan: vi.fn(),
taskFindById: vi.fn(),
+ taskAcceptanceAttachRun: vi.fn(),
taskAcceptanceResolve: vi.fn(),
}));
@@ -51,6 +52,7 @@ vi.mock('../planGenerator', () => ({
}));
vi.mock('../taskAcceptance', () => ({
+ attachTaskRunToAcceptance: mocks.taskAcceptanceAttachRun,
resolveTaskAcceptance: mocks.taskAcceptanceResolve,
}));
@@ -146,6 +148,67 @@ describe('Verify acceptance lifecycle', () => {
expect(mocks.acceptanceAttachPolicyRun).toHaveBeenCalledWith('run-1', '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. The
+ * round stayed orphaned from the Task's Acceptance, passed verification, and
+ * the Goal review then errored with "no Acceptance" β€” parking a delivery that
+ * met every criterion on a human decision gate.
+ */
+ it('binds a plan the builder authored itself to the task acceptance', async () => {
+ mocks.taskAcceptanceResolve.mockResolvedValue({
+ acceptance: { id: 'acceptance-1' },
+ config: { enabled: true },
+ requirement: 'Cut an isolated worktree',
+ });
+ mocks.taskFindById.mockResolvedValue({ name: 'Worktree' });
+ const authored = { acceptanceId: null, id: 'run-1', plan, planConfirmedAt: new Date() };
+ mocks.runFindByOperation.mockResolvedValue(authored);
+
+ await instantiateVerifyPlanOnStart(db, 'user-1', {
+ operationId: 'operation-1',
+ taskId: 'task-1',
+ });
+
+ // The plan is the builder's β€” regenerating it is exactly what the early
+ // return protects β€” but the round still has to belong to the Acceptance.
+ expect(mocks.generateDraftPlan).not.toHaveBeenCalled();
+ expect(mocks.taskAcceptanceAttachRun).toHaveBeenCalledWith(
+ db,
+ 'user-1',
+ { acceptanceId: 'acceptance-1', run: authored },
+ undefined,
+ );
+ });
+
+ /**
+ * Regression: an unconfirmed builder plan was bound too. It stayed the
+ * Acceptance's newest round as a draft, and the next attempt folded into it β€” so
+ * the round a later attempt ran in carried an operation that was not running.
+ */
+ it('leaves an unconfirmed builder plan unbound', async () => {
+ mocks.taskAcceptanceResolve.mockResolvedValue({
+ acceptance: { id: 'acceptance-1' },
+ config: { enabled: true },
+ requirement: 'Cut an isolated worktree',
+ });
+ mocks.taskFindById.mockResolvedValue({ name: 'Worktree' });
+ mocks.runFindByOperation.mockResolvedValue({
+ acceptanceId: null,
+ id: 'run-1',
+ plan,
+ planConfirmedAt: null,
+ });
+
+ await instantiateVerifyPlanOnStart(db, 'user-1', {
+ operationId: 'operation-1',
+ taskId: 'task-1',
+ });
+
+ expect(mocks.taskAcceptanceAttachRun).not.toHaveBeenCalled();
+ expect(mocks.generateDraftPlan).not.toHaveBeenCalled();
+ });
+
it('skips instantiation for a recurring task, even when an Acceptance policy exists', async () => {
// A failed acceptance pauses the task, and `paused` is permanently off the
// cron β€” so a recurring task must never get a verify plan in the first place.
diff --git a/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts b/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts
index a9844b2275f..d0d875fa6ec 100644
--- a/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts
+++ b/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts
@@ -9,8 +9,13 @@ import { scheduleGoalAdvance } from '@/server/services/goal/scheduler';
import { reviewGoalDelivery } from '../goalReview';
import { driveTaskFromVerify, finalizeVerifyRun } from '../settle';
+import { attachTaskRunToAcceptance, resolveTaskAcceptance } from '../taskAcceptance';
vi.mock('../goalReview', () => ({ reviewGoalDelivery: vi.fn() }));
+vi.mock('../taskAcceptance', () => ({
+ attachTaskRunToAcceptance: vi.fn(),
+ resolveTaskAcceptance: vi.fn(),
+}));
vi.mock('../repairService', () => ({
maybeAutoRepair: vi.fn(),
@@ -180,6 +185,74 @@ describe('driveTaskFromVerify', () => {
expect(deliverMock.mock.calls[0][0].errorMessage.toLowerCase()).toContain('internal error');
});
+ /**
+ * Regression: a builder that planned its own round left `acceptanceId` null, so
+ * the review could not reach the delivery and errored with "no Acceptance" β€” a
+ * failure class with no recovery branch, which parked a passing delivery on a
+ * person. The link is repaired here, before the review reads it.
+ */
+ it('binds an orphaned passing round to the task acceptance before reviewing it', async () => {
+ const orphan = { acceptanceId: null, id: 'run-1', status: 'passed' };
+ runFindByOperation.mockResolvedValue(orphan);
+ vi.mocked(resolveTaskAcceptance).mockResolvedValue({
+ acceptance: { id: 'acceptance-1' } as any,
+ config: {},
+ });
+ vi.mocked(reviewGoalDelivery).mockResolvedValue({
+ feedback: '',
+ predictionIds: [],
+ status: 'passed',
+ });
+
+ await driveTaskFromVerify(db, 'u1', 'op-1');
+
+ expect(attachTaskRunToAcceptance).toHaveBeenCalledWith(
+ db,
+ 'u1',
+ { acceptanceId: 'acceptance-1', run: orphan },
+ undefined,
+ );
+ expect(vi.mocked(attachTaskRunToAcceptance).mock.invocationCallOrder[0]).toBeLessThan(
+ vi.mocked(reviewGoalDelivery).mock.invocationCallOrder[0],
+ );
+ expect(serviceUpdateStatus).toHaveBeenCalledWith({ id: 'task-1', status: 'completed' });
+ });
+
+ /**
+ * Regression: a failed Acceptance resolution was swallowed after the drive claim
+ * was stamped. The unattached round was reviewed into the non-retryable
+ * "review could not run" gate, and every later finalizer call stopped at the
+ * stamped claim β€” a transient error became a permanent human escalation.
+ */
+ it('leaves the drive unclaimed when the acceptance cannot be resolved', async () => {
+ runFindByOperation.mockResolvedValue({ acceptanceId: null, id: 'run-1', status: 'passed' });
+ vi.mocked(resolveTaskAcceptance).mockRejectedValue(new Error('connection terminated'));
+
+ await driveTaskFromVerify(db, 'u1', 'op-1');
+
+ expect(runClaimTaskDrive).not.toHaveBeenCalled();
+ expect(reviewGoalDelivery).not.toHaveBeenCalled();
+ expect(taskUpdateStatus).not.toHaveBeenCalled();
+ });
+
+ it('leaves an already attached round alone', async () => {
+ runFindByOperation.mockResolvedValue({
+ acceptanceId: 'acceptance-1',
+ id: 'run-1',
+ status: 'passed',
+ });
+ vi.mocked(reviewGoalDelivery).mockResolvedValue({
+ feedback: '',
+ predictionIds: [],
+ status: 'passed',
+ });
+
+ await driveTaskFromVerify(db, 'u1', 'op-1');
+
+ expect(resolveTaskAcceptance).not.toHaveBeenCalled();
+ expect(attachTaskRunToAcceptance).not.toHaveBeenCalled();
+ });
+
it('does not launch a duplicate review when task drive is already claimed', async () => {
runFindByOperation.mockResolvedValue({
id: 'run-1',
@@ -193,6 +266,10 @@ describe('driveTaskFromVerify', () => {
beforeEach(() => {
vi.mocked(reviewGoalDelivery).mockReset();
+ vi.mocked(resolveTaskAcceptance).mockReset().mockResolvedValue(undefined);
+ vi.mocked(attachTaskRunToAcceptance)
+ .mockReset()
+ .mockImplementation(async (_db, _userId, params) => params.run);
vi.mocked(scheduleGoalAdvance).mockClear();
goalFindByTask.mockReset();
[
diff --git a/apps/server/src/services/verify/__tests__/goalReview.test.ts b/apps/server/src/services/verify/__tests__/goalReview.test.ts
index f1b1ad7b765..4eba3f9c32b 100644
--- a/apps/server/src/services/verify/__tests__/goalReview.test.ts
+++ b/apps/server/src/services/verify/__tests__/goalReview.test.ts
@@ -221,6 +221,65 @@ describe('Goal automatic Acceptance review', () => {
expect(mocks.predict).toHaveBeenCalledTimes(2);
});
+ /**
+ * Regression: every exception in here produced one canned sentence telling the
+ * reader to configure a review model. A round that was never linked to its
+ * Acceptance therefore escalated to a person as a model-configuration problem,
+ * hiding the only fact that could have unblocked it.
+ */
+ it('carries the real reason when the review cannot even start', async () => {
+ mocks.run.mockResolvedValue({ id: 'r1', acceptanceId: null, metadata: {} });
+
+ const review = await reviewGoalDelivery(db, 'u1', 't1', 'op1');
+
+ expect(review?.status).toBe('errored');
+ expect(review?.feedback).toContain('Goal delivery has no Acceptance');
+ expect(review?.feedback).not.toContain('Configure an available model');
+ });
+
+ /**
+ * Regression: an unconfirmed draft left in the round chain β€” abandoned, or one a
+ * CLI-driven verification was appended past β€” contributed result-less required
+ * checks to the union, each rejected as missing evidence, so a delivery that
+ * passed every confirmed check was sent back anyway.
+ */
+ it('judges only confirmed rounds, not a draft left in the chain', async () => {
+ mocks.rounds.mockResolvedValue({
+ runs: [
+ {
+ id: 'draft',
+ plan: [{ ...check, id: 'draft-only', title: 'Never confirmed' }],
+ planConfirmedAt: null,
+ roundIndex: 1,
+ status: 'planned',
+ userDecision: null,
+ },
+ { id: 'r1', plan: [check], planConfirmedAt: new Date(), roundIndex: 2, status: 'passed' },
+ ],
+ 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 provider
+ * diagnostics out of the server log.
+ */
+ it('keeps an unexpected backend failure out of the feedback', async () => {
+ mocks.rounds.mockRejectedValue(
+ new Error('select "verify_runs"."id" from ... β€” connection terminated'),
+ );
+
+ const review = await reviewGoalDelivery(db, 'u1', 't1', 'op1');
+
+ expect(review?.status).toBe('errored');
+ expect(review?.feedback).toContain('internal error');
+ expect(review?.feedback).not.toContain('verify_runs');
+ });
+
/**
* Regression: a review that could not run on one check was retried by
* rerunning the whole review. Every other check was re-asked and its opinion
diff --git a/apps/server/src/services/verify/__tests__/lifecycleClaim.test.ts b/apps/server/src/services/verify/__tests__/lifecycleClaim.test.ts
index f9249ee3fda..e5c159d4cd7 100644
--- a/apps/server/src/services/verify/__tests__/lifecycleClaim.test.ts
+++ b/apps/server/src/services/verify/__tests__/lifecycleClaim.test.ts
@@ -5,6 +5,7 @@ import { runVerifyAfterEvidenceSubmission, runVerifyOnCompletion } from '../life
import { VERIFY_ABANDONED_MS } from '../staleness';
const {
+ attachTaskRunToAcceptance,
claimEvidenceCollection,
claimVerifying,
execute,
@@ -13,9 +14,11 @@ const {
operationFindById,
finalizeVerifyRun,
recordHeterogeneousDeliverableEvidence,
+ resolveTaskAcceptance,
startEvidenceSubmission,
updateStatus,
} = vi.hoisted(() => ({
+ attachTaskRunToAcceptance: vi.fn(),
claimEvidenceCollection: vi.fn(),
claimVerifying: vi.fn(),
evidenceListByRun: vi.fn(),
@@ -24,6 +27,7 @@ const {
findByOperation: vi.fn(),
operationFindById: vi.fn(),
recordHeterogeneousDeliverableEvidence: vi.fn(),
+ resolveTaskAcceptance: vi.fn(),
startEvidenceSubmission: vi.fn(),
updateStatus: vi.fn(),
}));
@@ -83,9 +87,7 @@ vi.mock('../evidenceSubmission', () => ({
recordHeterogeneousDeliverableEvidence,
startEvidenceSubmission,
}));
-vi.mock('../taskAcceptance', () => ({
- resolveTaskAcceptance: vi.fn().mockResolvedValue({ config: { enabled: true } }),
-}));
+vi.mock('../taskAcceptance', () => ({ attachTaskRunToAcceptance, resolveTaskAcceptance }));
const db = {} as any;
const params = { deliverable: 'done', goal: 'ship it', operationId: 'op-1' };
@@ -100,6 +102,7 @@ const confirmedRun = {
describe('runVerifyOnCompletion β€” verification claim', () => {
beforeEach(() => {
[
+ attachTaskRunToAcceptance,
claimEvidenceCollection,
claimVerifying,
evidenceListByRun,
@@ -108,9 +111,19 @@ describe('runVerifyOnCompletion β€” verification claim', () => {
findByOperation,
operationFindById,
recordHeterogeneousDeliverableEvidence,
+ resolveTaskAcceptance,
startEvidenceSubmission,
updateStatus,
].forEach((m) => m.mockReset());
+ resolveTaskAcceptance.mockResolvedValue({
+ acceptance: { id: 'acceptance-1' },
+ config: { enabled: true },
+ });
+ // The real helper hands back the row the round ended up in; by default that is
+ // the row it was given.
+ attachTaskRunToAcceptance.mockImplementation(
+ async (_db: unknown, _userId: string, { run }: { run: unknown }) => run,
+ );
findByOperation.mockResolvedValue(confirmedRun);
operationFindById.mockResolvedValue({ id: 'op-1', model: 'm', provider: 'p', taskId: null });
claimVerifying.mockResolvedValue(true);
@@ -171,6 +184,98 @@ describe('runVerifyOnCompletion β€” verification claim', () => {
expect(startEvidenceSubmission).toHaveBeenCalledTimes(1);
});
+ /**
+ * Regression: attaching onto an acceptance whose newest round is still a draft
+ * folds this run into it and deletes the source row, moving the operation id
+ * across. Keeping the id we came in with meant claiming and reading a row that
+ * no longer exists, and the completion path returned without judging anything.
+ */
+ it('follows the row the attach settled on when the round is folded', async () => {
+ findByOperation.mockResolvedValue({ ...confirmedRun, acceptanceId: null });
+ // Shaped like a real fold: a different row, still claimable. That the survivor
+ // keeps the live status is guaranteed by `VerifyRunModel.foldIntoRound`'s own
+ // test against the database.
+ attachTaskRunToAcceptance.mockResolvedValue({
+ ...confirmedRun,
+ acceptanceId: 'acceptance-1',
+ id: 'folded-run',
+ status: 'planned',
+ });
+ operationFindById.mockResolvedValue({
+ agentId: 'builder',
+ id: 'op-1',
+ model: 'm',
+ provider: 'p',
+ taskId: 'task-1',
+ topicId: 'topic-1',
+ });
+ evidenceListByRun.mockResolvedValue([{ checkItemId: 'c1', type: 'text' }]);
+
+ await runVerifyOnCompletion(db, 'u1', params);
+
+ expect(evidenceListByRun).toHaveBeenCalledWith('folded-run');
+ expect(execute).toHaveBeenCalledTimes(1);
+ });
+
+ /**
+ * Regression: swallowing a failed Acceptance resolution left `verifierAgentId`
+ * undefined, which is also how "this Task has no Acceptance" reads. A transient
+ * failure would hand a Task that pins its own verifier to the builtin one and
+ * settle the Task on that verdict, where before the error stopped the run.
+ */
+ it('stops instead of judging with the fallback verifier when resolution fails', async () => {
+ resolveTaskAcceptance.mockRejectedValue(new Error('connection terminated'));
+ operationFindById.mockResolvedValue({
+ agentId: 'builder',
+ id: 'op-1',
+ model: 'm',
+ provider: 'p',
+ taskId: 'task-1',
+ topicId: 'topic-1',
+ });
+ evidenceListByRun.mockResolvedValue([{ checkItemId: 'c1', type: 'text' }]);
+
+ await runVerifyOnCompletion(db, 'u1', params);
+
+ expect(claimVerifying).not.toHaveBeenCalled();
+ expect(execute).not.toHaveBeenCalled();
+ });
+
+ /**
+ * Regression: only the plan this pipeline creates itself was bound to the Task's
+ * Acceptance. A builder that authored its own plan through the CLI produced a
+ * round with no acceptance, which passed verification and then failed the Goal
+ * review with "no Acceptance" β€” parking a complete delivery on a person.
+ */
+ it('binds a task-bound round to its Acceptance before judging it', async () => {
+ const orphan = { ...confirmedRun, acceptanceId: null };
+ findByOperation.mockResolvedValue(orphan);
+ operationFindById.mockResolvedValue({
+ agentId: 'builder',
+ id: 'op-1',
+ model: 'm',
+ provider: 'p',
+ taskId: 'task-1',
+ topicId: 'topic-1',
+ });
+ evidenceListByRun.mockResolvedValue([{ checkItemId: 'c1', type: 'text' }]);
+
+ await runVerifyOnCompletion(db, 'u1', params);
+
+ expect(attachTaskRunToAcceptance).toHaveBeenCalledWith(
+ db,
+ 'u1',
+ { acceptanceId: 'acceptance-1', run: orphan },
+ undefined,
+ );
+ });
+
+ it('leaves a run with no task out of the Acceptance binding', async () => {
+ await runVerifyOnCompletion(db, 'u1', params);
+
+ expect(attachTaskRunToAcceptance).not.toHaveBeenCalled();
+ });
+
it('judges directly when the builder already submitted evidence inside the Task run', async () => {
operationFindById.mockResolvedValue({
agentId: 'builder',
diff --git a/apps/server/src/services/verify/__tests__/taskAcceptance.test.ts b/apps/server/src/services/verify/__tests__/taskAcceptance.test.ts
index 2181e84a8d0..ef85b83d47c 100644
--- a/apps/server/src/services/verify/__tests__/taskAcceptance.test.ts
+++ b/apps/server/src/services/verify/__tests__/taskAcceptance.test.ts
@@ -1,15 +1,22 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { resolveTaskAcceptance } from '../taskAcceptance';
+import { attachTaskRunToAcceptance, resolveTaskAcceptance } from '../taskAcceptance';
const mocks = vi.hoisted(() => ({
acceptanceEnsure: vi.fn(),
acceptanceFindPolicyBySubject: vi.fn(),
acceptanceUpdatePolicy: vi.fn(),
+ attachPolicyRun: vi.fn(),
taskFindById: vi.fn(),
}));
+vi.mock('../acceptanceService', () => ({
+ AcceptanceService: vi.fn(function () {
+ return { attachPolicyRun: mocks.attachPolicyRun };
+ }),
+}));
+
vi.mock('@/database/models/acceptance', () => ({
AcceptanceModel: vi.fn(function () {
return {
@@ -127,3 +134,63 @@ describe('resolveTaskAcceptance', () => {
expect(resolved?.config).toMatchObject({ enabled: true, maxIterations: 1 });
});
});
+
+/**
+ * Regression: a builder that planned its own verification round through the CLI
+ * left `verify_runs.acceptance_id` null. The round passed, and then the Goal's
+ * Acceptance review β€” which reaches a delivery only through its Acceptance β€”
+ * errored with "no Acceptance", a failure class with no recovery branch. A
+ * delivery that met every criterion was parked on a human decision gate.
+ */
+describe('attachTaskRunToAcceptance', () => {
+ beforeEach(() => {
+ Object.values(mocks).forEach((mock) => mock.mockReset());
+ });
+
+ it('binds an orphaned round to the acceptance that owns the task', async () => {
+ await attachTaskRunToAcceptance(
+ db,
+ 'user-1',
+ { acceptanceId: 'acceptance-1', run: { acceptanceId: null, id: 'run-1' } },
+ 'workspace-1',
+ );
+
+ expect(mocks.attachPolicyRun).toHaveBeenCalledWith('run-1', 'acceptance-1');
+ });
+
+ it('leaves a round that already belongs to an acceptance alone', async () => {
+ const run = { acceptanceId: 'acceptance-1', id: 'run-1' };
+
+ await expect(
+ attachTaskRunToAcceptance(db, 'user-1', { acceptanceId: 'acceptance-2', run }),
+ ).resolves.toBe(run);
+ expect(mocks.attachPolicyRun).not.toHaveBeenCalled();
+ });
+
+ it('never breaks verification when the aggregate refuses the round', async () => {
+ mocks.attachPolicyRun.mockRejectedValue(new Error('This acceptance has already been accepted'));
+ const run = { acceptanceId: null, id: 'run-1' };
+
+ // The caller keeps verifying against the row it already holds.
+ await expect(
+ attachTaskRunToAcceptance(db, 'user-1', { acceptanceId: 'acceptance-1', run }),
+ ).resolves.toBe(run);
+ });
+
+ /**
+ * Regression: attaching onto an acceptance whose newest round is still a draft
+ * folds this run into it and deletes the source row. A caller that kept the id it
+ * passed in would go on claiming and reading a row that no longer exists.
+ */
+ it('hands back the row the round was folded into', async () => {
+ const folded = { acceptanceId: 'acceptance-1', id: 'draft-run' };
+ mocks.attachPolicyRun.mockResolvedValue(folded);
+
+ await expect(
+ attachTaskRunToAcceptance(db, 'user-1', {
+ acceptanceId: 'acceptance-1',
+ run: { acceptanceId: null, id: 'run-1' },
+ }),
+ ).resolves.toBe(folded);
+ });
+});
diff --git a/apps/server/src/services/verify/acceptanceService.ts b/apps/server/src/services/verify/acceptanceService.ts
index 56473280084..cb526424e44 100644
--- a/apps/server/src/services/verify/acceptanceService.ts
+++ b/apps/server/src/services/verify/acceptanceService.ts
@@ -694,7 +694,14 @@ export class AcceptanceService {
// Only the newest round counts β€” `listByAcceptance` is ascending, and an
// older draft the chain has moved past is an abandoned ledger position.
const latest = (await this.runModel.listByAcceptance(acceptanceId)).at(-1);
- const draft = latest && isDraftVerifyRun(latest) ? latest : undefined;
+ // A run that already executed cannot fold (`foldIntoRound` refuses any source
+ // with results): its verdicts belong to its own round. It is appended after
+ // the draft instead β€” the path a verification driven by the CLI takes, since
+ // it writes its results before the Task drive binds the round.
+ const draft =
+ latest && isDraftVerifyRun(latest) && (await this.resultModel.listByRun(runId)).length === 0
+ ? latest
+ : undefined;
if (draft) {
const folded = await this.runModel.foldIntoRound(runId, draft.id);
await this.recomputeStatus(acceptanceId);
diff --git a/apps/server/src/services/verify/goalReview.ts b/apps/server/src/services/verify/goalReview.ts
index 04a7e338229..d4fbda0d3a2 100644
--- a/apps/server/src/services/verify/goalReview.ts
+++ b/apps/server/src/services/verify/goalReview.ts
@@ -1,3 +1,4 @@
+import { isDraftVerifyRun } from '@lobechat/const/verify';
import type { VerifyRunMetadata } from '@lobechat/types';
import { GoalModel } from '@/database/models/goal';
@@ -10,6 +11,24 @@ import { mapWithConcurrency } from './concurrency';
import { resolveGoalReviewModelConfig } from './goalReviewModelConfig';
import { REVIEW_PREDICT_CONCURRENCY, VerifyReviewPredictorService } from './reviewPredictor';
+/**
+ * The startup failures this review can name back to a person. Everything else that
+ * can throw in here β€” the database, the acceptance and evidence reads, the model
+ * lookup β€” could carry SQL, identifiers or provider diagnostics, and the feedback
+ * string is persisted on the run and quoted into the escalation, so those stay in
+ * the server log only.
+ */
+const REVIEW_BLOCKERS = {
+ acceptanceMissing: 'Goal Acceptance was not found',
+ noAcceptance: 'Goal delivery has no Acceptance',
+ noRequiredChecks: 'Goal Acceptance has no required checks',
+} as const;
+
+const namedBlocker = (error: unknown): string | undefined => {
+ const message = error instanceof Error ? error.message : undefined;
+ return Object.values(REVIEW_BLOCKERS).find((blocker) => blocker === message);
+};
+
/** Called under the verify run's task-drive claim, before completing a Goal task. */
export const reviewGoalDelivery = async (
db: LobeChatDatabase,
@@ -29,18 +48,25 @@ export const reviewGoalDelivery = async (
status: 'passed',
};
try {
- if (!run?.acceptanceId) throw new Error('Goal delivery has no Acceptance');
+ if (!run?.acceptanceId) throw new Error(REVIEW_BLOCKERS.noAcceptance);
const service = new AcceptanceService(db, userId, workspaceId);
const acceptance = await service.acceptanceModel.findById(run.acceptanceId);
- if (!acceptance) throw new Error('Goal Acceptance was not found');
+ if (!acceptance) throw new Error(REVIEW_BLOCKERS.acceptanceMissing);
const { results, runs } = await service.loadRounds(acceptance.id);
+ // An unconfirmed draft was never frozen, so its checks are not part of the
+ // contract being judged. It can sit behind an executed round β€” an abandoned
+ // 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 checks = buildAcceptanceCheckUnion(
- runs.map((round) => ({
- results: results.filter((result) => result.verifyRunId === round.id),
- run: round,
- })),
+ runs
+ .filter((round) => !isDraftVerifyRun(round))
+ .map((round) => ({
+ results: results.filter((result) => result.verifyRunId === round.id),
+ run: round,
+ })),
).filter((check) => check.required);
- if (!checks.length) throw new Error('Goal Acceptance has no required checks');
+ if (!checks.length) throw new Error(REVIEW_BLOCKERS.noRequiredChecks);
const evidenceModel = new VerifyEvidenceModel(db, userId, workspaceId);
const evidence = await Promise.all(
@@ -136,8 +162,14 @@ export const reviewGoalDelivery = async (
} catch (error) {
console.error('[goal-review] Acceptance review failed:', error);
review.status = 'errored';
- review.feedback =
- 'Automatic Acceptance review could not complete. Configure an available model on the Acceptance verifier agent and retry the review before advancing.';
+ // The reason has to travel: this string is what the escalation quotes back to
+ // the person who has to unblock the Goal. A single canned sentence sent every
+ // failure β€” a missing Acceptance link included β€” to look like an unconfigured
+ // review model, which is a different problem with a different fix.
+ const blocker = namedBlocker(error);
+ review.feedback = blocker
+ ? `Automatic Acceptance review could not complete: ${blocker}. Resolve the cause and retry the review before advancing.`
+ : 'Automatic Acceptance review could not complete (internal error); the server log holds the reason. Retry the review before advancing.';
}
if (run) {
// Preserve the task-drive claim and the run's existing policy/provenance.
diff --git a/apps/server/src/services/verify/lifecycle.ts b/apps/server/src/services/verify/lifecycle.ts
index 9fbf4fdd2e0..64ed9e36222 100644
--- a/apps/server/src/services/verify/lifecycle.ts
+++ b/apps/server/src/services/verify/lifecycle.ts
@@ -18,7 +18,7 @@ import { resolveVerifyModelConfig } from './modelConfig';
import { finalizeVerifyRun } from './settle';
import { VERIFY_ABANDONED_MS } from './staleness';
import { VerifyStatusService } from './statusService';
-import { resolveTaskAcceptance } from './taskAcceptance';
+import { attachTaskRunToAcceptance, resolveTaskAcceptance } from './taskAcceptance';
const log = debug('lobe-server:verify-lifecycle');
const MAX_TASK_DOCUMENT_CHARS = 80_000;
@@ -89,12 +89,12 @@ const executeVerifyLifecycle = async (
throwOnError = false,
): Promise<void> => {
try {
- const run = await new VerifyRunModel(db, userId, workspaceId).findByOperation(
+ const confirmedRun = await new VerifyRunModel(db, userId, workspaceId).findByOperation(
params.operationId,
);
// Opt-in gate: only runs with a confirmed plan.
- if (!run?.plan?.length || !run.planConfirmedAt) return;
+ if (!confirmedRun?.plan?.length || !confirmedRun.planConfirmedAt) return;
const op = await new AgentOperationModel(db, userId, workspaceId).findById(params.operationId);
if (!op) {
@@ -102,6 +102,33 @@ const executeVerifyLifecycle = async (
return;
}
+ // Resolved once here, before any of the branches below can return: it both
+ // binds this round to the Task's Acceptance (a builder that planned the round
+ // itself leaves it unattached) and pins which agent verifies. Non-task runs
+ // keep an undefined verifier β†’ builtin fallback.
+ //
+ // A throw is left to the outer catch on purpose. Only a resolved "this Task has
+ // no Acceptance" may fall back to the builtin verifier; swallowing a transient
+ // failure here would hand a Task that pins its own verifier to a different one
+ // and settle it on that verdict.
+ const resolvedAcceptance = op.taskId
+ ? await resolveTaskAcceptance(db, userId, op.taskId, workspaceId)
+ : undefined;
+ // Attaching can fold this round into a draft round of the acceptance, which
+ // deletes the row we read above, so the rest of the lifecycle follows the row
+ // the attach settled on.
+ const run = resolvedAcceptance
+ ? await attachTaskRunToAcceptance(
+ db,
+ userId,
+ { acceptanceId: resolvedAcceptance.acceptance.id, run: confirmedRun },
+ workspaceId,
+ )
+ : confirmedRun;
+ // A fold merges both plans onto the surviving row; anything else keeps the plan
+ // the opt-in gate above already accepted.
+ const plan = run.plan?.length ? run.plan : confirmedRun.plan;
+
// The builder now captures Acceptance evidence inside the main run. When it
// covered the whole plan, the post-run evidence turn has nothing left to
// collect β€” it mounts the evidence tool exclusively, so all it could add is
@@ -123,7 +150,7 @@ const executeVerifyLifecycle = async (
byCheckItem.set(row.checkItemId, types);
}
- const uncovered = run.plan.filter((item) => {
+ const uncovered = plan.filter((item) => {
if (item.required === false) return false;
const captured = byCheckItem.get(item.id);
if (!captured?.size) return true;
@@ -166,7 +193,7 @@ const executeVerifyLifecycle = async (
db,
deliverable: params.deliverable,
operation: op,
- plan: run.plan,
+ plan,
userId,
workspaceId,
});
@@ -177,7 +204,7 @@ const executeVerifyLifecycle = async (
deliverable: params.deliverable,
goal: params.goal,
operation: op,
- plan: run.plan,
+ plan,
userId,
workspaceId,
});
@@ -206,13 +233,7 @@ const executeVerifyLifecycle = async (
return;
}
- // Task-bound runs may pin which agent verifies through its Acceptance policy.
- // Non-task runs leave it undefined β†’ builtin fallback.
- let verifierAgentId: string | undefined;
- if (op.taskId) {
- const resolvedAcceptance = await resolveTaskAcceptance(db, userId, op.taskId, workspaceId);
- verifierAgentId = resolvedAcceptance?.config.verifierAgentId ?? undefined;
- }
+ const verifierAgentId = resolvedAcceptance?.config.verifierAgentId ?? undefined;
const modelConfig = await resolveVerifyModelConfig(
db,
diff --git a/apps/server/src/services/verify/planInstantiation.ts b/apps/server/src/services/verify/planInstantiation.ts
index 11bb7d90523..f1727737fc5 100644
--- a/apps/server/src/services/verify/planInstantiation.ts
+++ b/apps/server/src/services/verify/planInstantiation.ts
@@ -8,7 +8,7 @@ import type { LobeChatDatabase } from '@/database/type';
import { AcceptanceService, buildAcceptanceCheckUnion } from './acceptanceService';
import { resolveVerifyModelConfig } from './modelConfig';
import { VerifyPlanGeneratorService } from './planGenerator';
-import { resolveTaskAcceptance } from './taskAcceptance';
+import { attachTaskRunToAcceptance, resolveTaskAcceptance } from './taskAcceptance';
const log = debug('lobe-server:verify-plan-instantiation');
@@ -70,7 +70,24 @@ export const instantiateVerifyPlanOnStart = async (
const runModel = new VerifyRunModel(db, userId, workspaceId);
const existing = await runModel.findByOperation(params.operationId);
// Idempotent: a plan already exists for this run (re-fire, or agent/UI-built).
- if (existing?.plan?.length) return;
+ if (existing?.plan?.length) {
+ // An agent/UI-built plan never passed through the attach at the end of this
+ // function, so the round would stay orphaned from the Task's Acceptance β€”
+ // invisible to the task surface and unreadable by the Goal review.
+ //
+ // Only once it is confirmed, though. An unconfirmed plan is not a round yet,
+ // and binding it would leave a draft the next attempt folds into. The
+ // completion lifecycle binds the round anyway once the plan is confirmed.
+ if (existing.planConfirmedAt) {
+ await attachTaskRunToAcceptance(
+ db,
+ userId,
+ { acceptanceId: acceptance.id, run: existing },
+ workspaceId,
+ );
+ }
+ return;
+ }
const goal = task?.instruction ?? task?.name ?? '';
diff --git a/apps/server/src/services/verify/settle.ts b/apps/server/src/services/verify/settle.ts
index fdd126f9f68..4ae89dddfcf 100644
--- a/apps/server/src/services/verify/settle.ts
+++ b/apps/server/src/services/verify/settle.ts
@@ -19,6 +19,7 @@ import { reviewGoalDelivery } from './goalReview';
import { maybeAutoRepair } from './repairService';
import { VerifyReporterService } from './reporter';
import { VerifyStatusService } from './statusService';
+import { attachTaskRunToAcceptance, resolveTaskAcceptance } from './taskAcceptance';
const log = debug('lobe-server:verify-settle');
@@ -91,14 +92,35 @@ export const driveTaskFromVerify = async (
// Only act on a terminally settled run (skip pending / verifying / repairing).
if (run?.status !== 'passed' && run?.status !== 'failed' && run?.status !== 'errored') return;
if ((run.metadata as { taskDrivenAt?: string } | null)?.taskDrivenAt) return; // already drove
+ const operationModel = new AgentOperationModel(db, userId, workspaceId);
+ const op = await operationModel.findById(operationId);
+ const taskOperation = await resolveTaskOperation(operationModel, operationId);
+
+ // Last defence before the review: a round the builder planned itself can still
+ // arrive here unattached, because the CLI-driven verify path never passes
+ // through the completion lifecycle. The review reaches a delivery only through
+ // its Acceptance, and a missing link reads as "no Acceptance" β€” an error with
+ // no recovery branch, which parks a passing delivery on a person.
+ //
+ // Bound BEFORE the drive claim, and a failed resolution is not swallowed: it
+ // leaves through the outer catch with the claim unstamped, so a later finalizer
+ // retries instead of reviewing an unattached round into that same human gate.
+ if (op && taskOperation?.taskId && run.status === 'passed' && !run.acceptanceId) {
+ const resolved = await resolveTaskAcceptance(db, userId, taskOperation.taskId, workspaceId);
+ if (resolved)
+ await attachTaskRunToAcceptance(
+ db,
+ userId,
+ { acceptanceId: resolved.acceptance.id, run },
+ workspaceId,
+ );
+ }
+
// Cheap read above, authoritative claim here: concurrent verifier
// callbacks would otherwise both pass the read and both act β€” spawning two
// rounds, or one spawning while the other pauses the task it just started.
if (!(await runModel.claimTaskDrive(run.id))) return;
- const operationModel = new AgentOperationModel(db, userId, workspaceId);
- const op = await operationModel.findById(operationId);
- const taskOperation = await resolveTaskOperation(operationModel, operationId);
if (!op || !taskOperation?.taskId) return; // not a task-bound run β€” nothing to drive
const taskModel = new TaskModel(db, userId, workspaceId);
diff --git a/apps/server/src/services/verify/taskAcceptance.ts b/apps/server/src/services/verify/taskAcceptance.ts
index 300cdc9b757..08141ed347f 100644
--- a/apps/server/src/services/verify/taskAcceptance.ts
+++ b/apps/server/src/services/verify/taskAcceptance.ts
@@ -1,10 +1,15 @@
import type { AcceptanceConfig, TaskVerifyConfig } from '@lobechat/types';
+import debug from 'debug';
import { AcceptanceModel } from '@/database/models/acceptance';
import { TaskModel } from '@/database/models/task';
-import type { AcceptanceItem } from '@/database/schemas/verify';
+import type { AcceptanceItem, VerifyRunItem } from '@/database/schemas/verify';
import type { LobeChatDatabase } from '@/database/type';
+import { AcceptanceService } from './acceptanceService';
+
+const log = debug('lobe-server:verify-task-acceptance');
+
export interface ResolvedTaskAcceptance {
acceptance: AcceptanceItem;
config: AcceptanceConfig;
@@ -98,3 +103,52 @@ export const resolveTaskAcceptance = async (
requirement: acceptance.requirement ?? undefined,
};
};
+
+/**
+ * Bind a task-bound verification round to the Acceptance that owns the Task's
+ * completion contract.
+ *
+ * `instantiateVerifyPlanOnStart` attaches the plan it creates itself, but a builder
+ * that authors its own plan through the CLI (`verify.generateDraftPlan` β†’
+ * `verify.confirmPlan`) writes a round with no acceptance. That round still verifies
+ * and still passes, and then the Goal's Acceptance review β€” which can only reach the
+ * delivery through its Acceptance β€” errors with "no Acceptance". That failure class
+ * has no recovery branch, so a delivery that met every criterion ends up parked on a
+ * human decision gate.
+ *
+ * Idempotent and best-effort: a round that already belongs to an acceptance is left
+ * alone, and a refusal (already accepted / closed aggregate) must never break verify.
+ *
+ * Returns the row the round now lives in, which the caller must keep using: attaching
+ * onto an acceptance whose newest round is still a draft FOLDS this run into that
+ * draft and deletes the source row, moving its operation id across. A caller that
+ * kept the id it came in with would go on claiming and reading a row that no longer
+ * exists.
+ */
+export const attachTaskRunToAcceptance = async <
+ T extends Pick<VerifyRunItem, 'acceptanceId' | 'id'>,
+>(
+ db: LobeChatDatabase,
+ userId: string,
+ params: { acceptanceId: string; run: T },
+ workspaceId?: string,
+): Promise<T | VerifyRunItem> => {
+ if (params.run.acceptanceId) return params.run;
+
+ try {
+ const attached = await new AcceptanceService(db, userId, workspaceId).attachPolicyRun(
+ params.run.id,
+ params.acceptanceId,
+ );
+ log('attached run %s to task acceptance %s', params.run.id, params.acceptanceId);
+ return attached;
+ } catch (error) {
+ log(
+ 'could not attach run %s to acceptance %s (non-fatal): %O',
+ params.run.id,
+ params.acceptanceId,
+ error,
+ );
+ return params.run;
+ }
+};
diff --git a/packages/database/src/models/__tests__/verifyRun.test.ts b/packages/database/src/models/__tests__/verifyRun.test.ts
index eefb9bbb07f..e2d826a689a 100644
--- a/packages/database/src/models/__tests__/verifyRun.test.ts
+++ b/packages/database/src/models/__tests__/verifyRun.test.ts
@@ -288,6 +288,54 @@ describe('VerifyRunModel.foldIntoRound', () => {
expect(await model().listByAcceptance(acceptance.id)).toHaveLength(1);
});
+ /**
+ * Regression: the survivor was always written with a null status. Folding a live
+ * builder round into a leftover draft therefore produced a row no claim can move
+ * β€” `claimEvidenceCollection` wants `planned`, `claimVerifying` wants `planned`
+ * or `collecting_evidence` β€” so completion returned without collecting evidence
+ * or judging, and the Task was stranded.
+ */
+ it('keeps a live round claimable after folding it into a draft', async () => {
+ const { draft } = await draftRound();
+ const incoming = await model().create({
+ plan: [item('case-1')],
+ status: 'planned',
+ title: 'builder run',
+ });
+ await model().confirmPlan(incoming.id);
+
+ const folded = await model().foldIntoRound(incoming.id, draft.id);
+
+ expect(folded.status).toBe('planned');
+ expect(await model().claimEvidenceCollection(folded.id)).toBe(true);
+ });
+
+ /**
+ * Regression: the survivor kept the draft's operation. A draft left behind by an
+ * earlier attempt therefore swallowed the next attempt's row, and that attempt
+ * was no longer discoverable by its own operation β€” its verification stopped.
+ */
+ it("hands the survivor to the incoming run's operation", async () => {
+ const { draft } = await draftRound();
+ await new AgentOperationModel(serverDB, userId).recordStart({ operationId: 'fold-stale-op' });
+ await new AgentOperationModel(serverDB, userId).recordStart({ operationId: 'fold-live-op' });
+ await serverDB
+ .update(verifyRuns)
+ .set({ operationId: 'fold-stale-op' })
+ .where(eq(verifyRuns.id, draft.id));
+ const incoming = await model().create({
+ operationId: 'fold-live-op',
+ plan: [item('case-1')],
+ status: 'planned',
+ title: 'next attempt',
+ });
+
+ const folded = await model().foldIntoRound(incoming.id, draft.id);
+
+ expect(folded.operationId).toBe('fold-live-op');
+ expect((await model().findByOperation('fold-live-op'))?.id).toBe(draft.id);
+ });
+
it('refuses to fold into a round that already executed or a run already chained', async () => {
const { acceptance, draft } = await draftRound();
await model().confirmPlan(draft.id);
diff --git a/packages/database/src/models/verifyRun.ts b/packages/database/src/models/verifyRun.ts
index 1b2d35150cf..cb40d3e324b 100644
--- a/packages/database/src/models/verifyRun.ts
+++ b/packages/database/src/models/verifyRun.ts
@@ -364,13 +364,21 @@ export class VerifyRunModel {
context: target.context ?? source.context,
goal: target.goal ?? source.goal,
metadata: { ...target.metadata, ...source.metadata },
- operationId: target.operationId ?? source.operationId,
+ // The incoming run is the live work, and its operation is what the
+ // lifecycle keys on (`findByOperation`). Keeping a stale draft's
+ // operation instead would orphan the attempt that is actually running.
+ operationId: source.operationId ?? target.operationId,
plan,
planConfirmedAt: new Date(),
scenario: target.scenario ?? source.scenario,
source: source.source ?? target.source,
- // Ingested rounds carry no rollup status: the report settles them.
- status: null,
+ // The survivor takes over the source's identity, so it takes over its
+ // pipeline status too. An ingested round carries none and the report
+ // settles it, which is what nulls the draft's own `planned` here. A LIVE
+ // round folded mid-flight keeps its status instead: `claimEvidenceCollection`
+ // and `claimVerifying` only move a run that still has one, so clearing it
+ // would strand the run β€” and its Task β€” with nothing able to judge it.
+ status: source.status,
})
.where(eq(verifyRuns.id, targetRunId))
.returning();