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.

5.7 KB
Raw Blame
import { isCheckWaivedByDispute } from '@lobechat/const/verify';
import type { VerifyCheckItem, VerifyRunStatus } from '@lobechat/types';
import debug from 'debug';

import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';
import { VerifyRunModel } from '@/database/models/verifyRun';
import type { LobeChatDatabase } from '@/database/type';

import { AcceptanceService } from './acceptanceService';

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

/**
 * Service-layer chokepoint for the denormalized `verify_runs.status` rollup. MUST
 * be the only writer of that column (besides explicit repair / deliver
 * transitions) so the badge never drifts from the underlying results. Addresses
 * sessions by their bound Agent Run (`operationId`) for the agent pipeline.
 */
export class VerifyStatusService {
  private readonly db: LobeChatDatabase;
  private readonly runModel: VerifyRunModel;
  private readonly resultModel: VerifyCheckResultModel;
  private readonly userId: string;
  private readonly workspaceId?: string;

  constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
    this.db = db;
    this.userId = userId;
    this.workspaceId = workspaceId;
    this.runModel = new VerifyRunModel(db, userId, workspaceId);
    this.resultModel = new VerifyCheckResultModel(db, userId, workspaceId);
  }

  /**
   * Derive the rollup from the frozen plan + current results and persist it.
   * Returns the computed status. Gate logic only considers `required` items:
   * - any required result still pending/running β†’ `verifying`
   * - any required result failed β†’ `failed`
   * - else any required result errored (verifier couldn't run) β†’ `errored`
   * - otherwise β†’ `passed`
   * A genuine `failed` dominates an `errored` (the delivery has a real problem to
   * fix, so it should still gate + repair). A check waived by an upheld dispute
   * is skipped entirely. A required `skipped` result is an
   * execution gap and rolls up as `errored`; only optional checks may skip.
   */
  async recompute(operationId: string): Promise<VerifyRunStatus | null> {
    const run = await this.runModel.findByOperation(operationId);
    if (!run) return null;

    const plan = (run.plan ?? []) as VerifyCheckItem[];
    if (plan.length === 0) {
      // No plan β†’ nothing to verify. Leave as-is (unverified / skipped).
      return (run.status ?? null) as VerifyRunStatus | null;
    }
    if (!run.planConfirmedAt) return 'planned';

    const results = await this.resultModel.listByRun(run.id);
    const byItem = new Map(results.map((r) => [r.checkItemId, r]));

    const requiredItems = plan.filter((i) => i.required);

    let anyPending = false;
    let anyFailed = false;
    let anyErrored = false;
    for (const item of requiredItems) {
      const result = byItem.get(item.id);
      // A panel upheld the builder's dispute that this check is invalid: it no
      // longer gates the round, whatever the verifier said about it.
      if (result && isCheckWaivedByDispute(result.metadata)) continue;
      // A required item without a result yet is still pending.
      if (!result || result.status === 'pending' || result.status === 'running') {
        anyPending = true;
        continue;
      }
      if (result.status === 'failed' || result.verdict === 'failed') anyFailed = true;
      else if (result.status === 'errored' || result.status === 'skipped') anyErrored = true;
    }

    const status: VerifyRunStatus = anyPending
      ? 'verifying'
      : anyFailed
        ? 'failed'
        : anyErrored
          ? 'errored'
          : 'passed';

    if (status !== run.status) {
      await this.runModel.updateStatus(run.id, status);
      if (run.acceptanceId) {
        await new AcceptanceService(this.db, this.userId, this.workspaceId).recomputeStatus(
          run.acceptanceId,
        );
      }
      log('rollup op %s (run %s) β†’ %s', operationId, run.id, status);
    }

    return status;
  }

  /**
   * Claim the verification of an Agent Run and enter `verifying`, exactly once.
   *
   * This is the re-entrant form of {@link markVerifying}: the completion-time
   * gate uses it so a redelivered completion cannot start a second judge pass,
   * while an attempt that entered `verifying` and then died (its post-response
   * work stopped being scheduled) can still be picked up by a later one.
   *
   * @returns false when someone else holds the verification.
   */
  async claimVerifying(operationId: string, staleBefore: Date): Promise<boolean> {
    const run = await this.runModel.findByOperation(operationId);
    if (!run) return false;

    const claimed = await this.runModel.claimVerifying(run.id, staleBefore);
    if (claimed && run.acceptanceId) {
      await new AcceptanceService(this.db, this.userId, this.workspaceId).recomputeStatus(
        run.acceptanceId,
      );
    }
    return claimed;
  }

  /** Explicit transitions that aren't derivable from results alone. */
  async markVerifying(operationId: string) {
    await this.setStatus(operationId, 'verifying');
  }

  async markRepairing(operationId: string) {
    await this.setStatus(operationId, 'repairing');
  }

  async markDelivered(operationId: string) {
    await this.setStatus(operationId, 'delivered');
  }

  /** Resolve the session for an Agent Run and write its rollup status. */
  private async setStatus(operationId: string, status: VerifyRunStatus): Promise<void> {
    const run = await this.runModel.findByOperation(operationId);
    if (!run) {
      log('setStatus: no verify run for op %s, skipping %s', operationId, status);
      return;
    }
    await this.runModel.updateStatus(run.id, status);
    if (run.acceptanceId) {
      await new AcceptanceService(this.db, this.userId, this.workspaceId).recomputeStatus(
        run.acceptanceId,
      );
    }
  }
}