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.

38.5 KB
Raw Blame
import type { VerifyCheckDefinition } from './acceptanceFlow';
import type { GoalReleaseGateDossier } from './goalRollout';
import type { RequiredEvidenceSpec } from './verify/evidence';

export * from './verify/evidence';
/**
 * Verify (delivery checker) domain types β€” the shared vocabulary, frozen-item
 * shape, Toulmin narrative, and rubric run-policy config. Kept here (not in the
 * DB schema) so every layer β€” schema, services, store, UI β€” depends on one
 * source of truth without reaching into the database package.
 *
 * The unions below are declared here, and their runtime counterparts (the `as
 * const` arrays a schema or a `<Select>` iterates) live in
 * `@lobechat/const/verify`. The duplication is deliberate: this package is
 * replaced by a hand-written stub inside the isolated desktop workspace, so a
 * runtime value exported from here is unreachable for members of that workspace
 * (`@lobehub/cli`), while `@lobechat/types` must stay dependency-free of
 * `@lobechat/const`. `packages/const/src/verify.test.ts` fails the type-check the
 * moment the two sides drift apart.
 */

/**
 * How a single criterion is judged.
 * - program: run a deterministic command / script
 * - agent:   spawn a sub agent_operations to investigate
 * - llm:     call generateObject and let an LLM judge produce a Toulmin verdict
 */
export type VerifierType = 'program' | 'agent' | 'llm';

/** What to do when a check item fails. */
export type VerifyOnFailStrategy = 'manual' | 'auto_repair';

/**
 * Lifecycle of a single check result.
 * - errored: the verifier could not run (infra / startup failure) β€” NOT a
 *   delivery judgment. Kept distinct from `failed` so a broken verifier never
 *   reads as a rejected delivery and never seeds an auto-repair round.
 */
export type VerifyCheckResultStatus =
  'pending' | 'running' | 'passed' | 'failed' | 'errored' | 'skipped';

/** Toulmin Claim β€” the verifier's judgement. */
export type VerifyVerdict = 'passed' | 'failed' | 'uncertain';

/** Human feedback on a result, feeding the data flywheel. */
export type VerifyUserDecision = 'accepted' | 'rejected' | 'overridden';

// ============================================
// Acceptance β€” business-level delivery acceptance aggregate
// ============================================

/**
 * The product object being accepted. Kept polymorphic so the acceptance aggregate
 * is not coupled to task-only workflows: a future run can accept a topic,
 * document, artifact, release, etc. without another schema reshape.
 */
export type AcceptanceSubjectType =
  'task' | 'topic' | 'document' | 'standalone' | 'goal_gate' | 'site';

export type CreatableAcceptanceSubjectType = Exclude<AcceptanceSubjectType, 'site'>;

/**
 * Business-level acceptance state. Check-level and run-level verdicts stay in the
 * verify vocabulary (`passed` / `failed`); the aggregate exposes the user's
 * outcome language (`accepted` / `rejected`). `closed` is a reversible archive
 * state for an acceptance that is no longer needed; unlike `accepted`, it does
 * not record a positive delivery decision.
 *
 * `delivered`: verification settled (passed OR failed) and the aggregate now
 * waits for the user's accept/reject β€” the human decision closes the lifecycle,
 * the verifier's verdict is only a recommendation either way.
 */
export type AcceptanceStatus =
  | 'pending'
  | 'planned'
  | 'verifying'
  | 'repairing'
  | 'delivered'
  | 'accepted'
  | 'closed'
  | 'rejected'
  | 'errored';

/**
 * AI-generated visualization for an acceptance report (`acceptances.visual_render`).
 * One jsonb bag (not a bare text column) so generation provenance and future
 * knobs (theme, assets) never need a migration.
 *
 * The `html` payload is model-produced β€” viewers MUST render it inside a
 * sandboxed iframe, never inject it into the host document.
 */
export interface AcceptanceVisualRender {
  generatedAt?: string;
  /** Producer of the visualization, e.g. a model id. */
  generatedBy?: string;
  /** Self-contained HTML document filled in by the AI. */
  html: string;
}

/**
 * Acceptance policy/config snapshot. This is the authoritative policy for the
 * subject's verification lifecycle; legacy task `config.verify` values are
 * migrated here on first read.
 */
/**
 * One user-authored acceptance criterion in a subject's standing checklist
 * (e.g. the topic acceptance tray). Every item is judged by the verify agent;
 * `method` is the optional "how to check" note.
 */
export interface AcceptanceChecklistItem {
  id: string;
  method?: string;
  name: string;
}

export interface AcceptanceConfig {
  /**
   * The subject's standing, user-editable acceptance checklist (topic tray).
   * Persisted here so it lives with the verify aggregate, not in client storage.
   */
  checklist?: AcceptanceChecklistItem[];
  enabled?: boolean;
  maxIterations?: number;
  verifierAgentId?: string;
  verifyCriteriaIds?: string[];
  verifyRubricId?: string;
}

