Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

60.2 KB
Raw Blame
/**
 * Canonical code-health wire contract — shared by the web dashboard
 * (`packages/web`), the shared UI (`packages/ui`), the hosted frontend, and
 * the bot. Mirrors the server's `routers/code_health.py` response shapes plus
 * the band/distribution "currency" layer.
 *
 * Before this module the health types lived web-locally in
 * `packages/web/src/lib/api/code-health.ts`; they were migrated here so every
 * consumer reads one contract.
 *
 * Band cutoffs are the SINGLE TypeScript mirror of the canonical Python source
 * in `packages/core/src/repowise/core/analysis/health/grading.py`. The two are
 * kept in sync by a parity test (`__tests__/health.test.ts` here,
 * `tests/unit/health/test_grading.py` in core). Do not hardcode band cutoffs
 * anywhere else — derive from these consts or read the API `band`.
 */

import type { C4IoKind } from "./external-systems.js";
import type { CoverageHistoryPoint, CoverageSummary } from "./generated/http.js";
import type { Paginated } from "./pagination.js";
import type { QueueCounts, QueueCountsByUnit } from "./queue.js";
import type {
  StepClassification,
  StepVerify,
  ValidationBasis,
  ValidationVia,
} from "./refactoring.js";

/** Finding severity used across the health surface. */
export type HealthSeverity = "low" | "medium" | "high" | "critical";

/* ------------------------------------------------------------------ *
 * Health dimensions (the three-signal split)
 * ------------------------------------------------------------------ */

/**
 * The orthogonal health signals. `defect` is the historical, calibrated score
 * surfaced as the overall number; `maintainability` is a co-surfaced signal
 * made of the smells the defect calibration floors (they don't predict bugs, so
 * they get a proper home here instead of diluting the defect score);
 * `performance` is the co-surfaced third signal: static performance RISK
 * (I/O-in-loop / N+1 shapes that waste work). All three are co-equal views; the
 * overall number stays the defect score and is never a blend.
 *
 * Mirror of `DIMENSIONS` in
 * `packages/core/src/repowise/core/analysis/health/scoring.py`, kept in sync by
 * a parity test (`__tests__/health.test.ts` here,
 * `tests/unit/health/test_scoring_dimensions.py` in core).
 */
export type ScoredHealthDimension = "defect" | "maintainability" | "performance";

/**
 * The non-scoring fourth dimension. A marker homes here when it measures
 * something no defect corpus labels, so it can never be calibrated and never
 * earns weight. Its findings carry a zero health impact by construction and so
 * are kept out of every impact-ranked queue, describing without accusing. That
 * is about ranking, not existence: a surface that ranks nothing, such as one
 * file's findings in an editor, asks for them and gets them.
 *
 * Mirror of `ADVISORY_DIMENSION` in core's `scoring.py`. Deliberately outside
 * `HEALTH_DIMENSIONS`, which stays exactly the set that carries a score.
 */
export type AdvisoryHealthDimension = "advisory";

/** Every dimension label a finding may carry on the wire, scored or not. */
export type HealthDimension = ScoredHealthDimension | AdvisoryHealthDimension;

/** Canonical SCORED dimension order (parity-locked against core's `DIMENSIONS`). */
export const HEALTH_DIMENSIONS: readonly ScoredHealthDimension[] = [
  "defect",
  "maintainability",
  "performance",
] as const;

/** The dimension whose findings never move a number. */
export const ADVISORY_DIMENSION: AdvisoryHealthDimension = "advisory";

/**
 * What a code-health figure counts. `everything` is the calibrated score;
 * `code_shape` removes the git-derived half, which rises as a file is worked
 * on and so answers what a repository has been through rather than what its
 * code is like.
 */
export type HealthCounts = "everything" | "code_shape";
export const HEALTH_COUNTS: readonly HealthCounts[] = ["everything", "code_shape"] as const;

/**
 * Which half of a repository a health figure describes. Tests score higher
 * than production code, so narrowing lowers every figure without a defect
 * having been found — `all` is the default for that reason.
 */
export type HealthScope = "all" | "production";

export const HEALTH_SCOPES: readonly HealthScope[] = ["all", "production"] as const;

/** Display labels for the dimensions surfaced today. */
export const HEALTH_DIMENSION_LABEL: Record<HealthDimension, string> = {
  defect: "Code health",
  maintainability: "Maintainability",
  performance: "Performance",
  advisory: "Advisory",
};

/**
 * Human-readable labels for the I/O-boundary kind a performance finding crosses
 * (the `boundary_kind` on an `io_in_loop` finding's `details`). The kind set is
 * the canonical `C4IoKind` from `external-systems.ts`, parity-locked against the
 * Python `IO_KINDS` classifier; this only adds display strings, no new wire
 * enum. Used to render "a database call runs once per loop iteration" detail.
 */
export const PERF_BOUNDARY_LABEL: Record<C4IoKind, string> = {
  db: "Database",
  network: "Network",
  filesystem: "Filesystem",
  subprocess: "Subprocess",
  lock: "Lock",
};

/* ------------------------------------------------------------------ *
 * Band "currency" layer
 * ------------------------------------------------------------------ */

/**
 * The five absolute health bands: a score means the same thing behind a
 * firewall as against a public corpus. Excellent and Good share one green and
 * are told apart by the word. Mirror of `grading.py`, parity-tested both ways.
 */
export type HealthBand = "excellent" | "good" | "fair" | "needs_work" | "at_risk";

export const EXCELLENT_MIN = 8.5;
export const GOOD_MIN = 7.0;
export const FAIR_MIN = 5.5;
export const NEEDS_WORK_MIN = 4.0;

/**
 * The canonical three-band reading beside a health mark: Healthy at 8 or
 * above, Warning from 4, Alert below 4 (`NEEDS_WORK_MIN`).
 */
export const HEALTHY_MIN = 8.0;

/** Worst-first, matching how the surfaces list files. */
export const HEALTH_BAND_ORDER: readonly HealthBand[] = [
  "at_risk",
  "needs_work",
  "fair",
  "good",
  "excellent",
] as const;

export const HEALTH_BAND_LABEL: Record<HealthBand, string> = {
  excellent: "Excellent",
  good: "Good",
  fair: "Fair",
  needs_work: "Needs work",
  at_risk: "At risk",
};

/** The range each band covers, for keys and legends that show the boundaries. */
export const HEALTH_BAND_RANGE_LABEL: Record<HealthBand, string> = {
  excellent: "8.5+",
  good: "7.0 to 8.5",
  fair: "5.5 to 7.0",
  needs_work: "4.0 to 5.5",
  at_risk: "under 4.0",
};

/** The lowest score a file can show. Mirror of `SCORE_FLOOR` in core scoring. */
export const SCORE_FLOOR = 1.0;

/**
 * Pure score -> band mapping. Mirror of `grading.band_for` in core. Prefer the
 * API-provided `band` where available; use this only when deriving locally.
 */
export function bandForScore(score: number): HealthBand {
  if (score >= EXCELLENT_MIN) return "excellent";
  if (score >= GOOD_MIN) return "good";
  if (score >= FAIR_MIN) return "fair";
  if (score >= NEEDS_WORK_MIN) return "needs_work";
  return "at_risk";
}

