Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

33.4 KB
Raw Blame
import type { BackupTask, GuestSnapshot, PBSBackup, StorageBackup } from '@/types/api';
import type { ProtectionPosture, ProtectionState } from '@/types/recovery';
import type { Resource } from '@/types/resource';
import { parseBackupTimestampMs } from '@/utils/backupTimestamp';
import { backupLocationScope, type BackupLocationScope } from './proxmoxBackupLocation';

import {
  getProxmoxArchiveSourceTitle,
  getProxmoxBackupSourcePresentation,
  type ProxmoxBackupSourceKind,
} from './proxmoxBackupSourcePresentation';

export type RecoverableSourceKind = ProxmoxBackupSourceKind;

// `checking` and `not-evaluated` are presentation states, not server posture
// states. They prevent an in-flight request or a non-canonical host/orphan row
// from being mislabeled as a completed `unknown` evaluation.
export type WorkloadRecoveryPosture = ProtectionState | 'checking' | 'not-evaluated';

export interface WorkloadReference {
  key: string;
  resourceId?: string;
  type: 'vm' | 'ct' | 'host' | 'unknown';
  typeLabel: string;
  vmid: string;
  label: string;
  name?: string;
  /** Preferred presentation label for the hosting node. */
  node?: string;
  /** Provider-native node name retained for matching and diagnostics. */
  nativeNode?: string;
  nativeNodeAliases?: string[];
  instance?: string;
}

export interface RecoverableArtifact extends BackupLocationScope {
  id: string;
  nativeId: string;
  sourceKind: RecoverableSourceKind;
  sourceLabel: string;
  sourceTitle?: string;
  workload: WorkloadReference;
  createdAt: string;
  createdMs?: number;
  /** Positive reported bytes only. Missing/zero does not establish an empty point. */
  size?: number;
  location: string;
  detail: string;
  /** Full provider identifier behind a shortened `detail`, shown on hover. */
  detailTitle?: string;
  protected: boolean;
  verified?: boolean;
  /** A still-running backup is writing this artifact; it is not recoverable yet. */
  running?: boolean;
  /** A terminal task left an incomplete artifact which is not recoverable. */
  failed?: boolean;
  fileCount?: number;
}

export interface CoverageTask {
  id: string;
  status: string;
  label: string;
  startedAt: string;
  startedMs?: number;
  durationSeconds?: number;
  /** Reported timing/status cannot establish a completed duration; not missing data or zero. */
  durationUnknown?: boolean;
  error?: string;
  /** Task-reported origin, independent of the workload's current placement. */
  instance?: string;
  node?: string;
}

export interface WorkloadCoverageRow {
  key: string;
  workload: WorkloadReference;
  artifacts: RecoverableArtifact[];
  /**
   * Newest completed PBS snapshot or PVE backup file, only when all completed
   * backup dates can be ordered. Guest snapshots never
   * fill this slot: they live on the guest's own storage and the protection
   * posture engine does not count them as independent recovery, so a fresh
   * snapshot must not read as a fresh backup beside a stale posture.
   */
  latestBackup?: RecoverableArtifact;
  latestPBS?: RecoverableArtifact;
  latestArchive?: RecoverableArtifact;
  latestSnapshot?: RecoverableArtifact;
  /** Unknown chronology is not an absent backup, nor an older dated backup. */
  ageUnknown?: Record<'backup' | 'pbs' | 'archive' | 'snapshot', boolean>;
  latestTask?: CoverageTask;
  /** Possible latest tasks when missing/future or tied starts prevent ordering. */
  taskCandidates?: CoverageTask[];
  pbsCount: number;
  archiveCount: number;
  snapshotCount: number;
  posture: WorkloadRecoveryPosture;
  postureRank: number;
  protectionPosture?: ProtectionPosture;
  // True only when a VM/LXC row exists because a backup/task referenced a VMID
  // with no unambiguous live inventory match (absent or conflicting). Host backups can also carry a
  // `backup:` key, but they are first-class backup targets, not orphaned guests.
  isOrphaned: boolean;
}

export interface ProxmoxBackupRecoveryModel {
  coverageRows: WorkloadCoverageRow[];
  /** All observed entries, including incomplete artifacts retained for inspection. */
  recoverableArtifacts: RecoverableArtifact[];
  coverageSummary: {
    totalWorkloads: number;
    protected: number;
    attention: number;
    unprotected: number;
    unknown: number;
    withPBS: number;
    /** Completed restore points only; completion is not a successful restore or thaw. */
    recoverableArtifacts: number;
    runningArtifacts: number;
    failedArtifacts: number;
    totalBytes: number;
  };
}

