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.

15.5 KB
Raw Blame
import { randomUUID } from 'node:crypto';

import { TRACING_SCENARIOS, VERIFY_INSTRUCTION_FILE_TYPE } from '@lobechat/const';
import { HOLISTIC_CHECK_TITLE, isProgrammaticTestCheck } from '@lobechat/const/verify';
import type { TracingOptions } from '@lobechat/llm-generation-tracing';
import {
  chainVerifyPlan,
  GENERATED_CRITERIA_JSON_SCHEMA,
  VERIFY_PLAN_PROMPT_VERSION,
} from '@lobechat/prompts';
import type { RequiredEvidenceSpec, VerifyCheckItem } from '@lobechat/types';
import { RequestTrigger } from '@lobechat/types';
import debug from 'debug';

import { DocumentModel } from '@/database/models/document';
import { VerifyCriterionModel } from '@/database/models/verifyCriterion';
import { VerifyRubricModel } from '@/database/models/verifyRubric';
import { VerifyRunModel } from '@/database/models/verifyRun';
import type { VerifyCriterionItem } from '@/database/schemas/verify';
import type { LobeChatDatabase } from '@/database/type';
import { AiGenerationService } from '@/server/services/aiGeneration';

import { VERIFY_PLAN_MODEL_CONFIG } from './modelConfig';
import { resolveVerifyResponseLanguage } from './responseLanguage';
import { RawGeneratedCriteriaSchema } from './schema';

const log = debug('lobe-server:verify-plan-generator');

const DEFAULT_MAX_AI_CRITERIA = 4;

export interface GeneratePlanParams {
  /** Optional run context appended to the AI prompt (agent role, repo, constraints). */
  context?: string;
  /** Ask the LLM to propose additional criteria beyond the mounted ones. */
  enableAiGeneration?: boolean;
  /** The user's task / instruction text the run must satisfy. */
  goal: string;
  /**
   * When the run opted into verify but produced no decomposed criteria, synthesize
   * a single agent-type holistic check (the coarse "one broad agent verify"
   * default) instead of leaving an empty plan (→ verify no-op).
   */
  holisticFallback?: boolean;
  maxAiCriteria?: number;
  operationId: string;
  /** One-sentence acceptance the holistic check verifies against (falls back to `goal`). */
  requirement?: string;
  /** Ad-hoc criteria mounted on the agent (`agencyConfig.verifyCriteriaIds`). */
  verifyCriteriaIds?: string[];
  /** Reusable rubric mounted on the agent (`agencyConfig.verifyRubricId`). */
  verifyRubricId?: string | null;
}

/** One check draft, fully specified by its author (AI generation or user editing). */
export interface CriterionDraft {
  /** One-sentence summary; stored on the `verify_criteria.description` column. */
  description?: string;
  /**
   * Reuse an existing instruction document instead of creating one from
   * `instruction`. Set when re-persisting a hydrated criterion so its detailed
   * rubric (the doc body) is preserved rather than dropped to null.
   */
  documentId?: string | null;
  /** The detailed judging rubric; stored as the linked document's content. */
  instruction?: string;
  onFail?: VerifyCheckItem['onFail'];
  required?: boolean;
  requiredEvidence?: RequiredEvidenceSpec[];
  title: string;
  /** Verifier knobs (e.g. `requiredEvidence`) — attached when the user adds them. */
  verifierConfig?: Record<string, unknown>;
  verifierType?: VerifyCheckItem['verifierType'];
}

/**
 * Synthesize a single `agent`-type holistic check from the task's acceptance
 * requirement (or its goal). The agent verifier investigates the whole
 * deliverable and submits one verdict — the coarse "one broad agent verify"
 * default for tasks that opted into verify without decomposing into criteria
 * No `requiredEvidence` hard gate: the agent self-captures, so the
 * structural gate never marks it uncertain for "missing evidence".
 */
