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.

9.9 KB
Raw Blame
import debug from 'debug';

import { AcceptanceReviewModel } from '@/database/models/acceptanceReview';
import { GoalModel } from '@/database/models/goal';
import { TaskModel } from '@/database/models/task';
import { VerifyRunModel } from '@/database/models/verifyRun';
import type { LobeChatDatabase } from '@/database/type';
import { buildReviewPlanItems } from '@/server/services/acceptanceReview/reviewPlan';
import { reviewIdOfTask } from '@/server/services/acceptanceReview/roundContext';

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');

export interface InstantiateVerifyPlanParams {
  operationId: string;
  taskId: string;
}

/**
 * Auto-instantiate + auto-confirm a verify plan for a task-bound operation at run
 * start, so the completion-time gate (`runVerifyOnCompletion`) actually fires.
 *
 * Without this, a task's Acceptance policy (rubric / criteria) is never turned
 * into a plan, so verify silently no-ops. We resolve the Task's Acceptance and
 * materialize the rubric + ad-hoc criteria into a plan (no AI generation there
 * β€” the task already picked its criteria), and confirm it immediately (task
 * scenario doesn't show a "confirm plan" step). Only the undecomposed path
 * spends an AI call: the acceptance requirement is split into named criteria so
 * the checklist shows distinguishable items, with the single holistic check as
 * the fallback when generation fails.
 *
 * Fire-and-forget + idempotent: never throws (verify must not affect the run),
 * and skips when a plan already exists (recordStart can re-fire).
 */
export const instantiateVerifyPlanOnStart = async (
  db: LobeChatDatabase,
  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);

    const task = await taskModel.findById(params.taskId);
    // A recurring task (schedule / heartbeat) is a loop of ticks, not a
    // delivery: a single tick has no acceptance contract, and a failed
    // acceptance would pause the task β€” permanently disarming its schedule,
    // since the cron query never picks `paused` tasks up again. Verify stays
    // off for automation tasks even when they inherit an Acceptance policy.
    if (task?.automationMode) return;

    const resolvedAcceptance = await resolveTaskAcceptance(db, userId, params.taskId, workspaceId);
    if (!resolvedAcceptance) return;
    const { acceptance, config: verifyConfig, requirement } = resolvedAcceptance;

    // Opt-in to verify, then pick the plan shape:
    //  - rubric / ad-hoc criteria  β†’ decomposed multi-item plan (existing path)
    //  - else explicitly enabled OR a one-sentence acceptance requirement set
    //    β†’ coarse single holistic agent check
    //  - no signal at all          β†’ verify stays off
    if (verifyConfig.enabled === false) return;
    const hasCriteria = Boolean(
      verifyConfig.verifyRubricId || verifyConfig.verifyCriteriaIds?.length,
    );
    const holistic =
      !hasCriteria && (verifyConfig.enabled === true || Boolean(requirement?.trim()));
    if (!hasCriteria && !holistic) return;

    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) {
      // 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 reviewId = reviewIdOfTask(task?.config);
    if (reviewId) {
      const marks = await new AcceptanceReviewModel(db).listMarks(reviewId);
      const service = new AcceptanceService(db, userId, workspaceId);
      const { results, runs } = await service.loadRounds(acceptance.id);
      const previous = new Map(
        buildAcceptanceCheckUnion(
          runs.map((run) => ({
            results: results.filter((result) => result.verifyRunId === run.id),
            run,
          })),
        ).map((check) => [
          check.planItem?.id ?? check.id,
          { state: check.state, userDecision: check.result?.userDecision ?? null },
        ]),
      );
      const items = buildReviewPlanItems(marks, previous);
      if (!items.length) return;
      const reviewRun = await runModel.ensureForOperation(params.operationId);
      await runModel.setPlan(reviewRun.id, items);
      await runModel.confirmPlan(reviewRun.id);
      await service.attachPolicyRun(reviewRun.id, acceptance.id);
      return;
    }

    const goal = task?.instruction ?? task?.name ?? '';

    // Goal retries re-verify the same acceptance checks, including supplementary
    // checks submitted with the delivery. Generating new ids would leave the
    // rejected evidence in the union forever instead of superseding it.
    if (holistic && (await new GoalModel(db, userId, workspaceId).findByGraphTask(params.taskId))) {
      const service = new AcceptanceService(db, userId, workspaceId);
      const { results, runs } = await service.loadRounds(acceptance.id);
      const previousPlan = buildAcceptanceCheckUnion(
        runs.map((run) => ({
          results: results.filter((result) => result.verifyRunId === run.id),
          run,
        })),
      ).flatMap((check) => (check.planItem ? [{ ...check.planItem, id: check.id }] : []));
      if (previousPlan.length) {
        const retry = await runModel.ensureForOperation(params.operationId);
        await runModel.setPlan(retry.id, previousPlan);
        if (typeof verifyConfig.maxIterations === 'number') {
          await runModel.setMetadata(retry.id, { maxRepairRounds: verifyConfig.maxIterations });
        }
        await runModel.confirmPlan(retry.id);
        await service.attachPolicyRun(retry.id, acceptance.id);
        return;
      }
    }

    const planGenerator = new VerifyPlanGeneratorService(db, userId, workspaceId);
    // Undecomposed acceptance (goal-dispatched Task, one-sentence requirement):
    // spend one generation call splitting the requirement into named criteria,
    // so the checklist reads as distinguishable items instead of one generic
    // "Task delivery acceptance" row. The split runs on the pinned plan model
    // (VERIFY_PLAN_MODEL_CONFIG), not the verifier agent's chat model.
    await planGenerator.generateDraftPlan({
      // Ground the generated criteria in the acceptance text, not just the title.
      context: requirement,
      // Configured rubric/criteria ARE the plan β€” no AI proposal on that path.
      enableAiGeneration: holistic,
      goal,
      // Still fall back to the single agent-type holistic check when the
      // generation fails or returns nothing, so verify runs either way.
      holisticFallback: holistic,
      operationId: params.operationId,
      requirement,
      verifyCriteriaIds: verifyConfig.verifyCriteriaIds,
      verifyRubricId: verifyConfig.verifyRubricId,
    });

    // generateDraftPlan only sets the (draft) plan; the task scenario auto-confirms
    // so the completion gate treats it as ready instead of a pending draft.
    const run = await runModel.findByOperation(params.operationId);
    if (run?.plan?.length) {
      // Carry the Acceptance repair/re-run cap onto
      // the run so auto-repair honors it. Without this the repair path falls back
      // to the source rubric's config or the default, dropping the task cap for
      // ad-hoc-criteria or per-task-override tasks.
      if (typeof verifyConfig.maxIterations === 'number') {
        await runModel.setMetadata(run.id, { maxRepairRounds: verifyConfig.maxIterations });
      }
      await runModel.confirmPlan(run.id);

      // A task verification round belongs to its business-level Acceptance from
      // the moment the plan is confirmed. This lets the task surface show live
      // planned/verifying/repairing progress instead of waiting for an external
      // ingest command to create the aggregate after verification has finished.
      const acceptanceService = new AcceptanceService(db, userId, workspaceId);
      await acceptanceService.attachPolicyRun(run.id, acceptance.id);

      log(
        'instantiated + confirmed verify plan for op %s (%d items), acceptance %s',
        params.operationId,
        run.plan.length,
        acceptance.id,
      );
    }
  } catch (error) {
    log('instantiateVerifyPlanOnStart failed for op %s (non-fatal): %O', params.operationId, error);
  }
};