interface BuildModelInput {
  workloads: readonly Resource[];
  pbsBackups: readonly PBSBackup[];
  archives: readonly StorageBackup[];
  snapshots: readonly GuestSnapshot[];
  tasks: readonly BackupTask[];
  nowMs: number;
  protectionPostures?: ReadonlyMap<string, ProtectionPosture>;
  protectionPosturesResolved?: boolean;
}

type WorkloadCandidate = WorkloadReference;

type WorkloadRowDraft = Omit<WorkloadCoverageRow, 'posture' | 'postureRank' | 'isOrphaned'>;

const DAY_MS = 24 * 60 * 60 * 1000;
export const CURRENT_RECOVERY_MS = 7 * DAY_MS;
export const STALE_RECOVERY_MS = 30 * DAY_MS;

export type RecoveryAgeBand = 'current' | 'aging' | 'stale' | 'unknown';

export function getRecoveryAgeBand(
  createdMs: number | undefined,
  nowMs: number = Date.now(),
): RecoveryAgeBand {
  if (createdMs === undefined || createdMs <= 0 || !Number.isFinite(new Date(createdMs).getTime()))
    return 'unknown';
  const ageMs = nowMs - createdMs;
  if (!Number.isFinite(ageMs) || ageMs < 0) return 'unknown';
  if (ageMs <= CURRENT_RECOVERY_MS) return 'current';
  if (ageMs <= STALE_RECOVERY_MS) return 'aging';
  return 'stale';
}

// A guest snapshot shares the guest's storage, so it is listed as restore
// evidence but never counted as a backup. Mirrors the server posture rule that
// "a snapshot is not a separate backup, so it does not count".
export function isBackupArtifact(artifact: RecoverableArtifact): boolean {
  return artifact.sourceKind !== 'snapshot';
}

/** Incomplete artifacts remain evidence, but are not completed restore points. */
export function isCompletedRecoveryArtifact(artifact: RecoverableArtifact): boolean {
  return !artifact.running && !artifact.failed;
}

/**
 * What a list holds beyond its completed restore points ("33 running · 1 failed").
 * An entry both running and failed counts once, as running, as its row reads.
 */
export function describeIncompleteArtifacts(artifacts: readonly RecoverableArtifact[]): string {
  const running = artifacts.filter((artifact) => artifact.running).length;
  const failed = artifacts.filter((artifact) => !artifact.running && artifact.failed).length;
  return [running > 0 ? `${running} running` : '', failed > 0 ? `${failed} failed` : '']
    .filter(Boolean)
    .join(' · ');
}

export const restorePointCountNoun = (count: number, inventoryIncomplete: boolean): string => {
  const noun = count === 1 ? 'restore point' : 'restore points';
  return inventoryIncomplete ? `${noun} read` : noun;
};

// Zero is also the producer's missing-size placeholder. Keep it in the raw
// inventory, but not as a measured zero in the recovery view (including sorts).
function reportedSizeBytes(size: number | undefined): number | undefined {
  return size !== undefined && Number.isFinite(size) && size > 0 ? size : undefined;
}

function archiveFileName(volid: string | undefined): string {
  const trimmed = volid?.trim() ?? '';
  if (!trimmed) return '';
  return trimmed.slice(trimmed.lastIndexOf('/') + 1);
}

function pbsBackupFileDetailLabel(fileCount: number): string {
  if (fileCount <= 0) return 'PBS files not listed';
  if (fileCount === 1) return '1 PBS file';
  return `${fileCount} PBS files`;
}

function normalizeKey(value: string | number | undefined | null): string {
  return String(value ?? '')
    .trim()
    .toLowerCase();
}

function isZeroWorkloadId(vmid: string): boolean {
  return normalizeKey(vmid) === '0';
}

function backupTypeLabel(type: string | undefined): WorkloadReference['type'] {
  const normalized = normalizeKey(type);
  if (normalized === 'vm' || normalized === 'qemu') return 'vm';
  if (normalized === 'ct' || normalized === 'lxc') return 'ct';
  if (normalized === 'host') return 'host';
  return 'unknown';
}

function typeLabel(type: WorkloadReference['type']): string {
  if (type === 'vm') return 'VM';
  if (type === 'ct') return 'LXC';
  if (type === 'host') return 'Host';
  return 'Guest';
}

function firstHostHint(hints: readonly (string | undefined)[]): string | undefined {
  return hints
    .map((hint) => hint?.trim())
    .find((hint) => hint && normalizeKey(hint) !== 'root' && normalizeKey(hint) !== '(root)');
}

