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.

10.4 KB
Raw Blame
import {
  bulletList,
  closingSections,
  FLAVOR_PREAMBLE,
  joinSections,
  repoSuffix,
  type AiPromptFlavor,
} from "./shared";

// ─────────────────────────────────────────────────────────────────────
// Coupling decouple prompt (per co-change pair)
// ─────────────────────────────────────────────────────────────────────

export interface CouplingPromptEdge {
  source: string;
  target: string;
  strength?: number | null;
  last_co_change?: string | null;
  /** Commits that touched both files, undecayed. */
  support?: number | null;
  /** Share of `source`'s own commits that also touched `target`. */
  confidence_ab?: number | null;
  /** The same share from `target`'s side. */
  confidence_ba?: number | null;
  /** `corroborated` / `unexplained` / `not_applicable`, or absent on an older index. */
  structural?: string | null;
}

/** What the page already knows about one end of the pair. */
export interface CouplingPromptNode {
  module?: string | null;
  score?: number | null;
  nloc?: number | null;
}

export interface BuildCouplingPromptOptions {
  edge: CouplingPromptEdge;
  flavor?: AiPromptFlavor;
  repoName?: string;
  /** Per-file facts keyed by path; either end may be missing. */
  nodes?: Record<string, CouplingPromptNode>;
}

/** The dependency-graph verdict, spelled out, keyed by `structural`. */
const STRUCTURAL_VERDICT = new Map<string, string>([
  [
    "unexplained",
    "Dependency graph: **nothing connects them** — no import, type use, framework wiring, or read. This is the finding: they move together with no structural reason to.",
  ],
  [
    "corroborated",
    "Dependency graph: a dependency already connects them, so the co-change is at least partly explained. Judge whether the dependency is the *right* one before treating this as accidental.",
  ],
  [
    "not_applicable",
    "Dependency graph: at least one side was never parsed (a lockfile, changelog, config, or doc), so there was no edge to look for. The coupling is real but is probably release plumbing, not a code-structure problem.",
  ],
]);

/** One end's module / health / size, as a bullet, when anything is known. */
function fileFacts(path: string, label: string, node: CouplingPromptNode | undefined): string {
  const facts: string[] = [];
  if (node?.module) facts.push(`module \`${node.module}\``);
  if (typeof node?.score === "number") facts.push(`health ${node.score.toFixed(1)}/10`);
  if (typeof node?.nloc === "number" && node.nloc > 0) facts.push(`${node.nloc} lines`);
  return facts.length
    ? `File ${label}: \`${path}\` (${facts.join(", ")})`
    : `File ${label}: \`${path}\``;
}

function pctOf(v: number | null | undefined): string | null {
  return typeof v === "number" ? `${Math.round(v * 100)}%` : null;
}

// The asymmetry is the content: a file that never changes alone is a
// different finding from two that both change often.
function directionalConfidence(edge: CouplingPromptEdge): string | null {
  const abPct = pctOf(edge.confidence_ab);
  const baPct = pctOf(edge.confidence_ba);
  if (abPct && baPct) {
    return `Directional confidence: ${abPct} of A's own commits also touched B; ${baPct} of B's also touched A. The larger share is the stronger claim; the smaller one says how independent that side still is.`;
  }
  if (abPct) {
    return `Directional confidence: ${abPct} of A's own commits also touched B (the other side's commit total is unknown).`;
  }
  if (baPct) {
    return `Directional confidence: ${baPct} of B's own commits also touched A (the other side's commit total is unknown).`;
  }
  return null;
}

const CONSTRAINTS = [
  "**Diagnose before decoupling.** Read both files and the commits that touched them together. The coupling may be legitimate (two halves of one feature) or accidental (a leaky abstraction, a shared constant, copy-paste). Name which it is before acting.",
  "If it's accidental, fix the cause: extract the shared concept into one owner, invert the dependency, or introduce a stable interface — don't just move code around.",
  "If it's legitimate and unavoidable, say so and stop. Forcing a split that the domain doesn't support makes things worse.",
  "Preserve behavior. This is a structural change, not a feature change.",
  "Add or update tests so the new boundary is exercised and the old hidden contract can't silently regress.",
];

const EXPECTED = [
  "1. A verdict: is this coupling accidental or legitimate, and what's the underlying shared concern?",
  "2. If accidental — a concrete decoupling plan (extract / invert / interface), smallest-risk first.",
  "3. The first change, scoped and behavior-preserving, with its tests.",
  "4. If legitimate — the reason to leave it, and any lighter-touch improvement (docs, a shared module) worth doing instead.",
];