const buildHolisticAgentItem = (requirement?: string, goal?: string): VerifyCheckItem => {
  const acceptance = requirement?.trim() || goal?.trim() || 'The deliverable fulfills the task.';
  return {
    description: acceptance,
    id: randomUUID(),
    index: 0,
    // Delegate the fail decision to the task bridge (pass→completed / fail→brief)
    // rather than the operation-level auto-repair loop.
    onFail: 'manual',
    required: true,
    title: HOLISTIC_CHECK_TITLE,
    verifierConfig: {},
    verifierType: 'agent',
  };
};

/**
 * Drop AI-proposed criteria that are really the repo's own test / lint gates.
 *
 * The prompt already forbids them, but a model asked to verify a code change
 * reaches for "unit tests pass" reliably enough that the acceptance page fills
 * with rows nobody can act on. Applied only to the AI-generated criteria: they
 * are complementary by construction, and `generateDraftPlan` still falls back
 * to the holistic check if the filter empties the plan.
 */
const withoutProgrammaticTests = <T extends { description?: string; title: string }>(
  criteria: T[],
): T[] => criteria.filter((c) => !isProgrammaticTestCheck(c.title, c.description));

const criterionToCheckItem = (
  criterion: VerifyCriterionItem,
  index: number,
  sourceRubricId: string | null,
): VerifyCheckItem => ({
  description: criterion.description ?? undefined,
  documentId: criterion.documentId ?? undefined,
  // A criterion is the stable logical acceptance check. Reuse its id for every
  // run snapshot so independent task re-runs converge onto one Acceptance row;
  // the verify run still scopes each immutable snapshot and result.
  id: criterion.id,
  index,
  onFail: criterion.onFail,
  required: criterion.required,
  sourceCriterionId: criterion.id,
  definition: criterion.definition ?? undefined,
  sourceRubricId,
  title: criterion.title,
  verifierConfig: (criterion.verifierConfig as Record<string, unknown>) ?? {},
  verifierType: criterion.verifierType,
});

export class VerifyPlanGeneratorService {
  private readonly db: LobeChatDatabase;
  private readonly userId: string;
  private readonly workspaceId?: string;
  private readonly criterionModel: VerifyCriterionModel;
  private readonly rubricModel: VerifyRubricModel;
  private readonly runModel: VerifyRunModel;
  private readonly documentModel: DocumentModel;
  /**
   * Visibility of the agent that triggered this plan (only set when invoked
   * from a tool runtime). Threaded into every instruction-document create so
   * private-agent verify criteria stay in the caller's private Pages bucket
   * instead of leaking to the workspace.
   */
  private readonly callerAgentVisibility?: 'private' | 'public' | null;

  constructor(
    db: LobeChatDatabase,
    userId: string,
    workspaceId?: string,
    callerAgentVisibility?: 'private' | 'public' | null,
  ) {
    this.db = db;
    this.userId = userId;
    this.workspaceId = workspaceId;
    this.callerAgentVisibility = callerAgentVisibility;
    this.criterionModel = new VerifyCriterionModel(db, userId, workspaceId);
    this.rubricModel = new VerifyRubricModel(db, userId, workspaceId);
    this.runModel = new VerifyRunModel(db, userId, workspaceId);
    this.documentModel = new DocumentModel(db, userId, workspaceId, callerAgentVisibility);
  }

  private get inheritedVisibility(): { visibility: 'private' | 'public' } | Record<string, never> {
    return this.callerAgentVisibility === 'private' || this.callerAgentVisibility === 'public'
      ? { visibility: this.callerAgentVisibility }
      : {};
  }