function fallbackWorkloadId(
  type: WorkloadReference['type'],
  vmid: string,
  hints: readonly (string | undefined)[],
): string {
  const cleanVmid = vmid.trim();
  if (type === 'host') {
    if (cleanVmid && !isZeroWorkloadId(cleanVmid)) return cleanVmid;
    return firstHostHint(hints) ?? '';
  }
  if (cleanVmid && !isZeroWorkloadId(cleanVmid)) return cleanVmid;
  return '';
}

function workloadFallbackLabel(type: WorkloadReference['type'], id: string): string {
  const label = typeLabel(type);
  const cleanId = id.trim();
  if (cleanId) return `${label} ${cleanId}`;
  if (type === 'host') return 'Host backup';
  return type === 'unknown' ? label : `${label} backup`;
}

function resourceVmid(resource: Resource): string {
  const fromMeta = resource.proxmox?.vmid;
  if (typeof fromMeta === 'number' && Number.isFinite(fromMeta)) return String(fromMeta);
  const platformProxmox = resource.platformData?.proxmox;
  if (typeof platformProxmox === 'object' && platformProxmox !== null) {
    const value = (platformProxmox as Record<string, unknown>).vmid;
    if (typeof value === 'number' && Number.isFinite(value)) return String(value);
    if (typeof value === 'string' && value.trim()) return value.trim();
  }
  return '';
}

function resourceBackupType(resource: Resource): WorkloadReference['type'] {
  if (resource.type === 'vm') return 'vm';
  if (resource.type === 'system-container' || resource.type === 'oci-container') return 'ct';
  return 'unknown';
}

function resourceNode(resource: Resource): string | undefined {
  return resource.proxmox?.nodeName || resource.proxmox?.node || undefined;
}

function resourceNodeDisplayName(resource: Resource): string | undefined {
  return resource.proxmox?.nodeDisplayName || resource.parentName || resourceNode(resource);
}

function resourceInstance(resource: Resource): string | undefined {
  const fromMeta = resource.proxmox?.instance;
  if (fromMeta) return fromMeta;
  const platformProxmox = resource.platformData?.proxmox;
  if (typeof platformProxmox === 'object' && platformProxmox !== null) {
    const value = (platformProxmox as Record<string, unknown>).instance;
    if (typeof value === 'string' && value.trim()) return value.trim();
  }
  return undefined;
}

function buildWorkloadLabel(
  name: string | undefined,
  type: WorkloadReference['type'],
  vmid: string,
) {
  const fallback = workloadFallbackLabel(type, vmid);
  const cleanName = name?.trim();
  if (!cleanName || cleanName === fallback || cleanName === vmid) return fallback;
  return `${cleanName} (${fallback})`;
}

function buildCandidateFromResource(resource: Resource): WorkloadCandidate | null {
  const vmid = resourceVmid(resource);
  const type = resourceBackupType(resource);
  if (!vmid || isZeroWorkloadId(vmid) || type === 'unknown') return null;
  const name = resource.displayName || resource.name || undefined;
  const nativeNode = resourceNode(resource);
  const node = resourceNodeDisplayName(resource);
  const nativeNodeAliases = resource.proxmox?.nodeAliases ?? [];
  const instance = resourceInstance(resource);
  return {
    key: `resource:${resource.id}`,
    resourceId: resource.id,
    type,
    typeLabel: typeLabel(type),
    vmid,
    label: buildWorkloadLabel(name, type, vmid),
    name,
    node,
    nativeNode,
    nativeNodeAliases,
    instance,
  };
}

function fallbackWorkload(
  type: WorkloadReference['type'],
  vmid: string,
  hints: readonly (string | undefined)[],
  sourceScope: readonly (string | undefined)[],
  pveInstance?: string,
  pveNode?: string,
): WorkloadReference {
  const id = fallbackWorkloadId(type, vmid, hints);
  // A VMID (or host label) and repository name are not cross-source identity.
  // Keep unresolved evidence listed, with a collision-safe complete source key.
  const scope = encodeURIComponent(
    JSON.stringify(sourceScope.map((part) => String(part ?? '').trim())),
  );
  return {
    key: `backup:${type}:${id || 'unknown'}:${scope}`,
    type,
    typeLabel: typeLabel(type),
    vmid: id,
    label: workloadFallbackLabel(type, id),
    // Repository/namespace and connection hints can name a fallback target,
    // but do not report a guest node. Only the PVE producer supplies one.
    node: type === 'host' ? undefined : pveNode?.trim() || undefined,
    nativeNode: type === 'host' ? undefined : pveNode?.trim() || undefined,
    instance: pveInstance,
  };
}