/**
 * A file the user attached to their feedback (an uploaded/pasted screenshot),
 * resolved to a display URL. The stored form is a bare `fileId` on the decision
 * detail; this is the enriched view the acceptance page renders, produced by the
 * bundle read (which resolves the id to a signed URL as the aggregate's owner).
 */
export interface AcceptanceAttachment {
  id: string;
  /** Original file name, when known. */
  name?: string;
  /** Resolved (possibly signed) URL β€” null when the file no longer resolves. */
  url: string | null;
}

/**
 * User feedback addressed to a check GROUP (business category) rather than any
 * single check β€” the "this concern doesn't belong to a check I could reject"
 * channel. Stored on the round it judges ({@link VerifyRunDecisionDetail});
 * this is the derived view the acceptance page consumes, with `roundIndex`
 * read off that run, so the check-reject staleness rule (consumed once a
 * newer round lands) applies structurally.
 */
export interface AcceptanceGroupFeedback {
  /** Attachments backing the feedback, resolved to URLs by the bundle read. */
  attachments?: AcceptanceAttachment[];
  /** The group's category label ('' targets the uncategorized bucket). */
  category: string;
  comment: string;
  /** When the feedback was written (ISO 8601). */
  createdAt: string;
  /** Uploaded/pasted screenshots backing the feedback (FKs to files). */
  fileIds?: string[];
  /** The round the feedback was addressed to β€” its run's own round index. */
  roundIndex: number;
}

/** One group-scoped feedback entry as stored on a round's decision detail. */
export type VerifyRunGroupFeedbackEntry = Omit<AcceptanceGroupFeedback, 'roundIndex'>;

/** A presentation group of stable acceptance-union check IDs, independent of execution flows. */
export interface AcceptanceCheckGroup {
  checkItemIds: string[];
  title: string;
}

/** Generic acceptance extension bag for cross-subject state we have not modeled yet. */
export interface AcceptanceMetadata {
  [key: string]: unknown;
  /** Current checklist organization; frozen plans, results and reviews keep their original IDs. */
  checkGrouping?: { groups: AcceptanceCheckGroup[]; version: number };
  /**
   * Pull requests linked by hand (`lh acceptance link-pr`, or ingest finding
   * one). Display-only claims: nothing is verified against the provider, so
   * they never drive merge β†’ accepted. That stays with provider-verified
   * `scm_change_requests` rows, which take precedence when both name a PR.
   */
  pullRequests?: AcceptancePullRequestLink[];
  /** Latest explicit feedback handoff; kept apart from the standing Site review lifecycle. */
  repair?: AcceptanceRepairRequest;
  /** Task delivery's link back to the feedback handoff it addresses. */
  repairSource?: { acceptanceId: string; commentIds?: string[]; requestId: string };
  /** User-set display-title override for the acceptance (sidebar rename). */
  title?: string;
}

export interface AcceptanceRepairRequest {
  agentId?: string;
  comment?: string;
  commentIds: string[];
  deliveryAcceptanceId?: string;
  error?: string;
  executionUserId?: string;
  /** Frozen feedback, including page anchors and attachment references. */
  feedback: string;
  id: string;
  operationId?: string;
  requestedAt: string;
  requestedBy: string;
  state: 'failed' | 'finished' | 'running' | 'starting';
  taskId?: string;
  topicId?: string;
}

/** A hand-linked pull request on an acceptance. */
export interface AcceptancePullRequestLink {
  /** When it was linked (ISO 8601). */
  linkedAt: string;
  number: number;
  provider: 'github';
  /** `owner/name` as pasted; compare case-insensitively. */
  repoFullName: string;
  title?: string;
  url: string;
}

/**
 * The user's per-check verdict on the acceptance union. `accept` and `ignore`
 * are sticky β€” both settle the check across later rounds; `reject` binds to
 * the round it was made on and becomes iteration history once a newer round
 * lands.
 */
export type AcceptanceCheckReviewAction = 'accept' | 'ignore' | 'reject';

/**
 * Why a reviewer rejected a check β€” see `@lobechat/const/verify` for the reason
 * this exists at all (one button, three unrelated jobs).
 *
 * - unmet:       the delivery does not satisfy THIS check
 * - new-idea:    the check passes, but the reviewer wants something different
 * - no-evidence: the evidence does not show enough to judge the check at all
 */
export type AcceptanceRejectIntent = 'unmet' | 'new-idea' | 'no-evidence';

/** What an automated reviewer proposes for a check β€” never `ignore`, which is a
 *  statement about the reviewer's priorities rather than about the delivery.
 *  `unjudgeable` means no capture could settle the criterion from the reviewer's
 *  side; see `reviewPredictionActions` in `@lobechat/const/verify`. */