  /** Draft criteria for the generic task verification configuration surface. */
  async generateCriteria(params: {
    context?: string;
    goal: string;
    maxCriteria?: number;
  }): Promise<CriterionDraft[]> {
    const maxCriteria = params.maxCriteria ?? DEFAULT_MAX_AI_CRITERIA;
    const raw = await new AiGenerationService(
      this.db,
      this.userId,
      this.workspaceId,
    ).generateObject(
      {
        ...chainVerifyPlan({
          context: params.context,
          goal: params.goal,
          language: await resolveVerifyResponseLanguage(this.db, this.userId),
          maxCriteria,
        }),
        ...VERIFY_PLAN_MODEL_CONFIG,
        schema: GENERATED_CRITERIA_JSON_SCHEMA,
        thinking: { type: 'disabled' },
      },
      {
        metadata: { trigger: RequestTrigger.Verify },
        tracing: {
          promptVersion: VERIFY_PLAN_PROMPT_VERSION,
          scenario: TRACING_SCENARIOS.VerifyPlanGen,
          schemaName: GENERATED_CRITERIA_JSON_SCHEMA.name,
        } satisfies TracingOptions,
      },
    );

    const parsed = RawGeneratedCriteriaSchema.safeParse(raw);
    if (!parsed.success) {
      log('config criteria-gen output did not match schema: %O', parsed.error.flatten());
      return [];
    }

    return withoutProgrammaticTests(parsed.data.criteria.slice(0, maxCriteria)).map(
      (criterion) => ({
        description: criterion.description,
        instruction: criterion.instruction,
        onFail: criterion.onFail ?? 'manual',
        requiredEvidence: criterion.requiredEvidence,
        required: criterion.required ?? true,
        title: criterion.title,
        verifierType: criterion.verifierType,
      }),
    );
  }

  /**
   * Persist a list of (possibly user-edited) drafts as standalone `verify_criteria`
   * rows and return their ids in order — the "ad-hoc criteria" a task mounts via
   * `TaskVerifyConfig.verifyCriteriaIds`. The detailed instruction (if any) lands
   * in a linked document, mirroring the rubric path.
   */
  async createCriteriaFromDrafts(drafts: CriterionDraft[]): Promise<string[]> {
    const ids: string[] = [];
    for (const [index, draft] of drafts.entries()) {
      // Reuse the existing instruction doc when re-persisting a hydrated criterion;
      // only create a fresh doc for a genuinely new draft that carries inline text.
      let documentId: string | null = draft.documentId ?? null;
      if (!documentId && draft.instruction) {
        const doc = await this.documentModel.create({
          content: draft.instruction,
          fileType: VERIFY_INSTRUCTION_FILE_TYPE,
          source: `verify-criterion:adhoc:${index}`,
          sourceType: 'agent',
          title: draft.title,
          totalCharCount: draft.instruction.length,
          totalLineCount: draft.instruction.split('\n').length,
          ...this.inheritedVisibility,
        });
        documentId = doc.id;
      }
      const criterion = await this.criterionModel.create({
        description: draft.description,
        documentId,
        onFail: draft.onFail ?? 'manual',
        required: draft.required ?? true,
        title: draft.title,
        verifierConfig: {
          ...draft.verifierConfig,
          ...(draft.requiredEvidence ? { requiredEvidence: draft.requiredEvidence } : {}),
        },
        verifierType: draft.verifierType ?? 'llm',
      });
      ids.push(criterion.id);
    }
    return ids;
  }