/** The two bands below Fair: where a surface calls health weak. */
export function isWeakHealthBand(band: HealthBand): boolean {
  return band === "needs_work" || band === "at_risk";
}

/**
 * A 1-10 score at one decimal, rounded down, for display beside its band.
 * Rounding to nearest would print 6.98 as "7.0" beside "Fair"; flooring can
 * never cross a band edge, and the band itself stays on the unrounded value.
 * Mirror of `grading.format_score` in core.
 */
export function formatScore(score: number): string {
  const nearest = Number(score.toFixed(1));
  return (nearest > score ? nearest - 0.1 : nearest).toFixed(1);
}

export interface HealthBandShare {
  /** Number of files in this band. */
  files: number;
  /** Sum of NLOC across the files in this band. */
  nloc: number;
  /** NLOC-weighted share of the repo in this band, 0-100. */
  pct: number;
}

/**
 * NLOC-weighted distribution of files across the bands. The repo-level
 * "health distribution" surfaced on the dashboard + badge.
 */
export interface HealthDistribution {
  total_files: number;
  total_nloc: number;
  bands: Record<HealthBand, HealthBandShare>;
}

/* ------------------------------------------------------------------ *
 * Defect-accuracy ("does the score find the bugs?") — migrated from
 * packages/ui so the overview response can reference it without ui depending
 * back into web. `packages/ui` re-exports these for component prop typing.
 * ------------------------------------------------------------------ */

export interface DefectAccuracyFile {
  file_path: string;
  score: number;
  recent_fixes: number;
}

export interface DefectAccuracyPoint {
  k: number;
  hits: number;
}

export interface DefectAccuracy {
  k: number;
  hits: number;
  precision: number;
  base_rate: number;
  lift: number | null;
  window_days: number;
  scored_files: number;
  defect_files: number;
  concentration_file_fraction: number;
  concentration_defect_share: number;
  precision_table: DefectAccuracyPoint[];
  flagged_files: DefectAccuracyFile[];
}

/* ------------------------------------------------------------------ *
 * Core file/finding/module rows
 * ------------------------------------------------------------------ */

export interface HealthFileMetric {
  file_path: string;
  /**
   * `null` when health has no dialect for the file's language: nothing
   * measured it, so it has no score and no complexity figures. Render it as
   * "not analysed", never as a number. Older servers always send a number.
   */
  score: number | null;
  max_ccn: number | null;
  max_nesting: number | null;
  nloc: number;
  has_test_file: boolean;
  line_coverage_pct: number | null;
  module: string | null;
  duplication_pct?: number | null;
  /**
   * Per-dimension scores from the three-signal split. `score` stays the overall
   * surfaced number (== `defect_score` until a deliberate blend decision).
   * `maintainability_score` is the co-surfaced second signal;
   * `performance_score` is computed but not yet surfaced as its own pillar
   * (`null` on payloads that predate the performance detectors). All optional so
   * older payloads parse unchanged.
   */
  defect_score?: number | null;
  maintainability_score?: number | null;
  performance_score?: number | null;
  /**
   * The defect deduction split into the half a rewrite can move (code shape)
   * and the half only time can (git history). They sum to the total deduction,
   * so `unclamped_score` is `10 - structure - history` — the only number that
   * moves for a file held at the score floor. Absent on older payloads.
   */
  structure_deduction?: number | null;
  history_deduction?: number | null;
  unclamped_score?: number | null;
  /**
   * `"short"`: too few recorded commits for most history markers to fire, so a
   * high score is an absent history rather than a clean one. Omitted otherwise
   * and on `fields=summary` rows.
   */
  history?: "short" | null;
  /**
   * Test material, decided at ingestion. Drives the production/all scope
   * without re-deriving the answer from the path on every surface.
   */
  is_test?: boolean;
  /**
   * Where the file's code comes from (`production`, `test`, `vendored`,
   * `generated`, `docs_example`, `tooling`, `build`). `null` on rows scored
   * before the column existed; absent on payloads that do not carry it.
   */
  code_origin?: string | null;
  /**
   * @deprecated Open performance findings on this file, as payloads from the
   * previous release carry them. Read `performance_opportunities` instead.
   */
  performance_findings?: number | null;
  /**
   * Whether a performance detector actually ran on this file (its language has a
   * registered perf dialect). `false` = unsupported language, the perf pass never
   * looked — a silent 10.0 — so the map greys the file as "not analyzed" instead
   * of green. High-precision / low-recall: green means "a detector ran and
   * surfaced nothing", never "verified fast". `null`/absent on older payloads.
   */
  performance_analyzed?: boolean | null;
  /**
   * Open causal opportunities on this file, and the observations behind them.
   * The map's performance lens sizes its pressure ring by the opportunity
   * count, because an opportunity is one thing a reader could go and do while
   * an observation is one place a detector looked. Absent on payloads from a
   * server that serves no materialized read model, which the lens renders as
   * an unknown state rather than as zero.
   */
  performance_opportunities?: number | null;
  performance_observations?: number | null;
  /**
   * Best available next step on this file: a stored plan outranks an advisory
   * intervention, which outranks an investigation. `null` when the file
   * carries no open opportunity. Never a claim about runtime magnitude.
   */
  performance_actionability?: PerformanceActionabilityState | null;
  /** Best (lowest) queue rank position among this file's opportunities. */
  performance_rank?: number | null;
  /**
   * Dominant-cause lead: the biomarker + reason of this file's worst finding, so
   * a low file can headline "the one reason" instead of a wall of markers. Null
   * when the row carries no findings or the payload predates this field.
   */
  primary_biomarker?: string | null;
  primary_reason?: string | null;
  /**
   * Summed (pre-floor) `health_impact` across the file's findings — the score's
   * deduction magnitude. Distinguishes two files that both clamp to `1.0` (a −25
   * from a −9) so they can be ranked by depth. The calibrated `score` is
   * unchanged; this is a display-only secondary distinguisher.
   */
  total_deduction?: number | null;
  /** Git flags this file a hotspot (heavy recent change). Map feed only; absent on older servers. */
  is_hotspot?: boolean;
}

export interface HealthFinding {
  id: string;
  file_path: string;
  biomarker_type: string;
  severity: HealthSeverity;
  function_name: string | null;
  line_start: number | null;
  line_end: number | null;
  health_impact: number;
  reason: string;
  details: Record<string, unknown>;
  status: string;
  /** Matching symbol id when the finding names a function; links to the symbol page. */
  symbol_id?: string | null;
  /**
   * The finding's "home" health dimension (`defect` / `maintainability` /
   * `performance`), used to filter findings by pillar. Optional/`defect` when an
   * older payload omits it.
   */
  dimension?: HealthDimension;
  /** `"unverified"` for a provisional finding type, shown because it was asked
   *  for by name. Null or absent for a validated type. */
  verification?: string | null;
  /** Why the finding can wait ("lower priority: ..."); null when it is worth
   *  doing first. Lower-priority findings are listed after the rest. */
  lower_priority?: string | null;
  /** The measurement note when the row's language cell is served as a preview;
   *  null or absent for a validated cell. */
  preview?: string | null;
}