export type ReviewPredictionAction = 'accept' | 'reject' | 'unjudgeable';

/**
 * How a review attempt ended β€” see `@lobechat/const/verify` for why this is
 * separate from the verdict. `skipped` / `errored` carry no `action`.
 */
export type ReviewPredictionStatus = 'judged' | 'skipped' | 'errored';

/**
 * The reviewer's verdict on a model proposal. `misidentified` is separate from
 * `not-an-issue` on purpose: it carries the OPPOSITE signal on the judgement
 * (there really is a problem) while still marking the grounding wrong.
 */
export type ReviewAdjudication = 'confirmed' | 'not-an-issue' | 'misidentified';

/** How closely a submitted reject matched the proposal it started from. */
export type ReviewProposalEdit = 'verbatim' | 'comment-edited' | 'region-moved' | 'rewritten';

/**
 * One automated reviewer's opinion on one check result. Never written to
 * `verify_check_results.user_decision` β€” the human decision stays the single
 * ground truth, and this rides alongside it so the two can be compared per
 * model version.
 */
export interface ReviewPrediction {
  /** The verdict β€” absent unless `status` is `judged`. */
  action?: ReviewPredictionAction | null;
  /** Regions the model circled, same shape the human's annotations use. */
  annotations?: AcceptanceReviewAnnotation[];
  /** The one-line justification shown to the reviewer. */
  comment?: string;
  /** Model self-reported 0–1. Treat as unranked until calibrated per model. */
  confidence?: number;
  createdAt: string;
  id: string;
  /** Pins the opinion to what produced it, e.g. `gemini-3.6-flash`. */
  model: string;
  provider: string;
  /** Full reasoning, kept for training; not surfaced in the collapsed card. */
  rationale?: string;
  status: ReviewPredictionStatus;
}

/**
 * The reviewer's response to a proposal, recorded on the check's decision
 * detail. Kept next to the decision rather than on the prediction row so it
 * survives the prediction being regenerated for a newer model version.
 */
export interface ReviewProposalOutcome {
  adjudication: ReviewAdjudication;
  /** How much the reviewer changed the proposal before submitting it. */
  edit?: ReviewProposalEdit;
  /** The proposal being judged (`verify_review_predictions.id`). */
  predictionId: string;
  respondedAt: string;
}

/**
 * Where on a video evidence an annotation sits, in seconds from the start.
 * `start` alone pins one frame; `start` + `end` marks a span.
 */
export interface AcceptanceReviewAnnotationTime {
  end?: number;
  start: number;
}

/**
 * A user-drawn region on one evidence image, in coordinates normalized to the
 * image box (0–1) so the overlay renders at any display size. On video evidence
 * the region is drawn on the frame at `time.start`; a note that marks a moment
 * or a span without circling an area carries the whole frame
 * (`FULL_FRAME_RECT` in `@lobechat/const/verify`).
 */
export interface AcceptanceReviewAnnotation {
  /** The note attached to this region. */
  comment?: string;
  /**
   * The agent chapter this note disputes, quoted so the objection still reads
   * correctly after the evidence is re-uploaded.
   */
  disputes?: Pick<VerifyEvidenceChapter, 'kind' | 'note' | 't'>;
  /** The evidence row (`verify_evidence.id`) the region was drawn on. */
  evidenceId: string;
  rect: { height: number; width: number; x: number; y: number };
  /** Video evidence only: the frame or span the note is about. */
  time?: AcceptanceReviewAnnotationTime;
}

/**
 * How an agent marker on a video reads (runtime set: `verifyEvidenceChapterKinds`).
 *
 * - `step`: an action the agent performed, logged while driving the recording.
 * - `check`: something the agent verified on this frame β€” a claim for the reviewer
 *   to audit, never a pass.
 * - `flag`: an anomaly the agent noticed and judged harmless, disclosed so the
 *   reviewer can disagree.
 */
export type VerifyEvidenceChapterKind = 'check' | 'flag' | 'step';

/** An agent-authored marker on a video evidence (`verify_evidence.metadata.chapters`). */
export interface VerifyEvidenceChapter {
  kind: VerifyEvidenceChapterKind;
  /** Short name shown on the timeline; required for `step`. */
  label?: string;
  /** What the agent claims or noticed; required for `check` and `flag`. */
  note?: string;
  /** Seconds from the start of the video. */
  t: number;
}

/**
 * Provenance + feedback behind a user's decision on one check result
 * (`verify_check_results.user_decision_detail`) β€” the check-level mirror of
 * {@link VerifyRunDecisionDetail}. The `user_decision` verb stays the queryable
 * field; this bag carries the note, the circled evidence regions, and who/when,
 * so richer feedback never needs new columns.
 */