function isCoverageWorkload(workload: WorkloadReference): boolean {
  if (workload.type === 'vm' || workload.type === 'ct') {
    return Boolean(workload.vmid.trim()) && !isZeroWorkloadId(workload.vmid);
  }
  return workload.type === 'host' && Boolean(workload.vmid.trim());
}

interface WorkloadCandidateIndex {
  byTypeAndVmid: ReadonlyMap<string, readonly WorkloadCandidate[]>;
  byVmid: ReadonlyMap<string, readonly WorkloadCandidate[]>;
}

const workloadTypeVmidKey = (type: WorkloadReference['type'], vmid: string): string =>
  `${type}:${vmid}`;

function buildWorkloadCandidateIndex(
  candidates: readonly WorkloadCandidate[],
): WorkloadCandidateIndex {
  const byTypeAndVmid = new Map<string, WorkloadCandidate[]>();
  const byVmid = new Map<string, WorkloadCandidate[]>();
  for (const candidate of candidates) {
    const typedKey = workloadTypeVmidKey(candidate.type, candidate.vmid);
    const typed = byTypeAndVmid.get(typedKey);
    if (typed) typed.push(candidate);
    else byTypeAndVmid.set(typedKey, [candidate]);

    const matchingVmid = byVmid.get(candidate.vmid);
    if (matchingVmid) matchingVmid.push(candidate);
    else byVmid.set(candidate.vmid, [candidate]);
  }
  return { byTypeAndVmid, byVmid };
}

function uniqueWorkload<T>(matches: readonly T[]): T | undefined {
  return matches.length === 1 ? matches[0] : undefined;
}

function matchesNativeNode(workload: WorkloadReference, node: string): boolean {
  const key = normalizeKey(node);
  return (
    Boolean(key) &&
    [workload.nativeNode, ...(workload.nativeNodeAliases ?? [])].some(
      (name) => normalizeKey(name) === key,
    )
  );
}

function matchPVEWorkload<T extends WorkloadReference>(
  workloads: readonly T[],
  instance: string,
  node: string,
): T | undefined {
  const instanceKey = normalizeKey(instance);
  const nodeKey = normalizeKey(node);
  if (instanceKey) {
    const scoped = workloads.filter((workload) => normalizeKey(workload.instance) === instanceKey);
    // A VMID is unique inside its PVE connection. Historical backup/task nodes
    // can differ after a migration; they must not override that connection.
    if (scoped.length > 0) {
      return (
        uniqueWorkload(scoped) ??
        uniqueWorkload(scoped.filter((workload) => matchesNativeNode(workload, node)))
      );
    }
    // Older projections may omit the instance. An exact native node can still
    // identify one of them, but cannot rescue a known conflicting instance.
    return uniqueWorkload(
      workloads.filter(
        (workload) => !normalizeKey(workload.instance) && matchesNativeNode(workload, node),
      ),
    );
  }
  if (nodeKey)
    return uniqueWorkload(workloads.filter((workload) => matchesNativeNode(workload, node)));
  return uniqueWorkload(workloads);
}

function resolvePVEWorkload(
  candidates: WorkloadCandidateIndex,
  type: WorkloadReference['type'],
  vmid: string,
  instance: string,
  node: string,
): WorkloadReference {
  const typed = candidates.byTypeAndVmid.get(workloadTypeVmidKey(type, vmid)) ?? [];
  return (
    matchPVEWorkload(typed, instance, node) ??
    fallbackWorkload(
      type,
      vmid,
      type === 'host' ? [instance, node] : [node, instance],
      ['pve', instance, node],
      instance,
      node,
    )
  );
}

function resolvePBSWorkload(
  candidates: WorkloadCandidateIndex,
  backup: PBSBackup,
): WorkloadReference {
  const type = backupTypeLabel(backup.backupType);
  const typed = candidates.byTypeAndVmid.get(workloadTypeVmidKey(type, backup.vmid)) ?? [];
  // PBS instance/datastore identify a repository, not a PVE connection. A
  // namespace can disambiguate a repeated VMID only with one exact native
  // node/alias or connection match. A display name or substring proves none.
  const namespace = normalizeKey(backup.namespace);
  const matched = namespace
    ? uniqueWorkload(
        typed.filter(
          (workload) =>
            matchesNativeNode(workload, backup.namespace) ||
            normalizeKey(workload.instance) === namespace,
        ),
      )
    : undefined;
  return (
    matched ??
    uniqueWorkload(typed) ??
    fallbackWorkload(
      type,
      backup.vmid,
      [backup.namespace, backup.datastore],
      ['pbs', backup.instance, backup.datastore, backup.namespace],
    )
  );
}