  /**
   * Build a draft check plan for a run: instantiate the mounted rubric + ad-hoc
   * criteria into frozen snapshot items, optionally appending AI-proposed
   * criteria, then persist it onto the operation (`verifyStatus` → 'planned').
   * Returns the plan items.
   */
  async generateDraftPlan(params: GeneratePlanParams): Promise<VerifyCheckItem[]> {
    const items: VerifyCheckItem[] = [];

    // 1. Instantiate the mounted rubric's criteria (in rubric order).
    if (params.verifyRubricId) {
      const rubricCriteria = await this.rubricModel.getCriteria(params.verifyRubricId);
      for (const c of rubricCriteria) {
        items.push(criterionToCheckItem(c, items.length, params.verifyRubricId));
      }
    }

    // 2. Instantiate ad-hoc criteria, skipping any already pulled in via the rubric.
    if (params.verifyCriteriaIds?.length) {
      const seen = new Set(items.map((i) => i.sourceCriterionId).filter(Boolean));
      const adHoc = await this.criterionModel.findByIds(params.verifyCriteriaIds);
      for (const c of adHoc) {
        if (seen.has(c.id)) continue;
        items.push(criterionToCheckItem(c, items.length, null));
      }
    }

    // 3. AI-generate complementary criteria (the "auto-create verify" path).
    if (params.enableAiGeneration) {
      try {
        const generated = await this.generateCriteriaWithAi({
          context: params.context,
          existingTitles: items.map((i) => i.title),
          goal: params.goal,
          maxCriteria: params.maxAiCriteria ?? DEFAULT_MAX_AI_CRITERIA,
          operationId: params.operationId,
        });
        for (const item of generated) {
          items.push({ ...item, index: items.length });
        }
      } catch (error) {
        // AI generation is best-effort — a failure must not block the run.
        log('AI criteria generation failed: %O', error);
      }
    }

    // 4. Holistic fallback: opted into verify but nothing decomposed into
    //    criteria — synthesize one agent-type check over the whole deliverable
    //    so verify actually runs (instead of an empty plan → no-op).
    if (items.length === 0 && params.holisticFallback) {
      items.push(buildHolisticAgentItem(params.requirement, params.goal));
      log('synthesized holistic agent check for op %s', params.operationId);
    }

    const run = await this.runModel.ensureForOperation(params.operationId, { goal: params.goal });
    await this.runModel.setPlan(run.id, items);
    log('generated draft plan for op %s with %d items', params.operationId, items.length);

    return items;
  }

  private async generateCriteriaWithAi(params: {
    context?: string;
    existingTitles: string[];
    goal: string;
    maxCriteria: number;
    operationId: string;
  }): Promise<VerifyCheckItem[]> {
    const chain = chainVerifyPlan({
      context: params.context,
      existingTitles: params.existingTitles,
      goal: params.goal,
      language: await resolveVerifyResponseLanguage(this.db, this.userId),
      maxCriteria: params.maxCriteria,
    });

    const ai = new AiGenerationService(this.db, this.userId, this.workspaceId);
    const raw = await ai.generateObject(
      {
        ...chain,
        ...VERIFY_PLAN_MODEL_CONFIG,
        schema: GENERATED_CRITERIA_JSON_SCHEMA,
        thinking: { type: 'disabled' },
      },
      {
        metadata: { trigger: RequestTrigger.Verify },
        tracing: {
          promptVersion: VERIFY_PLAN_PROMPT_VERSION,
          scenario: TRACING_SCENARIOS.VerifyPlanGen,
          schemaName: GENERATED_CRITERIA_JSON_SCHEMA.name,
        } satisfies TracingOptions,
      },
    );

    const parsed = RawGeneratedCriteriaSchema.safeParse(raw);
    if (!parsed.success) {
      log('AI plan-gen output did not match schema: %O', parsed.error.flatten());
      return [];
    }

    // Like the agent-authored path, the detailed instruction lives in a document
    // (the single source of truth) referenced by documentId — never inline.
    return Promise.all(
      withoutProgrammaticTests(parsed.data.criteria.slice(0, params.maxCriteria)).map(async (c) => {
        let documentId: string | null = null;
        if (c.instruction) {
          const doc = await this.documentModel.create({
            content: c.instruction,
            fileType: VERIFY_INSTRUCTION_FILE_TYPE,
            source: `verify-criterion:ai:${params.operationId}`,
            sourceType: 'agent',
            title: c.title,
            totalCharCount: c.instruction.length,
            totalLineCount: c.instruction.split('\n').length,
            ...this.inheritedVisibility,
          });
          documentId = doc.id;
        }
        return {
          description: c.description,
          documentId,
          id: randomUUID(),
          index: 0, // re-indexed by the caller
          onFail: c.onFail ?? 'manual',
          required: c.required ?? true,
          sourceCriterionId: null,
          sourceRubricId: null,
          title: c.title,
          verifierConfig: { requiredEvidence: c.requiredEvidence },
          verifierType: c.verifierType,
        };
      }),
    );
  }
}