export interface VerifyCheckDecisionDetail {
  /** Regions circled on the check's evidence images, each with its own note. */
  annotations?: AcceptanceReviewAnnotation[];
  /** Free-form feedback β€” for a reject, the re-tasking input of the next round. */
  comment?: string;
  /** When the decision was made (ISO 8601). */
  decidedAt?: string;
  /** Who made the decision (user id) β€” set when it may differ from the row owner. */
  decidedBy?: string;
  /** Uploaded/pasted screenshots backing the reject (FKs to files). */
  fileIds?: string[];
  /**
   * Set when this decision started from a model proposal. Absent means the
   * reviewer judged cold β€” either they were in the blind control slice, or no
   * proposal existed yet. That distinction is what keeps miss rate measurable.
   */
  proposal?: ReviewProposalOutcome;
  /**
   * Which of the three jobs this reject is doing. Absent on rows written before
   * the intent split, which is why every reader must treat "no intent" as
   * "unknown" rather than defaulting it to `unmet` β€” backfilling a guess here
   * would manufacture exactly the label noise the split exists to remove.
   */
  rejectIntent?: AcceptanceRejectIntent;
  /**
   * The acceptance round that was CURRENT when the decision was made. A
   * carried-forward check's result row belongs to an older round, so the
   * result's own round cannot arbitrate staleness β€” a reject stands until a
   * round NEWER than this lands, regardless of which round produced the
   * judged evidence.
   */
  roundIndex?: number;
}

/**
 * Denormalized rollup of a verification round's pipeline state β€” mirrors the
 * legacy `agent_operations.verify_status` set so the two stay interchangeable
 * while results/reports migrate from being operation-anchored to run-anchored.
 *
 * `errored`: at least one required check errored (verifier couldn't run) and none
 * genuinely failed β€” verification is inconclusive, not a rejected delivery.
 */
export type VerifyRunStatus =
  | 'unverified'
  | 'planned'
  | 'collecting_evidence'
  | 'verifying'
  | 'passed'
  | 'failed'
  | 'errored'
  | 'repairing'
  | 'delivered';

/**
 * What produced a verification round.
 * - agent:         verifying a real Agent Run (`verify_runs.operation_id` set)
 * - agent-testing: a standalone round ingested from the agent-testing harness
 *   (no Agent Run β€” `operation_id` is null)
 */
export type VerifyRunSource = 'agent' | 'agent-testing';

/**
 * The kind of thing a verification round checks. Orthogonal to `source` (which
 * records what *produced* the run): `scenario` drives how the report renders its
 * scope header and scenario-specific detail. Open-ended β€” new scenarios add a
 * value here plus their own {@link VerifyRunContext} shape.
 * - coding:   verifying a software change (branch / commit / surfaces under test).
 * - writing:  verifying a written deliverable (manuscript / chapters / documents).
 * - research: verifying a research deliverable (question / sources / claims).
 * - generic:  any other delivery β€” no modeled scope; context is an open bag.
 */
export type VerifyRunScenario = 'coding' | 'writing' | 'research' | 'generic';

/**
 * The product surface a check was exercised on β€” *where* it ran, never *what
 * kind* of test it was. `unit` / `backend` / `type-check` are test kinds and do
 * not belong here; a backend change verified through the CLI has surface `cli`.
 *
 * A closed set on purpose: free-form surfaces drifted into 76 distinct values
 * (long prose, runtime modes, tool names), which no viewer can render as a
 * legible badge. Runtime detail ("packaged build", "CDP dev instance") belongs
 * on the plan item's `method`, not here.
 */
export type VerifySurface = 'web' | 'desktop' | 'cli' | 'mobile' | 'bot';

/** Who / what captured an evidence artifact (provenance). */
export type VerifyEvidenceCapturedBy =
  'agent' | 'agent-browser' | 'cdp' | 'cli' | 'program' | 'llm_judge';

/**
 * Provenance of a user's acceptance decision on a verify round
 * (`verify_runs.decision_detail`). One bag so the decision can carry richer
 * evidence β€” a note, attachments, who and when β€” without new columns; the
 * `verify_runs.user_decision` verb stays the queryable field.
 */
export interface VerifyRunDecisionDetail {
  /**
   * The provider change request whose merge made this decision, when
   * `source` is `scm_merge`. Lets the board and the verifier-training
   * pipeline tell a human verdict apart from a merge-driven one.
   */
  changeRequest?: {
    /** Provider user id of whoever merged; resolves through the SCM identities. */
    mergedByExternalId?: string;
    number: number;
    provider: string;
    repoFullName: string;
    url: string;
  };
  /** Free-form reason, e.g. the reject note that seeds the next repair round. */
  comment?: string;
  /** When the decision was made (ISO 8601). */
  decidedAt?: string;
  /** Who made the decision (user id) β€” set when it may differ from the run owner. */
  decidedBy?: string;
  /** Attachments backing the decision (annotated screenshots, etc.) β€” FKs to files. */
  fileIds?: string[];
  /**
   * Group-scoped review feedback addressed to THIS round β€” concerns that
   * belong to no single check (whose checks may well be accepted) yet must
   * reach the next round. Lives here, not on the acceptance aggregate, so a
   * round carries its own feedback (and takes it along when deleted) and
   * staleness falls out of the round chain.
   */
  groupFeedback?: VerifyRunGroupFeedbackEntry[];
  /**
   * What made the decision. Absent means a human clicked accept / reject;
   * `scm_merge` means the linked pull request was merged, which LobeHub
   * treats as the strongest possible acceptance signal.
   */
  source?: 'scm_merge';
}