function resolveTaskWorkload(
  candidates: WorkloadCandidateIndex,
  pveWorkloadsByVmid: ReadonlyMap<string, readonly WorkloadReference[]>,
  task: BackupTask,
): WorkloadReference | undefined {
  const vmid = String(task.vmid);
  if (!vmid || isZeroWorkloadId(vmid)) return undefined;

  const explicitType = backupTypeLabel(task.type);
  if (explicitType !== 'unknown')
    return resolvePVEWorkload(candidates, explicitType, vmid, task.instance, task.node);

  const candidate = matchPVEWorkload(candidates.byVmid.get(vmid) ?? [], task.instance, task.node);
  if (candidate) return candidate;
  // Only PVE-backed orphan rows share this source scope. A PBS namespace that
  // happens to resemble the task node is not evidence that the task owns it.
  return matchPVEWorkload(pveWorkloadsByVmid.get(vmid) ?? [], task.instance, task.node);
}

function newest<T>(items: readonly T[], getMs: (item: T) => number | undefined): T | undefined {
  let best: T | undefined;
  let bestMs = Number.NEGATIVE_INFINITY;
  for (const item of items) {
    const ms = getMs(item);
    if (ms !== undefined && ms > bestMs) {
      best = item;
      bestMs = ms;
    }
  }
  return best;
}

/** Shared by the full inventory and the location-filtered Coverage view. */
export function selectWorkloadRecoveryArtifacts(
  artifacts: readonly RecoverableArtifact[],
  nowMs: number,
): Pick<
  WorkloadCoverageRow,
  'latestBackup' | 'latestPBS' | 'latestArchive' | 'latestSnapshot' | 'ageUnknown'
> {
  // Completion remains independent of age. Keep every artifact listed, but
  // don't guess the latest when even one completed date cannot be ordered.
  const completed = artifacts.filter(isCompletedRecoveryArtifact);
  const select = (items: RecoverableArtifact[]) => {
    const unknown = items.some(
      (artifact) => getRecoveryAgeBand(artifact.createdMs, nowMs) === 'unknown',
    );
    const latest = unknown ? undefined : newest(items, (artifact) => artifact.createdMs);
    return {
      unknown,
      // Coverage reconciles its row store in place. Each pointer needs its
      // own scalar fields: otherwise updating latestArchive can mutate the
      // same object also held by latestBackup after a newer PBS point arrives.
      latest: latest ? { ...latest } : undefined,
    };
  };
  const backup = select(completed.filter(isBackupArtifact));
  const pbs = select(completed.filter((artifact) => artifact.sourceKind === 'pbs'));
  const archive = select(completed.filter((artifact) => artifact.sourceKind === 'archive'));
  const snapshot = select(completed.filter((artifact) => artifact.sourceKind === 'snapshot'));
  return {
    latestBackup: backup.latest,
    latestPBS: pbs.latest,
    latestArchive: archive.latest,
    latestSnapshot: snapshot.latest,
    ageUnknown: {
      backup: backup.unknown,
      pbs: pbs.unknown,
      archive: archive.unknown,
      snapshot: snapshot.unknown,
    },
  };
}

function taskLabel(task: BackupTask): string {
  const normalized = normalizeKey(task.status);
  if (normalized === 'ok' || normalized === 'success' || normalized === 'completed') return 'OK';
  if (normalized === 'failed' || normalized === 'error') return 'Failed';
  if (normalized === 'running') return 'Running';
  return task.status || 'Unknown';
}

function taskDuration(
  task: BackupTask,
  nowMs: number,
): Pick<CoverageTask, 'durationSeconds' | 'durationUnknown'> {
  if (!task.endTime) return {};
  const start = parseBackupTimestampMs(task.startTime);
  const end = parseBackupTimestampMs(task.endTime);
  // Parseable endpoints alone do not establish observed elapsed time. Apply
  // the same positive/past-instant rule as task ordering, and never use a
  // contradictory end time to make a running task look completed.
  if (
    normalizeKey(task.status) === 'running' ||
    start === undefined ||
    end === undefined ||
    getRecoveryAgeBand(start, nowMs) === 'unknown' ||
    getRecoveryAgeBand(end, nowMs) === 'unknown' ||
    end <= start
  ) {
    return { durationUnknown: true };
  }
  return { durationSeconds: Math.round((end - start) / 1000) };
}