export type PerformanceExecutionContext = "production" | "tooling" | "test" | "unknown";

/**
 * What runs a cause's loop (`execution_roles.EXECUTION_ROLES`). `unknown` means
 * no request, job, startup or CLI seed reaches it, not that nothing does.
 */
export const PERFORMANCE_EXECUTION_ROLES = [
  "request",
  "event_consumer",
  "scheduled_job",
  "startup",
  "cli",
  "ui",
  "tooling",
  "test",
  "unknown",
] as const;
export type PerformanceExecutionRole = (typeof PERFORMANCE_EXECUTION_ROLES)[number];
export type PerformanceOpportunityConfidence = "high" | "medium" | "low";

export interface PerformanceOpportunityFix {
  strategy: string;
  safety: "proven" | "advisory";
  rationale: string;
  /** The concrete construct the edit uses (a bulk call, a bound), when one was found. */
  api?: string;
}

export interface PerformanceOpportunityEvidence {
  finding_id: string;
  file_path: string;
  biomarker_type: string;
  function_name: string | null;
  line_start: number | null;
  line_end: number | null;
  reason: string;
  path: string[];
  provenance: string;
}

export type PerformanceActionabilityState = "plan_ready" | "advisory" | "investigate" | "expected";
export type PerformancePlanStatus = "available" | "no_safe_plan" | "not_persisted";

/** One rank term, the input it read, and the points it contributed. */
export interface PerformanceWhyRanked {
  factor: string;
  value: string | number | boolean | null;
  points: number;
}

/**
 * Whether the loop's trip count grows with data, read off every member of the
 * group. `n/a` is for markers whose amplification is not per_iteration or
 * quadratic, so there is no loop to measure.
 */
export type PerformanceLoopMagnitude = "grows_with_data" | "bounded" | "unknown" | "n/a";

/**
 * Which member loop shows the cost grows: `loop` one outside a registry and a
 * cold path, `registry` only loops over a registry or configuration table,
 * `cold_path` only migration, startup or recovery loops, `none` no loop grows.
 */
export type PerformanceGrowthSource = "loop" | "registry" | "cold_path" | "none" | "n/a";

/**
 * The facets that are not published anywhere else on the row.
 * `confidence` stays evidence confidence and `fix.safety` stays fix safety,
 * so no value appears twice.
 */
export interface PerformanceOpportunityFacets {
  actionability_confidence: PerformanceOpportunityConfidence;
  exposure: string;
  amplification: string;
  leverage: string;
  change_risk: string;
  /** Absent on rows stored before the fact existed. */
  loop_magnitude?: PerformanceLoopMagnitude;
  /** Absent on rows stored before the fact existed. */
  growth_source?: PerformanceGrowthSource;
  /** Absent on rows stored before the fact existed. */
  execution_role?: PerformanceExecutionRole;
}

/**
 * Another cause observed on the same source lines. `relation` is from this
 * opportunity's own view: `preferred` means the sibling's fix is the
 * stronger one, `alternative` means this one is, `same_site` is no
 * preference either way.
 */
export interface PerformanceOpportunitySibling {
  opportunity_id: string;
  biomarker_type: string;
  strategy: string | null;
  relation: "preferred" | "alternative" | "same_site";
}

/** How to validate a stored plan. Shares its vocabulary with refactoring's
 *  `RecommendationValidation`, trimmed to the fields the queue materializes. */
export interface PerformanceOpportunityValidation {
  basis: ValidationBasis;
  via: ValidationVia | null;
  total: number;
  tests: string[];
  /** Why each test is listed, keyed by test id. Null on a store written before it. */
  reasons?: Record<string, string> | null;
  commands: string[];
}

/** One ordered edit in a stored plan. */
export interface PerformanceOpportunityPlanStep {
  order: number;
  action: string;
  symbol: string | null;
  file_path: string | null;
  line: number | null;
  applicability: StepClassification;
  /** How to check this step, when it differs from the plan's validation.
   *  Absent: the plan's validation checks it. */
  verify?: StepVerify;
}

/** Ranking inputs behind a plan, not a cost/benefit ledger. */
export interface PerformanceOpportunityPlanEconomics {
  effort_bucket: string;
  benefit: number;
  cost: number;
  risk: number;
}

export interface PerformanceOpportunity {
  opportunity_id: string;
  /** Ids are stable within a model version and never translated across one. */
  performance_model_version: number;
  biomarker_type: string;
  biomarker_types: string[];
  boundary_kind: C4IoKind | null;
  execution_context: PerformanceExecutionContext;
  /** The one sink every observation reaches, else null; see `terminal_sinks`. */
  terminal_sink: string | null;
  /** Every sink the intervention's observations reach. Absent on an older store. */
  terminal_sinks?: string[];
  shared_path_suffix: string[];
  /** Where to edit. Named on every row from model 3 (`path::__module__` for
   *  top-level code); null only on an older store. */
  intervention_symbol: string | null;
  /** The loop's function, a helper every caller shares, or top-level code. */
  intervention_kind?: "function" | "shared_helper" | "module";
  /** The file holding the symbol worth editing. */
  file_path: string;
  resource_fingerprints: string[];
  affected_call_sites_total: number;
  affected_files_total: number;
  observations_total: number;
  evidence: PerformanceOpportunityEvidence[];
  evidence_truncated: boolean;
  evidence_total: number;
  evidence_emitted: number;
  /** Offset for the next evidence page, absent once the last one is emitted. */
  evidence_next_cursor?: number;
  reliable_entry_reachability: boolean | null;
  provenance: string;
  /** Evidence confidence: how reliably the call path resolved. */
  confidence: PerformanceOpportunityConfidence;
  facets: PerformanceOpportunityFacets;
  /** What fixing this cause buys, in the words Fix first uses. Absent on an older server. */
  gain_text?: string;
  actionability_state: PerformanceActionabilityState;
  actionability_reason: string;
  prerequisites: string[];
  rank_score: number;
  /** 0-based place in the ranked list that served the row; another sort or a
   *  lookup by id gives its rank among every cause in the repository. */
  rank_position: number;
  rank_factors: Record<string, number>;
  why_ranked: PerformanceWhyRanked[];
  fix: PerformanceOpportunityFix | null;
  /** Whether this cause may lead the dashboard. False for a marker below the
   *  leading bar (lazy loads outside Django). Absent on an older store. */
  may_lead?: boolean;
  /** Why the opportunity can wait ("lower priority: ..."); null when its
   *  production loop is known to grow with the data. */
  lower_priority?: string | null;
  /** The measurement note when the row's language cell is served as a preview;
   *  null or absent for a validated cell. */
  preview?: string | null;
  /** Exact stored match. Never inferred from file, marker, or rank. */
  plan_id: string | null;
  plan_status: PerformancePlanStatus;
  plan_reason: string;
  /** Other causes flagged on the same lines. Always present (may be empty) on
   *  new stores; absent on payloads from an older store. */
  siblings?: PerformanceOpportunitySibling[];
  /** How to validate the stored plan. Absent when there is no stored plan. */
  validation?: PerformanceOpportunityValidation;
  /** Ordered edits for the stored plan. Absent when there is no stored plan. */
  plan_steps?: PerformanceOpportunityPlanStep[];
  /** Ranking inputs behind the stored plan, not a verdict. */
  plan_economics?: PerformanceOpportunityPlanEconomics;
}