/**
 * The LobeHub conversation an ingested report was authored in. Lets the report
 * link back to (and later resume) the agent session that produced it.
 */
export interface VerifyRunOrigin {
  /** The agent that ran the verification. */
  agentId?: string;
  /** The agent operation (one execution) that produced the report. */
  operationId?: string;
  /** The topic to reopen to continue from this report. */
  topicId?: string;
}

/**
 * Coding-scenario scope: where the code under test came from and how it ran.
 * Rendered as the report's scope header so the verify page reads as the final
 * report.
 */
export interface VerifyCodingPullRequest {
  /** Pull request number, e.g. 123. */
  number?: number | string;
  /** Pull request title. */
  title?: string;
  /** Web URL for opening the PR. */
  url?: string;
}

export interface VerifyCodingScope {
  /** Git branch the report was produced against. */
  branch?: string;
  /** Git commit (short sha) of the code under test. */
  commit?: string;
  /** Entry point / command exercised, e.g. "lh acceptance run ingest". */
  entry?: string;
  /** Associated pull request, when the verification run has one. */
  pullRequest?: VerifyCodingPullRequest;
  /** Product surfaces the checks ran on. */
  surfaces?: VerifySurface[];
  /** When the report was authored (ISO 8601) β€” distinct from the row's createdAt (ingest time). */
  testedAt?: string;
}

/**
 * Writing-scenario scope: what manuscript this round verified. Every field is
 * optional β€” the viewer renders whatever the round recorded.
 */
export interface VerifyWritingScope {
  /** Chapters covered by this round (delivered so far / in this batch). */
  chapters?: number;
  /** Documents holding the deliverable under verification. */
  documentIds?: string[];
  /** Entry point / command exercised, e.g. "lh doc export". */
  entry?: string;
  /** Genre / form of the work, e.g. "长篇小说". */
  genre?: string;
  /** When the round was executed (ISO 8601) β€” distinct from ingest time. */
  testedAt?: string;
  /** Word count of the manuscript under verification. */
  wordCount?: number;
  /** Title of the work under verification. */
  work?: string;
}

/** One source backing a research deliverable. */
export interface VerifyResearchSource {
  title?: string;
  url?: string;
}

/**
 * Research-scenario scope: what question the deliverable answers and what it
 * stands on.
 */
export interface VerifyResearchScope {
  /** Entry point / command exercised. */
  entry?: string;
  /** The research question the deliverable answers. */
  question?: string;
  /** Count of distinct sources consulted (when listing them all is too long). */
  sourceCount?: number;
  /** Key sources backing the deliverable. */
  sources?: VerifyResearchSource[];
  /** When the round was executed (ISO 8601) β€” distinct from ingest time. */
  testedAt?: string;
  /** Time range the research covers, e.g. "2024–2026". */
  timeRange?: string;
}

/**
 * Catch-all scope for scenarios without a modeled shape yet. An open bag on
 * purpose: the server stores non-coding context as-is, so a new scenario can
 * ship its own scope fields without a server change.
 */
export interface VerifyGenericScope {
  [key: string]: unknown;
  /** Entry point / command exercised. */
  entry?: string;
  /** When the round was executed (ISO 8601) β€” distinct from ingest time. */
  testedAt?: string;
}

/**
 * The scenario's context β€” its scope/provenance, discriminated by the run's
 * `scenario` (a sibling column, so the shapes need no inline discriminant).
 * Kept in one jsonb (not columns) so each scenario can carry its own shape and
 * the viewer can render per scenario without a migration.
 *
 * Distinct from the generic `metadata` bag (reserved for cross-scenario
 * extension) β€” `context` is specifically the active scenario's input.
 */
export type VerifyRunContext =
  VerifyCodingScope | VerifyWritingScope | VerifyResearchScope | VerifyGenericScope;

export interface VerifyInteractionCostOperators {
  H?: number;
  K?: number;
  M?: number;
  P?: number;
  R_ms?: number;
  T_chars?: number;
}

export interface VerifyInteractionCostPhase {
  actionCount?: number;
  activeSeconds?: number;
  /** Wall-clock the agent actually spent here β€” not the user-equivalent price. */
  actualAgentSeconds?: number;
  checkItemId?: string;
  id: string;
  label?: string;
  operators?: VerifyInteractionCostOperators;
  seconds?: number;
  waitSeconds?: number;
}