function selectLatestTask(
  tasks: readonly CoverageTask[],
): Pick<WorkloadCoverageRow, 'latestTask' | 'taskCandidates'> {
  const unknown = tasks.filter((task) => task.startedMs === undefined);
  const newestMs = tasks.reduce((latest, task) => Math.max(latest, task.startedMs ?? 0), 0);
  // An undated task might be newer than any dated task. Equal starts do not
  // order distinct observations either. Retain all possible latest tasks;
  // never choose by API input order, status, ID or an invented zero date.
  const candidates = tasks.filter(
    (task) => task.startedMs === undefined || task.startedMs === newestMs,
  );
  if (candidates.length === 1) return { latestTask: candidates[0] };
  if (candidates.length === 0) return {};
  return {
    taskCandidates: [
      ...unknown.sort((left, right) => left.id.localeCompare(right.id)),
      ...candidates
        .filter((task) => task.startedMs !== undefined)
        .sort((left, right) => left.id.localeCompare(right.id)),
    ],
  };
}

function protectionPostureRank(posture: WorkloadRecoveryPosture): number {
  if (posture === 'attention') return 0;
  if (posture === 'unprotected') return 1;
  if (posture === 'unknown') return 2;
  if (posture === 'checking') return 3;
  if (posture === 'protected') return 4;
  return 5;
}

export function getWorkloadRecoveryPostureLabel(posture: WorkloadRecoveryPosture): string {
  switch (posture) {
    case 'protected':
      return 'Protected';
    case 'attention':
      return 'Needs attention';
    case 'unprotected':
      return 'Unprotected';
    case 'unknown':
      return 'Unknown';
    case 'checking':
      return 'Checking';
    case 'not-evaluated':
      return 'Not evaluated';
  }
}

export function isCoverageAttention(posture: WorkloadRecoveryPosture): boolean {
  return posture === 'attention';
}

