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.

10.7 KB
Raw Blame
import { DISPUTE_SETTLED_RUN_STATUSES } from '@lobechat/const/verify';
import { and, asc, desc, eq, inArray, isNull, sql } from 'drizzle-orm';

import type { NewVerifyCheckResult, VerifyCheckResultItem } from '../schemas/verify';
import { acceptances, verifyCheckResults, verifyRuns } from '../schemas/verify';
import type { LobeChatDatabase } from '../type';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';

export class VerifyCheckResultModel {
  private readonly db: LobeChatDatabase;
  private readonly userId: string;
  private readonly workspaceId?: string;

  constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
    this.db = db;
    this.userId = userId;
    this.workspaceId = workspaceId;
  }

  private ownership = () =>
    buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, verifyCheckResults);

  private runOwnership = () =>
    buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, verifyRuns);

  private assertRunOwned = async (verifyRunId: string): Promise<void> => {
    const [run] = await this.db
      .select({ id: verifyRuns.id })
      .from(verifyRuns)
      .where(and(eq(verifyRuns.id, verifyRunId), this.runOwnership()))
      .limit(1);

    if (!run) {
      throw new Error(`Verify run "${verifyRunId}" not found in the current workspace`);
    }
  };

  private sourceCriterion = async (verifyRunId: string | null | undefined, checkItemId: string) => {
    if (!verifyRunId) return null;
    const [run] = await this.db
      .select({ plan: verifyRuns.plan })
      .from(verifyRuns)
      .where(and(eq(verifyRuns.id, verifyRunId), this.runOwnership()));
    return run?.plan?.find((item) => item.id === checkItemId)?.sourceCriterionId ?? null;
  };

  create = async (params: Omit<NewVerifyCheckResult, 'userId' | 'workspaceId'>) => {
    if (typeof params.verifyRunId === 'string') await this.assertRunOwned(params.verifyRunId);

    params = {
      ...params,
      sourceCriterionId: await this.sourceCriterion(params.verifyRunId, params.checkItemId),
    };
    const [result] = await this.db
      .insert(verifyCheckResults)
      .values(buildWorkspacePayload({ userId: this.userId, workspaceId: this.workspaceId }, params))
      .returning();

    return result;
  };

  /** Batch-insert the initial `pending` rows when verify execution starts. */
  createMany = async (rows: Omit<NewVerifyCheckResult, 'userId' | 'workspaceId'>[]) => {
    if (rows.length === 0) return [];
    const verifyRunIds = [
      ...new Set(
        rows.map((r) => r.verifyRunId).filter((id): id is string => typeof id === 'string'),
      ),
    ];
    await Promise.all(verifyRunIds.map((verifyRunId) => this.assertRunOwned(verifyRunId)));

    rows = await Promise.all(
      rows.map(async (r) => ({
        ...r,
        sourceCriterionId: await this.sourceCriterion(r.verifyRunId, r.checkItemId),
      })),
    );
    return this.db
      .insert(verifyCheckResults)
      .values(
        rows.map((r) =>
          buildWorkspacePayload({ userId: this.userId, workspaceId: this.workspaceId }, r),
        ),
      )
      .returning();
  };

  /**
   * Insert-or-update a result by its stable `(verifyRunId, checkItemId)` key.
   * Used by the ingest path (e.g. agent-testing) which supplies a verdict for a
   * check directly rather than running a verifier. Idempotent — re-ingesting the
   * same check overwrites in place via the unique index.
   */
  upsertByCheckItem = async (
    params: Omit<NewVerifyCheckResult, 'userId' | 'workspaceId'> & {
      checkItemId: string;
      verifyRunId: string;
    },
  ): Promise<VerifyCheckResultItem> => {
    await this.assertRunOwned(params.verifyRunId);

    params = {
      ...params,
      sourceCriterionId: await this.sourceCriterion(params.verifyRunId, params.checkItemId),
    };
    const values = buildWorkspacePayload(
      { userId: this.userId, workspaceId: this.workspaceId },
      params,
    );
    // The conflict target and ownership keys identify the row, so they're excluded from the set.
    const { verifyRunId: _r, checkItemId: _c, userId: _u, workspaceId: _w, ...mutable } = values;

    const [row] = await this.db
      .insert(verifyCheckResults)
      .values(values)
      .onConflictDoUpdate({
        set: mutable,
        setWhere: this.ownership(),
        target: [verifyCheckResults.verifyRunId, verifyCheckResults.checkItemId],
      })
      .returning();

    if (!row) {
      throw new Error(
        `Verify check result "${params.checkItemId}" not found in the current workspace`,
      );
    }

    return row;
  };

  /**
   * Write a builder's dispute onto a result, but only while its round is still
   * open (not settled, no human decision, Acceptance not accepted or closed), no
   * ruling has been decided on it and no other arbitration holds it. Checked in
   * the same statement as the write, so a round that settles while a panel is
   * ruling refuses the late ruling. Only the `dispute` key is replaced, so
   * metadata written by a concurrent verifier survives.
   *
   * A claim is the dispute's `arbitratingSince` timestamp. `holder` lets the
   * claimant itself write the ruling; a claim older than `staleBefore` (an
   * arbitration that died) no longer blocks anyone.
   *
   * @returns the updated row, or undefined when the guard refused the write.
   */
  writeDisputeIfOpen = async (
    id: string,
    dispute: Record<string, unknown>,
    guard: { holder?: string; staleBefore: Date },
  ): Promise<VerifyCheckResultItem | undefined> => {
    const current = sql`${verifyCheckResults.metadata} -> 'dispute'`;
    const claimedAt = sql`(${current} ->> 'arbitratingSince')`;
    const [row] = await this.db
      .update(verifyCheckResults)
      .set({
        metadata: sql`jsonb_set(coalesce(${verifyCheckResults.metadata}, '{}'::jsonb), '{dispute}', ${JSON.stringify(dispute)}::jsonb)`,
      })
      .where(
        and(
          eq(verifyCheckResults.id, id),
          this.ownership(),
          sql`not (coalesce(${current} ->> 'kind', '') = 'invalid_criterion' and coalesce(${current} -> 'arbitration' ->> 'outcome', '') in ('upheld', 'overruled'))`,
          sql`exists (
            select 1 from ${verifyRuns}
            left join ${acceptances} on ${acceptances.id} = ${verifyRuns.acceptanceId}
            where ${verifyRuns.id} = ${verifyCheckResults.verifyRunId}
              and ${verifyRuns.userDecision} is null
              and coalesce(${verifyRuns.status}, '') not in (${sql.join(
                DISPUTE_SETTLED_RUN_STATUSES.map((status) => sql`${status}`),
                sql`, `,
              )})
              and coalesce(${acceptances.status}, '') not in ('accepted', 'closed')
          )`,
          // COALESCE, never `IS NULL`, on an extracted jsonb value: see jsonbNullTest.
          sql`(case when coalesce(${claimedAt}, '') = '' then true else ${claimedAt}::timestamptz < ${guard.staleBefore.toISOString()}::timestamptz end${
            guard.holder ? sql` or coalesce(${claimedAt}, '') = ${guard.holder}` : sql``
          })`,
        ),
      )
      .returning();
    return row;
  };

  listByCriterion = async (criterionId: string, limit = 50) => {
    return this.db
      .select()
      .from(verifyCheckResults)
      .where(and(eq(verifyCheckResults.sourceCriterionId, criterionId), this.ownership()))
      .orderBy(desc(verifyCheckResults.createdAt))
      .limit(Math.min(Math.max(limit, 1), 100));
  };

  findById = async (id: string) => {
    return this.db.query.verifyCheckResults.findFirst({
      where: and(eq(verifyCheckResults.id, id), this.ownership()),
    });
  };

  /** All results for one verification session, ordered by display index. */
  listByRun = async (verifyRunId: string): Promise<VerifyCheckResultItem[]> => {
    return this.db
      .select()
      .from(verifyCheckResults)
      .where(and(eq(verifyCheckResults.verifyRunId, verifyRunId), this.ownership()))
      .orderBy(asc(verifyCheckResults.checkItemIndex));
  };

  /**
   * All results across several verification rounds in one query — the
   * acceptance union reads a whole round chain, so it must not fan out into a
   * per-run query. Ordered by display index for stable downstream grouping.
   */
  listByRuns = async (verifyRunIds: string[]): Promise<VerifyCheckResultItem[]> => {
    if (verifyRunIds.length === 0) return [];
    return this.db
      .select()
      .from(verifyCheckResults)
      .where(and(inArray(verifyCheckResults.verifyRunId, verifyRunIds), this.ownership()))
      .orderBy(asc(verifyCheckResults.checkItemIndex));
  };

  update = async (id: string, value: Partial<Omit<VerifyCheckResultItem, 'id' | 'userId'>>) => {
    return this.db
      .update(verifyCheckResults)
      .set(value)
      .where(and(eq(verifyCheckResults.id, id), this.ownership()));
  };

  /**
   * Delete one result by id (ownership-scoped). Its evidence rows cascade via the
   * `verify_evidence.check_result_id` FK. Used by the re-ingest path to prune a
   * case that a later report round dropped, so a re-run stays a full replace
   * rather than accreting stale checks.
   */
  delete = async (id: string) => {
    return this.db
      .delete(verifyCheckResults)
      .where(and(eq(verifyCheckResults.id, id), this.ownership()));
  };

  /**
   * Update a result by its stable `(verifyRunId, checkItemId)` key rather than
   * the row id — used by the executor / batch judge which produces verdicts keyed
   * by check item id, never by array position.
   */
  updateByCheckItem = async (
    verifyRunId: string,
    checkItemId: string,
    value: Partial<Omit<VerifyCheckResultItem, 'id' | 'userId'>>,
  ) => {
    return this.db
      .update(verifyCheckResults)
      .set(value)
      .where(
        and(
          eq(verifyCheckResults.verifyRunId, verifyRunId),
          eq(verifyCheckResults.checkItemId, checkItemId),
          this.ownership(),
        ),
      );
  };

  /**
   * Late-bind the LLM tracing row onto already-written verdicts. The verdict is
   * persisted synchronously with `verifier_tracing_id = null`; the tracing row
   * lands asynchronously (best-effort, after the response), so the FK link is
   * backfilled only once that row exists. Idempotent — only fills `NULL`s and is
   * scoped to the items judged in this call (a batch shares one tracing id).
   */
  backfillTracingId = async (verifyRunId: string, checkItemIds: string[], tracingId: string) => {
    if (checkItemIds.length === 0) return;
    return this.db
      .update(verifyCheckResults)
      .set({ verifierTracingId: tracingId })
      .where(
        and(
          eq(verifyCheckResults.verifyRunId, verifyRunId),
          this.ownership(),
          inArray(verifyCheckResults.checkItemId, checkItemIds),
          isNull(verifyCheckResults.verifierTracingId),
        ),
      );
  };
}