export interface VerifyInteractionCost {
  actionCount?: number;
  activeSeconds: number;
  actualAgentSeconds?: number;
  categoryCounts?: Record<string, number>;
  generatedAt?: string;
  mentalEstimates?: Record<string, unknown>[];
  model: string;
  operators: VerifyInteractionCostOperators;
  phases?: VerifyInteractionCostPhase[];
  scope?: string;
  sourceTrace?: string;
  timingSeconds?: Record<string, number>;
  totalSeconds: number;
  waitSeconds: number;
}

/**
 * Run-policy knobs for a rubric β€” applied to every run that mounts it. Lives in
 * one bag (not columns) so new policy switches can be added without a migration.
 * Read live at repair time via the plan item's `sourceRubricId`.
 */
export interface VerifyRubricConfig {
  /**
   * Max automatic repair rounds (parent-chain depth) before giving up, to cap
   * runaway repair loops. Defaults to {@link DEFAULT_MAX_REPAIR_ROUNDS}.
   */
  maxRepairRounds?: number;
}

/**
 * Generic per-run extension bag (`verify_runs.metadata`) β€” cross-scenario knobs
 * we don't model as columns. Kept open so new policy switches don't require a
 * migration; the active scenario's input lives in `context`, not here.
 */
export interface VerifyRunMetadata {
  [key: string]: unknown;
  /** Autonomous Goal review, kept separate from human decisions and verifier verdicts. */
  goalReview?: {
    feedback: string;
    predictionIds: string[];
    /**
     * The checks of the reviewed round the review sent back, by that round's own
     * plan item id, with the review's reason. They are what an in-round repair is
     * asked to fix, instead of the whole Task starting another attempt.
     */
    rejectedChecks?: { checkItemId: string; feedback: string }[];
    /**
     * `unjudgeable` is separate from `rejected` on purpose: it means the review
     * could not decide from evidence, not that the delivery fell short. Folding
     * it into `rejected` both sent the builder off to fix nothing and made the
     * two indistinguishable in the agreement statistics.
     */
    status: 'passed' | 'rejected' | 'errored' | 'unjudgeable';
  };
  interactionCost?: VerifyInteractionCost;
  /**
   * Per-run override for the repair-round cap, taking precedence over the
   * rubric's {@link VerifyRubricConfig.maxRepairRounds}. Set from a task's
   * `TaskVerifyConfig.maxIterations` so a task with ad-hoc criteria or a per-task
   * override honors its saved cap (the rubric may not carry it). Read at repair
   * time via {@link DEFAULT_MAX_REPAIR_ROUNDS} fallback.
   */
  maxRepairRounds?: number;
  /**
   * Where this report came from β€” the LobeHub conversation whose agent produced
   * it. Set when the harness runs inside a LobeHub-spawned agent (the runtime
   * echoes the ids into the child env; see {@link VerifyRunOrigin}).
   *
   * Deliberately *not* `verify_runs.operation_id`: that column means "this
   * session verifies that Agent Run" and is uniquely indexed, so one agent
   * publishing two reports would collide. Origin is the inverse relation β€” the
   * run that *authored* the report β€” and is many-to-one.
   */
  origin?: VerifyRunOrigin;
  previewUrl?: string;
  /** A Goal decision gate's frozen dossier: what the owner decides a batch release on. */
  releaseGate?: GoalReleaseGateDossier;
  /**
   * The round this one replays (`flow plan --from-run`). A replay is pinned to
   * the source round's frozen definition, so it never follows later graph edits
   * and never absorbs another flow, even while it holds no results yet.
   */
  replayOfRunId?: string;
  /**
   * When the stuck-run sweep re-drove this round's judging after its first
   * attempt died before any verifier started. A round is re-driven at most
   * once; a second stall is closed as `errored`.
   */
  verifierRedrivenAt?: string;
}

export type VerifyVisualizationValue = boolean | null | number | string;

export interface VerifyVisualizationField {
  key: string;
  label?: string;
  type: 'boolean' | 'category' | 'number' | 'string' | 'temporal';
  unit?: string;
}

/** Small inline dataset used by one or more check-result views. */
export interface VerifyVisualizationDataset {
  fields: VerifyVisualizationField[];
  id: string;
  rows: Record<string, VerifyVisualizationValue>[];
}

interface VerifyVisualizationViewBase {
  context?: string;
  dataset: string;
  id: string;
  title?: string;
  version: 1;
}

export interface VerifyMetricComparisonView extends VerifyVisualizationViewBase {
  encoding: {
    after: string;
    afterSamples?: string;
    before: string;
    beforeSamples?: string;
    direction?: string;
    label: string;
    statistic?: string;
    target?: string;
    unit?: string;
  };
  type: 'metric-comparison';
}