export function buildProxmoxBackupRecoveryModel(
  input: BuildModelInput,
): ProxmoxBackupRecoveryModel {
  const candidates = input.workloads
    .map(buildCandidateFromResource)
    .filter((candidate): candidate is WorkloadCandidate => candidate !== null);
  const candidateIndex = buildWorkloadCandidateIndex(candidates);
  const rows = new Map<string, WorkloadRowDraft>();
  const pveWorkloadsByVmid = new Map<string, WorkloadReference[]>();

  const ensureRow = (workload: WorkloadReference, pveSource: boolean) => {
    const existing = rows.get(workload.key);
    if (existing) return existing;
    const row: WorkloadRowDraft = {
      key: workload.key,
      workload,
      artifacts: [],
      pbsCount: 0,
      archiveCount: 0,
      snapshotCount: 0,
    };
    rows.set(workload.key, row);
    if (pveSource) {
      const matchingVmid = pveWorkloadsByVmid.get(workload.vmid);
      if (matchingVmid) matchingVmid.push(workload);
      else pveWorkloadsByVmid.set(workload.vmid, [workload]);
    }
    return row;
  };

  for (const candidate of candidates) ensureRow(candidate, true);

  const artifacts: RecoverableArtifact[] = [];
  const pbsSource = getProxmoxBackupSourcePresentation('pbs');
  const archiveSource = getProxmoxBackupSourcePresentation('archive');
  const snapshotSource = getProxmoxBackupSourcePresentation('snapshot');
  const addArtifact = (artifact: RecoverableArtifact) => {
    artifacts.push(artifact);
    if (!isCoverageWorkload(artifact.workload)) return;
    const row = ensureRow(artifact.workload, artifact.sourceKind !== 'pbs');
    row.artifacts.push(artifact);
    if (artifact.sourceKind === 'pbs') row.pbsCount += 1;
    else if (artifact.sourceKind === 'archive') row.archiveCount += 1;
    else row.snapshotCount += 1;
  };

  for (const backup of input.pbsBackups) {
    const workload = resolvePBSWorkload(candidateIndex, backup);
    const parsedMs = parseBackupTimestampMs(backup.backupTime);
    const createdMs =
      getRecoveryAgeBand(parsedMs, input.nowMs) === 'unknown' ? undefined : parsedMs;
    const running =
      backup.inProgress === true &&
      (backup.writeActivityObserved !== true || backup.writeActive === true);
    const failed =
      backup.inProgress === true &&
      backup.writeActivityObserved === true &&
      backup.writeActive !== true;
    addArtifact({
      id: `pbs:${backup.id}`,
      nativeId: backup.id,
      sourceKind: 'pbs',
      sourceLabel: pbsSource.badgeLabel,
      sourceTitle: pbsSource.sourceTitle,
      workload,
      createdAt: backup.backupTime,
      createdMs,
      size: reportedSizeBytes(backup.size),
      location: `${backup.datastore || '—'} / ${backup.namespace?.trim() || '(root)'}`,
      ...backupLocationScope('pbs', backup.instance, backup.datastore),
      detail: pbsBackupFileDetailLabel(backup.files.length),
      protected: backup.protected,
      verified: backup.inProgress ? undefined : backup.verified,
      running,
      failed,
      fileCount: backup.files.length,
    });
  }

  for (const archive of input.archives) {
    const type = backupTypeLabel(archive.type);
    const workload = resolvePVEWorkload(
      candidateIndex,
      type,
      String(archive.vmid),
      archive.instance,
      archive.node,
    );
    const parsedMs = parseBackupTimestampMs(archive.time);
    const createdMs =
      getRecoveryAgeBand(parsedMs, input.nowMs) === 'unknown' ? undefined : parsedMs;
    addArtifact({
      id: `archive:${archive.id}`,
      nativeId: archive.id,
      sourceKind: 'archive',
      sourceLabel: archiveSource.badgeLabel,
      sourceTitle: getProxmoxArchiveSourceTitle(Boolean(archive.isPBS)),
      workload,
      createdAt: archive.time,
      createdMs,
      size: reportedSizeBytes(archive.size),
      location: archive.storage || archive.node || '—',
      ...backupLocationScope('archive', archive.instance, archive.storage || archive.node),
      // The volid repeats the storage, guest type, VMID, and timestamp the row
      // already shows in their own columns and clips at every width; the
      // archive format is the one fact it adds, so that is the cell and the
      // volid stays on hover and in search.
      detail: archive.format || archiveFileName(archive.volid) || archiveSource.detailFallbackLabel,
      detailTitle: archive.volid || undefined,
      protected: archive.protected,
      verified: archive.inProgress ? undefined : archive.isPBS ? archive.verified : undefined,
      running: archive.inProgress === true,
    });
  }

  for (const snapshot of input.snapshots) {
    const type = backupTypeLabel(snapshot.type);
    const workload = resolvePVEWorkload(
      candidateIndex,
      type,
      String(snapshot.vmid),
      snapshot.instance,
      snapshot.node,
    );
    const parsedMs = parseBackupTimestampMs(snapshot.time);
    const createdMs =
      getRecoveryAgeBand(parsedMs, input.nowMs) === 'unknown' ? undefined : parsedMs;
    addArtifact({
      id: `snapshot:${snapshot.id}`,
      nativeId: snapshot.id,
      sourceKind: 'snapshot',
      sourceLabel: snapshotSource.badgeLabel,
      sourceTitle: snapshotSource.sourceTitle,
      workload,
      createdAt: snapshot.time,
      createdMs,
      size: reportedSizeBytes(snapshot.sizeBytes),
      location: snapshot.node || snapshot.instance || '—',
      ...backupLocationScope('snapshot', snapshot.instance, snapshot.node),
      detail: snapshot.description || snapshot.name || snapshotSource.detailFallbackLabel,
      protected: false,
    });
  }

  const tasksByWorkload = new Map<string, CoverageTask[]>();
  for (const task of input.tasks) {
    const workload = resolveTaskWorkload(candidateIndex, pveWorkloadsByVmid, task);
    if (!workload) continue;
    const row = ensureRow(workload, true);
    const parsedStart = parseBackupTimestampMs(task.startTime);
    const candidateTask: CoverageTask = {
      id: task.id,
      status: task.status,
      label: taskLabel(task),
      startedAt: task.startTime,
      startedMs:
        getRecoveryAgeBand(parsedStart, input.nowMs) === 'unknown' ? undefined : parsedStart,
      ...taskDuration(task, input.nowMs),
      error: task.error,
      instance: task.instance?.trim() || undefined,
      node: task.node?.trim() || undefined,
    };
    const rowTasks = tasksByWorkload.get(row.key) ?? [];
    rowTasks.push(candidateTask);
    tasksByWorkload.set(row.key, rowTasks);
  }

  for (const row of rows.values()) {
    Object.assign(row, selectWorkloadRecoveryArtifacts(row.artifacts, input.nowMs));
    Object.assign(row, selectLatestTask(tasksByWorkload.get(row.key) ?? []));
  }

  const coverageRows = Array.from(rows.values()).map((row) => {
    const protectionPosture = row.workload.resourceId
      ? input.protectionPostures?.get(row.workload.resourceId)
      : undefined;
    const posture: WorkloadRecoveryPosture = protectionPosture?.state
      ? protectionPosture.state
      : !row.workload.resourceId
        ? 'not-evaluated'
        : input.protectionPosturesResolved === false
          ? 'checking'
          : 'unknown';
    return {
      ...row,
      posture,
      postureRank: protectionPostureRank(posture),
      protectionPosture,
      isOrphaned:
        !row.key.startsWith('resource:') &&
        (row.workload.type === 'vm' || row.workload.type === 'ct'),
    };
  });

  coverageRows.sort((left, right) => {
    if (left.postureRank !== right.postureRank) return left.postureRank - right.postureRank;
    return (right.latestBackup?.createdMs ?? 0) - (left.latestBackup?.createdMs ?? 0);
  });
  artifacts.sort((left, right) => (right.createdMs ?? 0) - (left.createdMs ?? 0));

  const completedArtifacts = artifacts.filter(isCompletedRecoveryArtifact);
  const totalBytes = completedArtifacts.reduce((sum, artifact) => sum + (artifact.size ?? 0), 0);
  return {
    coverageRows,
    recoverableArtifacts: artifacts,
    coverageSummary: {
      totalWorkloads: coverageRows.length,
      protected: coverageRows.filter((row) => row.posture === 'protected').length,
      attention: coverageRows.filter((row) => isCoverageAttention(row.posture)).length,
      unprotected: coverageRows.filter((row) => row.posture === 'unprotected').length,
      unknown: coverageRows.filter((row) => row.posture === 'unknown').length,
      withPBS: coverageRows.filter((row) =>
        row.artifacts.some(
          (artifact) => artifact.sourceKind === 'pbs' && isCompletedRecoveryArtifact(artifact),
        ),
      ).length,
      recoverableArtifacts: completedArtifacts.length,
      runningArtifacts: artifacts.filter((artifact) => artifact.running).length,
      failedArtifacts: artifacts.filter((artifact) => artifact.failed).length,
      totalBytes,
    },
  };
}