/** Whether a quoted id still names something this index can resolve. */
export interface PerformanceModelState {
  state: "current" | "stale_model" | "unrecognized";
  opportunity_id: string;
  requested_model_version: number | null;
  performance_model_version: number;
  refresh_required: boolean;
}

/**
 * One opportunity by id. An unresolved id still answers, with the model state
 * and what to do about it, rather than reading as "nothing to fix here".
 */
export type PerformanceOpportunityDetail =
  | ({
      found: true;
      lifecycle_status: "open" | "resolved";
      analyzed_commit: string | null;
      model_state: PerformanceModelState;
      evidence_total: number;
      evidence_emitted: number;
      evidence_next_cursor?: number;
    } & PerformanceOpportunity)
  | {
      found: false;
      opportunity_id: string;
      model_state: PerformanceModelState;
      detail: string;
    };

/**
 * Counts per value for one filter, computed from the base result rather than
 * the filtered one, so selecting a value never erases its own alternatives.
 * A value with no rows is absent rather than reported as zero.
 */
export interface PerformanceFacetCount {
  value: string;
  total: number;
}

/**
 * The filters the server owns. Every key except `plan_state` is also a query
 * parameter; plan state is counted per value but is not something the queue
 * narrows by.
 */
export type PerformanceFacetKey =
  | "context"
  | "boundary"
  | "confidence"
  | "actionability"
  | "plan_state"
  | "proof"
  | "role";

/**
 * Whether anything measured that a cause's cost grows with the data
 * (`eligibility.QUEUE_PROOFS`). The queue holds `proven` causes unless asked
 * for another value. `background_unproven` is a scheduled job whose loop is
 * not shown to grow; neither unproven kind leads.
 */
export type PerformanceCostProof = "proven" | "unproven" | "background_unproven";

export type PerformanceFacets = Partial<Record<PerformanceFacetKey, PerformanceFacetCount[]>>;

/** `all` widens the context filter; the four contexts stay separate under it. */
export type PerformanceContextFilter = PerformanceExecutionContext | "all";

/**
 * The query the server answers, shared by the REST client and the views.
 * An alias rather than an interface so a client can hand it to a generic
 * query-parameter helper without restating every field.
 */
export type PerformanceOpportunityQuery = {
  /**
   * Canonical contexts. `production_tooling` is a retired spelling an older
   * server still answers as Production+Tooling. It is never returned as a
   * context, so only a legacy-compatibility path should send it.
   */
  context?: PerformanceContextFilter | "production_tooling";
  boundary?: string;
  /** Evidence confidence, requested apart from fix safety and actionability. */
  confidence?: PerformanceOpportunityConfidence;
  /** Absent means the default queue's states; `all` lifts them. */
  actionability?: PerformanceActionabilityState | "all";
  /** Absent means `proven`; `unproven` lists the causes the default queue leaves out;
   *  `all` lifts the proof filter. */
  proof?: PerformanceCostProof | "all";
  /** Keep to the default queue's stored verdict whatever state is chosen (REST only). */
  queue?: boolean;
  /** One area (a directory) at any depth (REST only). */
  area?: string;
  /** Group the area facet at this directory depth; absent lets the server choose (REST only). */
  area_depth?: number;
  /** Absent means every role but startup, cli, ui, tooling and test; `all` lists every role. */
  role?: PerformanceExecutionRole | "all";
  /** `summary` drops the explanatory fields and keeps identity and counts. */
  view?: "detail" | "summary";
  sort?: "rank" | "leverage" | "observations";
  /**
   * Scope to the opportunities whose intervention lives in these files. This
   * is how a file-scoped surface asks the queue about one file instead of
   * filtering a page it already narrowed.
   */
  file_paths?: string[];
  limit?: number;
  offset?: number;
};

/** Why the default queue leaves a cause out (`queue.eligibility.DEFAULT_QUEUE_EXCLUSIONS`). */
export type PerformanceQueueExclusion =
  | "test"
  | "tooling"
  | "unknown"
  | "gated_off"
  | "cold_path"
  | "expected"
  | "no_strategy"
  | "unmeasured_cost"
  | "cold_role"
  | "background_unproven";

export interface PerformanceDefaultQueue {
  total: number;
  /** Per reason; a server that predates a reason leaves it out. */
  excluded: Partial<Record<PerformanceQueueExclusion, number>>;
}

/**
 * A layer held back pending verification on a language is left out on files
 * of that language unless the caller opts in (`include_unverified`). Keyed by
 * language tag (`java`, `csharp`, `c`, `cpp`, `kotlin`, `swift`); `reason`
 * is the sentence to show.
 */
export type GatedByLanguage = Record<string, { count: number; reason: string }>;

export interface PerformanceOpportunitySummary {
  /** `current` once materialized, `stale_model` after a model bump, or
   * `unavailable` when this index has not been analyzed yet. */
  status: "current" | "stale_model" | "unavailable";
  /** Causes in the selected context. Equal to `repository_total` under `all`. */
  total: number;
  /** Causes in every context, so a scoped headline never hides the census.
   * Absent from a server that predates context scoping, whose `total` is
   * already the repository-wide count. */
  repository_total?: number;
  performance_model_version?: number;
  /** The model the stored rows were written by, when it trails the current one. */
  materialized_model_version?: number;
  analyzed_commit?: string | null;
  actionability?: Partial<Record<PerformanceActionabilityState, number>>;
  context?: Partial<Record<PerformanceExecutionContext, number>>;
  boundary?: Record<string, number>;
  /** Causes by cost proof; `unproven` ones sit outside the default queue. Absent on an older store. */
  proof?: Partial<Record<PerformanceCostProof, number>>;
  with_plan_total: number;
  /** The queue a caller gets with no filter (production work with a strategy),
   *  and how many causes it leaves out per reason. Absent on an older store. */
  default_queue?: PerformanceDefaultQueue;
  /** Why the queue is not current, when it is not. */
  reason?: string;
  detail?: string;
  /** What a language gate held back, by language. Empty or absent when nothing was. */
  gated?: GatedByLanguage;
}

/** The dashboard's three scopes: the default queue, every production cause, everything. */
export type PerformanceScope = "now" | "production" | "all";

/** One area of the queried causes, with its actionability split. */
export interface PerformanceAreaFacetEntry {
  area: string;
  total: number;
  /** The opened area's (or the root's) own files: opening it again narrows nothing. */
  own?: boolean;
  actionability: Partial<Record<PerformanceActionabilityState, number>>;
}

/** The queried causes by area, over the whole scope and filters, not one page. */
export interface PerformanceAreaFacet {
  /** The directory depth the areas are drawn at. */
  depth: number;
  /** Ranked by plan-ready causes, then advisory, then size. */
  items: PerformanceAreaFacetEntry[];
  /** Causes in areas past the response's limit. */
  more: number;
  total: number;
}