export interface VerifyLineChartView extends VerifyVisualizationViewBase {
  encoding: {
    series: {
      field: string;
      label?: string;
      /** Visual role: muted baselines stay gray while primary/accent series carry emphasis. */
      style?: 'accent' | 'muted' | 'primary';
    }[];
    x: string;
    xLabel?: string;
    yLabel?: string;
  };
  type: 'line-chart';
}

export interface VerifyScatterPlotView extends VerifyVisualizationViewBase {
  encoding: {
    color?: string;
    label?: string;
    x: string;
    xLabel?: string;
    y: string;
    yLabel?: string;
  };
  type: 'scatter-plot';
}

export interface VerifyHeatmapView extends VerifyVisualizationViewBase {
  encoding: { value: string; x: string; y: string };
  type: 'heatmap';
}

export interface VerifyBarChartView extends VerifyVisualizationViewBase {
  encoding: {
    category: string;
    series: { field: string; label?: string }[];
    valueLabel?: string;
  };
  type: 'bar-chart';
}

export interface VerifyTableView extends VerifyVisualizationViewBase {
  encoding?: {
    columns?: string[];
    /** Bold the best numeric value in each configured metric column. */
    highlights?: { field: string; mode: 'max' | 'min' }[];
  };
  type: 'table';
}

export type VerifyVisualizationView =
  | VerifyBarChartView
  | VerifyHeatmapView
  | VerifyLineChartView
  | VerifyMetricComparisonView
  | VerifyScatterPlotView
  | VerifyTableView;

/** Versioned structured presentation manifest attached to one check result. */
export interface VerifyVisualizationManifest {
  datasets: VerifyVisualizationDataset[];
  schemaVersion: 1;
  views: VerifyVisualizationView[];
}

/**
 * Why a builder disputes a check instead of satisfying it.
 * - `missed_evidence`: the evidence is already there; the previous review missed
 *   or misread it. The next review reads the builder's note next to the evidence.
 * - `invalid_criterion`: the check itself is wrong β€” outside the requirement,
 *   contradicting it or another check, or impossible for any delivery to meet.
 *   A panel of review models arbitrates; an upheld dispute waives the check.
 */
export type VerifyCheckDisputeKind = 'invalid_criterion' | 'missed_evidence';

/** One panel member's ruling on an `invalid_criterion` dispute. */
export interface VerifyDisputeVote {
  model: string;
  provider: string;
  reason?: string;
  /** `errored` when the member could not rule; it then casts no vote. */
  status: 'errored' | 'judged';
  /** Whether the member upholds the dispute (waives the check). Unset when errored. */
  upheld?: boolean;
}

export interface VerifyDisputeArbitration {
  decidedAt: string;
  /** `undecided` means no side reached a majority, so the check stands. */
  outcome: 'overruled' | 'undecided' | 'upheld';
  votes: VerifyDisputeVote[];
}

/** A builder's dispute of one check, filed on the round's check result. */
export interface VerifyCheckDispute {
  /** Set while a panel is ruling; it is the claim that keeps a second panel out. */
  arbitratingSince?: string;
  /** Only `invalid_criterion` disputes are arbitrated. */
  arbitration?: VerifyDisputeArbitration;
  /** Evidence rows on this check the builder points at. */
  evidenceIds?: string[];
  filedAt: string;
  kind: VerifyCheckDisputeKind;
  reason: string;
}

/** Known check-result metadata. Remains open for verifier-specific extensions. */
export interface VerifyCheckResultMetadata {
  [key: string]: unknown;
  dispute?: VerifyCheckDispute;
  visualization?: VerifyVisualizationManifest;
}

/**
 * How one round's checks came out, counted β€” what a surface shows as
 * "3 passed Β· 1 undecided" without reading the checks themselves.
 *
 * Deliberately the same three-way split the acceptance's criteria list uses
 * (`CriterionOutcomeState`): a check with no verdict falls back to its status,
 * and everything else is undecided. Two surfaces reading the same round must
 * not be able to disagree about it.
 */
export interface VerifyCheckTally {
  /** Judged failed β€” a failed verdict, or a failed status where no verdict landed. */
  failed: number;
  /** Judged passed β€” a passed verdict, or a passed status where no verdict landed. */
  passed: number;
  total: number;
  /** Planned but never judged: neither passed nor failed. */
  unjudged: number;
}

/**
 * Immutable snapshot of one check item, frozen into `agent_operations.verify_plan`
 * when the plan is confirmed. The resolved content (title / verifierConfig) is
 * copied in β€” not just a criterion FK β€” so editing the source criterion / rubric
 * never drifts the meaning of a historical plan. `sourceCriterionId` /
 * `sourceRubricId` are provenance pointers only.
 */