export function coverageRowMatchesSearch(row: WorkloadCoverageRow, term: string): boolean {
  const normalizedTerm = term.trim().toLowerCase();
  if (!normalizedTerm) return true;
  const haystack = [
    row.workload.label,
    row.workload.name,
    row.workload.typeLabel,
    row.workload.vmid,
    row.workload.node,
    row.workload.nativeNode,
    ...(row.workload.nativeNodeAliases ?? []),
    row.workload.instance,
    getWorkloadRecoveryPostureLabel(row.posture),
    ...[...(row.latestTask ? [row.latestTask] : []), ...(row.taskCandidates ?? [])].flatMap(
      (task) => [task.label, task.error, task.id, task.instance, task.node],
    ),
    ...row.artifacts.flatMap((artifact) => [
      artifact.nativeId,
      artifact.sourceLabel,
      artifact.sourceTitle,
      artifact.locationConnection || 'unknown connection',
      artifact.location,
      artifact.detail,
      artifact.detailTitle,
    ]),
  ];
  return haystack.filter(Boolean).join(' ').toLowerCase().includes(normalizedTerm);
}

export function recoverableArtifactMatchesSearch(
  artifact: RecoverableArtifact,
  term: string,
): boolean {
  const normalizedTerm = term.trim().toLowerCase();
  if (!normalizedTerm) return true;
  const haystack = [
    artifact.workload.label,
    artifact.workload.name,
    artifact.workload.typeLabel,
    artifact.workload.vmid,
    artifact.workload.node,
    artifact.workload.nativeNode,
    ...(artifact.workload.nativeNodeAliases ?? []),
    artifact.workload.instance,
    artifact.nativeId,
    artifact.sourceLabel,
    artifact.sourceTitle,
    artifact.locationConnection || 'unknown connection',
    artifact.location,
    artifact.detail,
    artifact.detailTitle,
    artifact.verified === true
      ? 'verified'
      : artifact.verified === false
        ? 'unverified'
        : undefined,
    artifact.running ? 'running' : undefined,
    artifact.failed ? 'failed incomplete' : undefined,
    // Keep legacy saved searches while matching the visible retention wording.
    artifact.protected ? 'protected kept pruning' : 'unprotected',
  ];
  return haystack.filter(Boolean).join(' ').toLowerCase().includes(normalizedTerm);
}