export interface PerformanceOpportunityPage extends Paginated<PerformanceOpportunity> {
  summary: PerformanceOpportunitySummary;
  /** Counted inside the requested scope and filters on the REST queue, so a
   *  facet with no own selection sums to `total`. */
  facets: PerformanceFacets;
  /** Causes per scope, unfiltered. Absent from a server that predates scopes. */
  scopes?: Partial<Record<PerformanceScope, number>>;
  /** The causes by area. Absent from a server that predates it. */
  areas?: PerformanceAreaFacet;
  /** What a language gate held back, by language. Empty or absent when nothing was. */
  gated?: GatedByLanguage;
  /** Filter values the server did not recognize, named rather than dropped. */
  ignored_arguments?: Record<string, string>;
  /** The causes' count vocabulary over the open inventory in the queried files. */
  counts?: QueueCounts;
}

export interface HealthModuleRow {
  module: string;
  file_count: number;
  nloc: number;
  average_health: number;
  worst_performer_path: string;
  worst_performer_score: number;
}

export interface BiomarkerBreakdownRow {
  biomarker_type: string;
  critical: number;
  high: number;
  medium: number;
  low: number;
  total: number;
}

/* ------------------------------------------------------------------ *
 * Overview
 * ------------------------------------------------------------------ */

/**
 * The performance headline every surface prints, in the Performance view's
 * three scopes: `now` (the default queue, worth fixing now) leads, and
 * `production` and `all` open causes give it context.
 */
export interface PerformanceCauses {
  now: number;
  production: number;
  all: number;
  /** Every open cause per 10K lines a performance detector ran on. */
  per_10k_loc: number | null;
}

export interface HealthOverviewSummary {
  file_count: number;
  /** `null` when no file is scored: every file is in a language health has no
   *  dialect for. */
  average_health: number | null;
  /** Files left out of every figure here because health has no dialect for
   *  their language. Absent on an older server. */
  unanalysed_file_count?: number;
  /** Scored files over all code files, 0-1; `null` with no code files. Absent
   *  on an older server. */
  analysed_share?: number | null;
  hotspot_health?: number | null;
  worst_performer_path: string | null;
  worst_performer_score: number | null;
  /** The lowest-scoring test file, ranked apart from production files. Null
   *  without test files; absent on an older server. */
  worst_test_path?: string | null;
  worst_test_score?: number | null;
  open_findings: number;
  severity_breakdown?: {
    critical: number;
    high: number;
    medium: number;
    low: number;
  };
  /** Repo-level band derived from `average_health` (added in the band/distribution layer).
   *  `null` when no file is scored or too few code files were analysed to grade
   *  the repo; absent on an older server. */
  band?: HealthBand | null;
  /**
   * NLOC-weighted repo headline for the maintainability pillar (the second
   * surfaced signal). `null`/absent when no file carries a maintainability
   * score. `maintainability_hotspot` is the same average restricted to hotspot
   * files, when available.
   */
  maintainability_average?: number | null;
  maintainability_hotspot?: number | null;
  /**
   * NLOC-weighted repo headline for the performance pillar (the third surfaced
   * signal: static performance RISK, not measured runtime). `null`/absent when
   * no file carries a performance score. `performance_hotspot` is the same
   * average restricted to hotspot files, when available.
   */
  performance_average?: number | null;
  performance_hotspot?: number | null;
  /** Open findings homing under the maintainability pillar. Absent on payloads
   *  predating the split. */
  maintainability_findings?: number;
  /** Open performance causes, as every surface counts them; `null` with no files. */
  performance_causes?: PerformanceCauses | null;
  /**
   * @deprecated Every open performance finding, as payloads from the previous
   * release carry it. The lede shows it only when `performance_causes` is absent.
   */
  performance_findings?: number;
  /** Lowest-scoring file by performance risk, surfaced only when score < 10
   *  (a clean repo returns `null` rather than a misleading "worst" at 10.0). */
  worst_performance_path?: string | null;
  worst_performance_score?: number | null;
  /**
   * `average_health`'s two halves, in deduction points: what the code's own
   * shape costs, and what its git history costs. They sum to the total
   * deduction, so ten minus both is the unclamped score. `null`/absent until
   * the rows carry the split.
   */
  structure_average?: number | null;
  history_average?: number | null;
  /** What this response counted. Echoed so a label cannot get ahead of its data. */
  counts?: HealthCounts;
  /** Files a code-shape reading cannot answer for, having no recorded split. */
  unscored_files?: number;
  /** What a language gate held back, by language. Empty or absent when nothing was. */
  gated?: GatedByLanguage;
}

export interface HealthOverviewResponse {
  summary: HealthOverviewSummary;
  /** NLOC-weighted file distribution across the health bands. */
  distribution?: HealthDistribution | null;
  defect_accuracy?: DefectAccuracy | null;
  files: HealthFileMetric[];
  top_findings: HealthFinding[];
  modules?: HealthModuleRow[];
  biomarkers?: BiomarkerBreakdownRow[];
  /** Every queue unit's counts, unprojected by the page's scope or counts. */
  queue_counts?: QueueCountsByUnit;
  meta?: {
    last_indexed_at: string | null;
    head_commit: string | null;
    snapshot_count: number;
  };
}

/* ------------------------------------------------------------------ *
 * Files list
 * ------------------------------------------------------------------ */

export interface HealthFilesResponse {
  total: number;
  offset: number;
  limit: number;
  files: HealthFileMetric[];
}

export interface HealthFilesQuery {
  counts?: HealthCounts;
  /** Which half of the repository to describe. Defaults to `"all"`. */
  scope?: HealthScope;
  limit?: number;
  offset?: number;
  sort?: string;
  order?: "asc" | "desc";
  search?: string;
  module?: string;
  only_hotspots?: boolean;
  only_untested?: boolean;
  only_failing?: boolean;
  /**
   * `"summary"` returns rows without the optional keys only the file table and
   * drawer read — `duplication_pct`, `defect_score`, and the
   * `primary_biomarker` / `primary_reason` / `total_deduction` lead — and lets
   * the server skip the repo-wide finding read that produces the lead. Measured
   * on the code-health map's 2,000-row request: 1,060,095 B -> 628,014 B.
   * Every omitted key is optional on {@link HealthFileMetric}, so a `summary`
   * row parses as one; ask for `"full"` (the default) if you print any of them.
   */
  fields?: "full" | "summary";
}

/* ------------------------------------------------------------------ *
 * Map feed
 * ------------------------------------------------------------------ */

/**
 * How the server chose the drawn field.
 *
 * `active_then_performance_then_nloc`: the caller's guaranteed paths first,
 * then the files carrying open performance opportunities in rank order, then
 * lines-of-code descending for whatever capacity is left. Ranking the whole
 * repository by size alone is a defensible sample for the health lens and the
 * wrong one for performance, because a small file can hold the worst cause.
 */
export type HealthMapSelectionBasis =
  | "active_then_performance_then_nloc"
  /**
   * The pins, then a floor of two files per module, then everything else by
   * origin tier (production, tooling and build, test, docs examples) with open
   * performance causes leading each tier and a health-debt rank after them.
   * Vendored and generated files are held out unless `include_held` is set.
   */
  | "active_then_module_floor_then_origin_tier_then_performance_then_debt";