function couplingFacts(edge: CouplingPromptEdge, nodes: BuildCouplingPromptOptions["nodes"]): string {
  const last = edge.last_co_change
    ? new Date(edge.last_co_change).toISOString().slice(0, 10)
    : null;
  return bulletList([
    fileFacts(edge.source, "A", nodes?.[edge.source]),
    fileFacts(edge.target, "B", nodes?.[edge.target]),
    edge.support
      ? `Shared commits: **${edge.support}** (undecayed count of commits that touched both)`
      : null,
    directionalConfidence(edge),
    STRUCTURAL_VERDICT.get(edge.structural ?? "") ?? null,
    edge.strength != null
      ? `Coupling strength: ${edge.strength} (recency-weighted, not a percentage and not a verified dependency)`
      : null,
    last ? `Last changed together: ${last}` : null,
    "Source: repowise co-change analysis (git history — treat as a lead).",
  ]);
}

export function buildCouplingAiPrompt({
  edge,
  flavor = "generic",
  repoName,
  nodes,
}: BuildCouplingPromptOptions): string {
  return joinSections([
    FLAVOR_PREAMBLE[flavor],
    "",
    `## Hidden coupling to untangle${repoSuffix(repoName)}`,
    "",
    couplingFacts(edge, nodes),
    "",
    ...closingSections(CONSTRAINTS, EXPECTED),
    flavor === "claude-code-mcp"
      ? `Call \`get_risk(['${edge.source}'])\` and \`get_context(['${edge.source}', '${edge.target}'])\` to see what else each file pulls in before you plan the split — repowise already mapped the dependency graph and the co-change history. Don't restructure until you know why they move together.`
      : "Start by reading both files and `git log` for the commits that changed them together. The co-change count is a symptom; find the shared concern driving it before you restructure anything.",
  ]);
}

// ─────────────────────────────────────────────────────────────────────
// Area coupling prompt (one or more area pairs)
// ─────────────────────────────────────────────────────────────────────

/** One area pair as the coupling view holds it. */
export interface AreaCouplingPromptPair {
  source: string;
  target: string;
  pairs: number;
  unexplained_pairs: number;
  co_changes: number;
  last_co_change?: string | null;
  /** The strongest file pairs, unexplained first. */
  top_pairs?: CouplingPromptEdge[];
}

export interface BuildAreaCouplingPromptOptions {
  areaPairs: AreaCouplingPromptPair[];
  flavor?: AiPromptFlavor;
  repoName?: string;
}

function areaName(path: string): string {
  return path ? `\`${path}/\`` : "the repository root";
}

function filePairLine(edge: CouplingPromptEdge): string {
  const verdict =
    edge.structural === "unexplained" ? "no dependency joins them" : (edge.structural ?? "unlabelled");
  const support = edge.support ? `, ${edge.support} shared commits` : "";
  return `\`${edge.source}\` ↔ \`${edge.target}\` (${verdict}${support})`;
}

function areaPairSection(pair: AreaCouplingPromptPair): string {
  const last = pair.last_co_change ? `, last on ${pair.last_co_change.slice(0, 10)}` : "";
  return [
    `### ${areaName(pair.source)} ↔ ${areaName(pair.target)}`,
    "",
    bulletList([
      `${pair.pairs} file pairs change together across these areas, and no dependency joins the two areas in either direction; **${pair.unexplained_pairs}** of the pairs are files that could have carried one.`,
      `${pair.co_changes} shared commits summed over those pairs${last}.`,
      ...(pair.top_pairs ?? []).map(filePairLine),
    ]),
  ].join("\n");
}

const AREA_EXPECTED = [
  "1. Per area pair: the shared concern behind the hidden coupling (a wire contract, a duplicated constant, a feature split across layers), named with evidence from the commits.",
  "2. Which of it is legitimate (two halves of one feature, a generated mirror) and which is accidental.",
  "3. For the accidental part: a decoupling plan, smallest-risk first, and the first behavior-preserving change with its tests.",
];

/**
 * A prompt asking an agent to investigate why whole areas change together
 * with no dependency between their files, and to decouple what is accidental.
 */
export function buildAreaCouplingAiPrompt({
  areaPairs,
  flavor = "generic",
  repoName,
}: BuildAreaCouplingPromptOptions): string {
  const first = areaPairs[0];
  return joinSections([
    FLAVOR_PREAMBLE[flavor],
    "",
    `## Hidden coupling between areas${repoSuffix(repoName)}`,
    "",
    "Files in these directories keep changing in the same commits although no file in one area imports, uses or wires a file in the other. Across languages that usually means an unwritten contract (a wire format, a schema mirrored by hand, a command a script runs). Source: repowise co-change analysis of git history; treat it as a lead, not proof. Test files are left out, since a test is expected to change with its code.",
    "",
    ...areaPairs.flatMap((pair) => [areaPairSection(pair), ""]),
    ...closingSections(CONSTRAINTS, AREA_EXPECTED),
    flavor === "claude-code-mcp" && first
      ? `Call \`get_context(['${first.source}', '${first.target}'])\` and \`get_risk\` on the file pairs above before planning: repowise already holds the dependency graph and co-change history.`
      : "Start with `git log` for the commits that touched both sides of a pair. The co-change count is a symptom; find the shared concern before restructuring anything.",
  ]);
}