export interface VerifyCheckItem {
  /**
   * Grouping key for the acceptance union view (a page section / feature
   * domain, authored by the harness that writes the plan). Free-form label;
   * checks without one fall back to surface grouping.
   */
  category?: string;
  definition?: VerifyCheckDefinition;
  /** One-sentence summary of what this check verifies. */
  description?: string;
  /** The document holding the detailed judging instruction / rule body, if any. */
  documentId?: string | null;
  /** Stable uuid; `verify_check_results.check_item_id` relates to this, never the index. */
  id: string;
  /** Display ordering only β€” never used as a relation key. */
  index: number;
  /** What to do when this item fails. */
  onFail: VerifyOnFailStrategy;
  /** Whether failing this item blocks delivery (snapshot may override the source default). */
  required: boolean;
  resourceSnapshot?: {
    documentContent?: string;
    fixtures: { fixtureId: string; content?: string; fileHash?: string; url?: string }[];
  };
  /** Provenance: the criterion this item was instantiated from, or null when agent-generated. */
  sourceCriterionId?: string | null;
  /** Immutable reusable flow definition instantiated for this verification round. */
  sourceFlowNode?: { flowId: string; nodeId: string; incomingEdgeId?: string };
  /** Provenance: the rubric (group) this item came in through, or null. */
  sourceRubricId?: string | null;
  /**
   * Generation declaration: the older check-item ids THIS item replaces. The
   * acceptance union folds the superseded items into this item's iteration
   * timeline instead of listing semantically-dead checks side by side.
   */
  supersedes?: string[];
  title: string;
  verifierConfig: Record<string, unknown>;
  verifierType: VerifierType;
}

/**
 * `verifierConfig` of a plan item authored by a harness before its run.
 *
 * Note what is NOT here: *how the item is judged* is `verifierType`
 * (program / agent / llm), and *what artifact it must produce* is
 * {@link RequiredEvidenceSpec} under `requiredEvidence` β€” both closed sets, and
 * the latter is enforced (a missing required artifact fails the item through the
 * executor's coverage gate). `method` and `expected` are the human-readable
 * complement to those two, not a replacement: prose the author writes down
 * *before* the run so a reader can weigh intent against outcome, and so a
 * planned-but-never-executed item stays legible instead of vanishing.
 */
export interface VerifyAgentPlanConfig {
  /** The observable outcome that would make this item pass. Prose. */
  expected?: string;
  /** How the item would be exercised (steps / command / probe). Prose. */
  method?: string;
  /** Evidence media this item must produce β€” gated, not decorative. */
  requiredEvidence?: RequiredEvidenceSpec[];
  /**
   * The product surface THIS item was exercised on β€” the acceptance union view
   * groups checks by it. Optional and per-item on purpose: the run-level
   * `context.surfaces` records where the round ran as a whole, while one round
   * routinely mixes web + cli + desktop checks. Same closed set as
   * {@link VerifySurface}; a missing value renders ungrouped.
   */
  surface?: VerifySurface;
}

/**
 * Strongly-typed Toulmin narrative for a verdict. Only ever read as a whole, so
 * the narrative elements live in one bag instead of 4-5 half-empty columns.
 * The query-driving Claim (`verdict`) and Qualifier (`confidence`) stay as columns.
 */
export interface ToulminVerdict {
  /** Rebuttal β€” evidence pointing the other way. */
  counterEvidence?: string;
  /** Data β€” the evidence collected to support the claim. */
  evidence?: string;
  /** Rebuttal β€” known limitations of this verifier. */
  limitation?: string;
  /** Warrant β€” why the evidence supports the claim. */
  reasoning?: string;
}

// ============================================
// Evidence β€” first-class artifacts a verifier produces (screenshots, logs, …)
// ============================================

/**
 * A delivery-verification report. A generated artifact (not a computed one):
 * `summary` / `content` are written by an LLM from the round's check results +
 * evidence. Tied to a verification round via `verifyRunId` (which itself
 * optionally links back to an Agent Run).
 */
export interface VerifyReport {
  /** Full Markdown report, shown in the expanded review view. */
  content?: string | null;
  createdAt: Date;
  failedChecks?: number | null;
  generatedAt: Date;
  /** Producer of this report, e.g. 'system' / a model id. */
  generatedBy?: string | null;
  id: string;
  /** 0-1 aggregate confidence across the run. */
  overallConfidence?: number | null;
  passedChecks?: number | null;
  /** Whether the user has acknowledged the report. */
  reviewedByUser?: boolean | null;
  /** Short 3-5 sentence summary, suitable for embedding in a chat message. */
  summary?: string | null;
  totalChecks?: number | null;
  uncertainChecks?: number | null;
  /** Overall Claim, reusing the verdict vocabulary. */
  verdict?: VerifyVerdict | null;
  /** The verification round this report summarizes. */
  verifyRunId: string;
}