export interface HealthMapSelection {
  basis: HealthMapSelectionBasis;
  /** Paths the caller asked to pin, in the order they were asked for. */
  active_requested: string[];
  active_shown: string[];
  /** Requested paths with no drawable metric row, so nothing pretends they are there. */
  active_missing: string[];
  performance_shown: number;
  performance_eligible: number;
  nloc_shown: number;
  /** Files the per-module floor admitted. Absent on older servers. */
  module_floor_shown?: number;
  /** The search substring the field pinned matches for, or `null`. */
  query?: string | null;
  /** Eligible files whose path contains the query, drawn or not. */
  query_matches?: number;
  /** Matches the query pinned into the field (bounded). */
  query_shown?: number;
  /** Whether vendored and generated files were admitted. */
  include_held?: boolean;
}

/** What the cap pushed out, in the units a reader would ask about. */
export interface HealthMapOmissions {
  files: number;
  performance_files: number;
  opportunities: number;
  observations: number;
  /**
   * Drawable vendored and generated files held out of the field (not counted
   * in `files`). Absent on servers that do not hold them out.
   */
  held?: number;
}

export interface HealthMapModuleRollup {
  module: string;
  files_shown: number;
  opportunities: number;
  observations: number;
  plan_ready: number;
  /** Best queue rank in the module, or `null` when it carries no opportunity. */
  best_rank: number | null;
}

/** Repository-wide performance state the lens needs to describe itself. */
export interface HealthMapPerformance {
  files_with_opportunities: number;
  files_with_opportunities_eligible: number;
  opportunities_total: number;
  observations_total: number;
  actionability: {
    plan_ready: number;
    advisory: number;
    investigate: number;
  };
  model_version: number | null;
  analyzed_commit: string | null;
}

/**
 * The bounded field the map draws, plus the exact scope of what it leaves out.
 *
 * The rendered set and the counts describing it come from one response, so a
 * caption can never disagree with the field beside it.
 */
export interface HealthMapFeed {
  /** The directory the field is narrowed to; `null` for the whole repository. Absent on older servers. */
  area?: string | null;
  files: HealthFileMetric[];
  cap: number;
  shown: number;
  /** Files that could be drawn at all: a zero-NLOC file cannot be sized. */
  eligible_total: number;
  repository_total: number;
  selection: HealthMapSelection;
  omitted: HealthMapOmissions;
  recovery: Record<string, string>;
  modules: HealthMapModuleRollup[];
  /** `null` when this index has never materialized the performance read model. */
  performance: HealthMapPerformance | null;
}

export interface HealthMapQuery {
  counts?: HealthCounts;
  cap?: number;
  /** Paths guaranteed a node, admitted before any other band. */
  active?: string[];
  /** Which half of the repository to describe. Defaults to `"all"`. */
  scope?: HealthScope;
  /** Also draw vendored and generated files. */
  include_held?: boolean;
  /** Pin files whose path contains this substring. */
  q?: string;
  /** Narrow the field to this directory; the cap and every count then describe it. */
  area?: string;
  /** `map` leaves out the origins the area map holds by default. */
  hold?: "none" | "map";
  /** With `hold: "map"`, held origins to bring back. */
  include?: readonly string[];
}

/* ------------------------------------------------------------------ *
 * File breakdown (score drill-down)
 * ------------------------------------------------------------------ */

export interface FileBreakdownFinding {
  id: string;
  biomarker_type: string;
  severity: HealthSeverity;
  raw_impact: number;
  applied_impact: number;
  function_name: string | null;
  reason: string;
}

export interface FileBreakdownCategory {
  category: string;
  cap: number;
  raw_deduction: number;
  applied_deduction: number;
  capped: boolean;
  finding_count: number;
  findings: FileBreakdownFinding[];
}

export interface HealthFileBreakdownResponse {
  file_path: string;
  /** What a language gate held back, by language. Empty or absent when nothing was. */
  gated?: GatedByLanguage;
  metric: HealthFileMetric | null;
  /** `null` for a file with no score (no health dialect for its language). */
  breakdown: {
    score: number;
    total_deduction: number;
    categories: FileBreakdownCategory[];
  } | null;
  findings: HealthFinding[];
  suggestions: Record<string, string>;
  /** Per-file score trajectory (silent when history is thin). */
  trend?: FileHealthTrend | null;
  /** Process / people / topology signals (null fields read "no signal"). */
  signals?: FileSignals | null;
}

/* ------------------------------------------------------------------ *
 * Per-file signals (process / people / topology)
 * ------------------------------------------------------------------ */

/**
 * The per-file signals we already compute and persist, consolidated into one
 * captioned contract. Every field is `null` when its source row is absent so
 * consumers render an honest "no signal" rather than a misleading zero — a
 * git-tracked file with no bug-fixes reports `prior_defect_count: 0`, whereas
 * a file with no git history reports `null` for the whole process/people group.
 * `change_entropy_pct` is on a 0-100 scale (the stored column is 0-1).
 * Topology degree is `null` when the file is not a graph node.
 */
export interface FileSignals {
  // Process — how the file changes over time.
  prior_defect_count: number | null;
  change_entropy_pct: number | null;
  lines_added_90d: number | null;
  lines_deleted_90d: number | null;
  commit_count_90d: number | null;
  age_days: number | null;
  // People — who owns it recently vs over its whole life.
  primary_owner_name: string | null;
  primary_owner_commit_pct: number | null;
  recent_owner_name: string | null;
  recent_owner_commit_pct: number | null;
  // Topology — how connected it is in the dependency graph.
  in_degree: number | null;
  out_degree: number | null;
  // Defect history — how often this file gets bug-fixed, and where in it.
  // `bug_magnet` is the decayed fix mass past its trigger, so it is a recency
  // claim: any copy that shows it must show `last_fix_at` too.
  // `fix_symbol_counts` maps symbol_id to how many recent fixes landed in it,
  // top few only, already sorted by count.
  bug_magnet: boolean | null;
  last_fix_at: string | null;
  fix_symbol_counts: Record<string, number> | null;
  // "short": too few recorded commits for most history markers to fire.
  history?: "short" | null;
}

/* ------------------------------------------------------------------ *
 * Per-file trajectory
 * ------------------------------------------------------------------ */

/** One file's score at one snapshot. */
export interface FileTrendPoint {
  taken_at: string | null;
  score: number;
  /**
   * `score` with the 1.0 floor undone, so a file too deep to move the visible
   * score still has a line that moves. Equal to `score` unless the snapshot
   * recorded the file's real depth, which only happens once it is on the
   * floor; may go below 0. Optional: the hosted backend does not send it, and
   * neither do rows written before deductions were captured.
   */
  unclamped_score?: number;
}

/**
 * A single file's score-over-time series plus the deltas worth surfacing.
 * `points` is oldest-first and **empty when fewer than two snapshots carry
 * the file** — consumers render a "no history yet" state rather than a
 * misleading single dot. `current`/`previous`/`delta`/`declining` are null/
 * false in that case. `snapshot_count` is the whole repo window size, so a
 * young repo is distinguishable from a file absent in older snapshots.
 */
export interface FileHealthTrend {
  file_path: string;
  points: FileTrendPoint[];
  current: number | null;
  previous: number | null;
  delta: number | null;
  /**
   * Movement in the unclamped score between the last two points. Equal to
   * `delta` whenever the floor is not involved, so it can be read
   * unconditionally. Optional for hosted, which does not send it.
   */
  unclamped_delta?: number | null;
  declining: boolean;
  snapshot_count: number;
}

/* ------------------------------------------------------------------ *
 * Trend
 * ------------------------------------------------------------------ */

export interface HealthTrendResponse {
  history: Array<{
    taken_at: string | null;
    /**
     * `null` under a narrowed scope, which recorded only the average, and on
     * the full scope when that snapshot recorded no hotspot files.
     */
    hotspot_health: number | null;
    average_health: number;
    worst_performer_path: string | null;
    worst_performer_score: number | null;
    /**
     * The headline's two halves in deduction points, and the maintainability
     * pillar, at this snapshot. `null` before each was recorded and under a
     * narrowed scope, so a series can start partway along the axis rather than
     * reading an unrecorded point as a zero.
     */
    structure_average?: number | null;
    history_average?: number | null;
    maintainability_average?: number | null;
    /** Stored documentation drift findings at this snapshot; `null` before recorded. */
    doc_drift_count?: number | null;
  }>;
  summary: {
    /**
     * `null` under a narrowed scope (only the average covers both populations),
     * and on the full scope when the newest snapshot recorded no hotspot files.
     */
    current_hotspot_health: number | null;
    current_average_health: number;
    previous_hotspot_health: number | null;
    previous_average_health: number | null;
    hotspot_delta: number | null;
    average_delta: number | null;
    /** The newest reading's two halves, in deduction points. */
    current_structure_deduction?: number | null;
    current_history_deduction?: number | null;
  };
  alerts: Array<{
    /**
     * `"declining"` and `"predicted_decline"` are regressions. `"history_drag"`
     * is a fall whose whole cause is git history while the code shape held or
     * improved: the same numbers with the opposite reading, and nothing to fix.
     */
    kind: string;
    metric: string;
    current: number;
    baseline: number | null;
    delta: number;
    message: string;
    /**
     * Which half of the headline moved, and how far each half moved in score
     * points. These are changes in mean deduction, so they sum to `delta` only
     * while no file sits at the score floor. `null` on the hotspot metric,
     * whose halves are not snapshotted, and on histories predating the split.
     */
    driver?: "structure" | "history" | null;
    structure_delta?: number | null;
    history_delta?: number | null;
  }>;
  /** Largest movements first, in either direction, capped server-side. */
  file_deltas: Array<{
    file_path: string;
    before: number;
    after: number;
    delta: number;
  }>;
  /**
   * How many files moved in total, before the cap. Optional: the hosted
   * backend does not send it, so consumers fall back to `file_deltas.length`.
   */
  file_deltas_total?: number;
  /**
   * How many of those fell and rose. The server holds half the slice for each
   * direction while it has rows to fill it. Optional like the total.
   */
  file_deltas_worse?: number;
  file_deltas_improved?: number;
  snapshot_count: number;
  /** Which half of the repository these figures describe. */
  scope?: HealthScope;
}

/* ------------------------------------------------------------------ *
 * Coverage
 * ------------------------------------------------------------------ */

export interface CoverageFileRow {
  file_path: string;
  source_format: string;
  line_coverage_pct: number;
  branch_coverage_pct: number | null;
  total_coverable_lines: number;
  ingested_at: string | null;
  ingested_commit_sha: string | null;
  covered_lines?: number[];
  health_score?: number | null;
  nloc?: number;
}

export interface ModuleCoverageRow {
  module: string;
  files: number;
  covered_lines: number;
  total_lines: number;
  line_coverage_pct: number;
}

/**
 * The summary is generated from the server's response model. `freshness` is
 * `stale` when the report was measured at another commit than the indexed
 * one; `report_paths` is how the report's own entries mapped, `null` for an
 * ingest that did not record it.
 */
export type {
  CoverageHistoryPoint,
  CoverageReportPaths,
  CoverageSummary,
  CoverageSummaryFreshness,
} from "./generated/http.js";

/**
 * What the other lenses hold for the same files: per file, findings, Fix
 * first, refactoring, performance and dead code, each capped with its total.
 * A lens with nothing for a file is absent from `lenses`.
 */
export type {
  RelatedWorkFile,
  RelatedWorkItem,
  RelatedWorkLens,
  RelatedWorkResponse,
} from "./generated/http.js";

/**
 * Which signal answered "is this tested". `measured` is a coverage report: it
 * records the lines a test really executed. `inferred` is the dependency graph:
 * a test whose calls reach this file, which says control *can* flow there, not
 * that a run did. `none` is the honest unknown. `unavailable` means the graph
 * walk failed, so nothing can be said either way until it is retried.
 *
 * The two are never merged and never averaged. They are different claims, and a
 * reader who cannot tell them apart cannot tell a measured test from a guessed
 * one. `basis` says which one answered; nothing blends them.
 */
export type CoverageBasis = "measured" | "inferred" | "none" | "unavailable";

/**
 * Which tier of the graph found a test. `call-graph` means a test's calls reach
 * the file, the stronger claim; `import-graph` means it only imports it;
 * `indirect-import` means it imports a file that imports it: a test-only
 * helper, a package entry file, or a longer import chain; `mocked-only` means
 * every test that reaches it replaces it with a double.
 */
export type ReachedVia = "call-graph" | "import-graph" | "indirect-import" | "mocked-only";

/**
 * One file on the inferred basis. `reached` is the whole of what this basis
 * knows about it: there is no percentage here and there never can be, because
 * reaching is a file-level fact with no line attribution behind it.
 *
 * Which tests reach it is a separate, per-file request — attributing every file
 * at once costs a walk per file, and the list is only ever read one row at a
 * time. See `TestsReachingFile`.
 */
export interface ReachedFileRow {
  file_path: string;
  reached: boolean;
  health_score?: number | null;
  nloc?: number;
}

/**
 * The graph-inferred test map: counts, never a ratio. `files_reached` and
 * `files_not_reached` are deliberately two counts rather than one fraction —
 * a fraction invites a progress bar, and a progress bar is the coverage
 * percentage this basis is not allowed to claim.
 *
 * `files_total` is the full count whatever `files` carries, so a trimmed list is
 * never read as the whole repo.
 */
export interface InferredTestMap {
  files: ReachedFileRow[];
  files_total: number;
  files_reached: number;
  files_not_reached: number;
  test_file_count: number;
  /**
   * Present only when `basis` is `measured` (the hybrid shape): how many files
   * carry a measured coverage row. On that shape `inferred` is scoped to the
   * files *without* a measured row, so this lets the UI state the split
   * (measured vs graph-answered) honestly. Absent on the pure-inferred shape.
   */
  measured_file_count?: number;
}

/** Which tests reach one file, and which tier found them. */
export interface TestsReachingFile {
  file_path: string;
  basis: CoverageBasis;
  reached: boolean;
  /**
   * Empty when `reached` is false, and capped server-side. Render `total`
   * beside it, never `tests.length` on its own, or a trimmed list states a
   * cap as if it were the answer.
   */
  tests: string[];
  /** Null when `reached` is false. */
  via: ReachedVia | null;
  /** How many tests the walk found, before the cap trimmed `tests`. */
  total?: number;
  /** Whether `tests` is a trimmed slice of `total`. */
  truncated?: boolean;
}

export interface HealthCoverageResponse {
  summary: CoverageSummary;
  files: CoverageFileRow[];
  /** Capped by the request's `module_limit`, which is independent of `limit`. */
  modules: ModuleCoverageRow[];
  /**
   * How many modules exist, whatever `modules` carries — so a trimmed or
   * declined rollup is never read as the repo having that few. Optional: the
   * hosted backend does not send it yet.
   */
  modules_total?: number;
  /**
   * Which signal answered, when the response determined one. Absent means it did
   * not: an older backend that predates the field, or a caller that passed
   * `include_inferred=false` and so never consulted the graph. That is why a
   * declined response omits it rather than reporting `"none"` — not consulted
   * and nothing to say are different states.
   */
  basis?: CoverageBasis;
  /**
   * Present only when `basis` is `inferred` (pure-inferred shape: `summary`,
   * `files` and `modules` are empty so no consumer renders one through the
   * other's code path) OR when `basis` is `measured` and the repo has files
   * with no measured row (hybrid shape: the measured fields are populated, and
   * `inferred` holds the graph answer for exactly the non-measured files).
   * On the hybrid shape `measured_file_count` states the split. In both shapes
   * the inferred map carries counts only — never a percentage.
   */
  inferred?: InferredTestMap;
  /**
   * One point per retained report, oldest first, partial reports left out.
   * Present on the measured basis only; absent from an older backend.
   */
  history?: CoverageHistoryPoint[];
}

/* ------------------------------------------------------------------ *
 * Health work queue (legacy route: /health/refactoring-targets)
 * ------------------------------------------------------------------ */

export interface HealthWorkItem {
  file_path: string;
  score: number;
  nloc: number;
  module?: string | null;
  /** A test file. Optional: an older backend does not send it. */
  is_test?: boolean;
  primary_biomarker: string;
  primary_severity: HealthSeverity;
  primary_reason: string;
  primary_function: string | null;
  primary_line_start: number | null;
  primary_line_end: number | null;
  primary_suggestion?: string;
  primary_finding_id?: string;
  total_impact: number;
  finding_count: number;
  /**
   * How many of those are still open. Equal to `finding_count` under the
   * default status filter. Optional: an older backend does not send it.
   */
  open_finding_count?: number;
  biomarkers: string[];
  effort_bucket: "S" | "M" | "L" | "XL";
  impact_per_effort: number;
  /**
   * No longer served by the OSS `/health/refactoring-targets` route: building it
   * for every file with findings, before the `limit` slice, cost 1.8 MB per
   * request to feed two click-gated consumers. Fetch a file's findings from
   * `GET /health/findings?file_path=` instead. Kept optional because the hosted
   * backend still sends it and a client may hold a cached older payload.
   */
  all_findings?: Array<{
    id: string;
    biomarker_type: string;
    severity: HealthSeverity;
    function_name: string | null;
    health_impact: number;
    reason: string;
    status?: string;
  }>;
}

export interface HealthWorkQueueResponse {
  targets: HealthWorkItem[];
  /** Files matching the filters, before the page slice. */
  total: number;
  /**
   * Findings across those files. The view lists files but triages findings, so
   * the file count alone leaves the size of the work unsaid. Optional: an older
   * backend does not send it and the view omits the clause rather than
   * inventing one.
   */
  finding_total?: number;
  /**
   * Files left out because every finding on them is a history marker
   * (`history: "exclude"`, the default). Not counted in `total`.
   */
  history_only_excluded?: number;
  offset?: number;
  limit?: number;
}

export interface HealthWorkQueueQuery {
  counts?: HealthCounts;
  limit?: number;
  offset?: number;
  module?: string;
  biomarker?: string;
  /** Severity floor. Ignored by the server when `severity` is given. */
  min_severity?: string;
  /** Exact severities, comma-separated. */
  severity?: string;
  dimension?: HealthDimension;
  /** Comma-separated statuses, or `"all"`. Defaults to open work. */
  status?: string;
  /** Substring filter on `file_path`. */
  search?: string;
  only_hotspots?: boolean;
  only_untested?: boolean;
  /** Files below the score green starts at. */
  only_failing?: boolean;
  max_effort?: string;
  sort?: "impact_per_effort" | "total_impact" | "score" | "finding_count";
  /** `"exclude"` (default) leaves out files whose only findings are history markers. */
  history?: "exclude" | "include";
  /** Which half of the repository to describe. Defaults to `"all"`. */
  scope?: HealthScope;
}

/**
 * One file on the impact / effort plane. With a refactoring plan that recovers
 * something, both coordinates describe the plan (`effort_basis: "plan"`: lines
 * its steps span, health it credits); otherwise the file (`"file"`: its code
 * lines, the deduction its open findings carry).
 */
export interface ImpactEffortPoint {
  file_path: string;
  /** Always at least 1, so a log axis can hold it. */
  effort_lines: number;
  effort_basis: "plan" | "file";
  /** Health points. */
  recoverable_health: number;
  /** The tier of the file's first Fix-first item, when it holds one. */
  tier?: "now" | "next" | "later" | null;
  /** That item's place in the Fix-first list, from 1. */
  fix_rank?: number | null;
}

/** Every file the work queue's filters keep, history-only files excluded. */
export interface ImpactEffortResponse {
  /** Largest recoverable health first; at most `cap`. */
  points: ImpactEffortPoint[];
  plotted: number;
  total: number;
  cap: number;
  /** Fixed quadrant midlines from core, never derived from the data. */
  effort_midline_lines: number;
  gain_midline_points: number;
  history_only_excluded?: number;
}

/** The work queue's filters, without its paging, order or history switch. */
export type ImpactEffortQuery = Omit<
  HealthWorkQueueQuery,
  "limit" | "offset" | "sort" | "history"
>;

/** @deprecated Use HealthWorkItem; this is a file triage row, not a plan. */
export type RefactoringTarget = HealthWorkItem;
/** @deprecated Use HealthWorkQueueResponse. */
export type RefactoringTargetsResponse = HealthWorkQueueResponse;
/** @deprecated Use HealthWorkQueueQuery. */
export type RefactoringQuery = HealthWorkQueueQuery;

/* ------------------------------------------------------------------ *
 * Churn x complexity quadrant (the "hotspot anatomy" view)
 * ------------------------------------------------------------------ */

/**
 * One file in the churn x complexity plane. `commit_count_90d` is the churn
 * (x) axis, `max_ccn` the complexity (y) axis, `nloc` encodes dot size, and
 * `score` drives dot color via the health band. `churn_percentile` (0-100) is
 * repo-relative tooltip context so a raw count reads sensibly across repos of
 * any size. Only files with recent churn (`commit_count_90d > 0`) are plotted.
 */
export interface ChurnComplexityPoint {
  file_path: string;
  commit_count_90d: number;
  max_ccn: number;
  nloc: number;
  score: number;
  churn_percentile: number;
}

export interface ChurnComplexityResponse {
  points: ChurnComplexityPoint[];
  total: number;
}