diff --git a/README.md b/README.md index e82439a..9c3f830 100644 --- a/README.md +++ b/README.md @@ -220,6 +220,23 @@ FixMap follows bounded imports and dependents, then joins existing tests, contra review ownership, and architecture policy. A missing `--add` path stays unresolved. FixMap does not interpret what "checkout" means, call an API or LLM, or require an account. +Ask who could review a change: + +```bash +fixmap reviewers --diff main...HEAD +fixmap reviewers --working-tree --no-history-authors +fixmap reviewers --report plan.json --format json +``` + +Each changed path lists suggested reviewers with the exact reason: the highest-precedence +CODEOWNERS file (the last matching rule wins) with its line, active annotation owners, +architecture-policy reviewers, and up to three frequent authors from the newest 250 non-merge +commits. Commit authors are canonicalized through the repository's `.mailmap` when one exists. +`--no-history-authors` leaves commit authors out entirely and reads no commit history. Names are +printed without `@`, so pasting the output into a pull request notifies nobody, and FixMap never +requests reviews. A name is not evidence of identity, employment, or current availability. The +MCP tool `fixmap_reviewers` takes the same inputs and is read-only. + Persist a reviewed product-to-implementation map without persisting generated conclusions: ```bash @@ -239,7 +256,7 @@ contract, decision, test-association, reviewer, and architecture evidence. ## Complete feature catalog -> **Preview features.** `change-scope`, `capability` / `capabilities`, `workspace`, `ask`, `migrate`, `reverse-docs`, `history`, `supply-chain`, `runtime`, `sandbox`, `editor`, `--semantic-model`, `--evidence`, and their MCP tools are previews: they work and are tested, but their output and options may change before v0.10.0. Language support beyond JavaScript and TypeScript is also preview quality while testing on unseen repositories continues. `fixmap features` lists which features are previews. +> **Preview features.** `change-scope`, `reviewers`, `capability` / `capabilities`, `workspace`, `ask`, `migrate`, `reverse-docs`, `history`, `supply-chain`, `runtime`, `sandbox`, `editor`, `--semantic-model`, `--evidence`, and their MCP tools are previews: they work and are tested, but their output and options may change before v0.10.0. Language support beyond JavaScript and TypeScript is also preview quality while testing on unseen repositories continues. `fixmap features` lists which features are previews. ### Inputs and repository mapping diff --git a/packages/action/dist/index.mjs b/packages/action/dist/index.mjs index fc2ef17..4403d73 100644 --- a/packages/action/dist/index.mjs +++ b/packages/action/dist/index.mjs @@ -7893,7 +7893,11 @@ function routeReviewers(repo, input) { addCodeOwners(repo, changedPaths, accumulated, diagnostics); addAnnotations(repo, changedPaths, input.now, accumulated, diagnostics); addPolicy(repo, changedPaths, accumulated, diagnostics); - addHistory(repo, changedPaths, accumulated); + if (input.includeHistoryAuthors === false) { + diagnostics.push({ source: "git-history", severity: "info", message: "Commit-author suggestions were turned off; only CODEOWNERS, annotations, and architecture policy were used." }); + } else { + addHistory(repo, changedPaths, accumulated, diagnostics); + } const suggestions = [...accumulated].map(([reviewer, value]) => ({ reviewer, confidence: value.confidence, @@ -8008,7 +8012,12 @@ function addPolicy(repo, paths, accumulated, diagnostics) { diagnostics.push({ source: ".fixmap/policy.json", severity: "warning", message: `Policy reviewers were skipped: ${error instanceof Error ? error.message : String(error)}` }); } } -function addHistory(repo, paths, accumulated) { +function addHistory(repo, paths, accumulated, diagnostics) { + if (repo.history?.shallow) { + diagnostics.push({ source: "git-history", severity: "warning", message: "Commit history is shallow, so commit-author suggestions only reflect the commits present in this clone." }); + } else if (repo.history?.truncated) { + diagnostics.push({ source: "git-history", severity: "info", message: `Commit-author suggestions use only the newest ${Math.min(repo.history.inspectedCommits, MAX_HISTORY_COMMITS2).toLocaleString()} non-merge commits.` }); + } for (const path of paths) { const counts = /* @__PURE__ */ new Map(); for (const commit of (repo.history?.commits ?? []).slice(0, MAX_HISTORY_COMMITS2)) { @@ -8039,8 +8048,9 @@ function add(accumulated, reviewer, confidence, path, evidence) { if (confidenceOrder(confidence) < confidenceOrder(existing.confidence)) existing.confidence = confidence; existing.paths.add(path); - if (!existing.evidence.some((entry2) => evidenceKey(entry2) === evidenceKey(evidence))) - existing.evidence.push(evidence); + const routed = { ...evidence, changedPath: path }; + if (!existing.evidence.some((entry2) => evidenceKey(entry2) === evidenceKey(routed))) + existing.evidence.push(routed); accumulated.set(identity, existing); } function normalizePaths(values) { @@ -8057,10 +8067,10 @@ function validOwner(value) { return value.length <= 200 && (/^@[A-Za-z0-9][A-Za-z0-9_.-]*(?:\/[A-Za-z0-9][A-Za-z0-9_.-]*)?$/.test(value) || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)); } function evidenceKey(value) { - return `${value.kind}\0${value.sourceFingerprint}\0${value.path ?? ""}\0${value.line ?? ""}\0${value.detail}`; + return `${value.kind}\0${value.sourceFingerprint}\0${value.path ?? ""}\0${value.line ?? ""}\0${value.changedPath ?? ""}\0${value.detail}`; } function evidenceOrder(a, b) { - return a.kind.localeCompare(b.kind) || (a.path ?? "").localeCompare(b.path ?? "") || (a.line ?? 0) - (b.line ?? 0); + return a.kind.localeCompare(b.kind) || (a.changedPath ?? "").localeCompare(b.changedPath ?? "") || (a.path ?? "").localeCompare(b.path ?? "") || (a.line ?? 0) - (b.line ?? 0); } function confidenceOrder(value) { return value === "high" ? 0 : value === "medium" ? 1 : 2; diff --git a/packages/cli/README.md b/packages/cli/README.md index e204725..027fc15 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -163,6 +163,7 @@ For long task text, use `--issue-file task.md`, pipe it directly to `fixmap plan - **Context Pack** — use `fixmap context` to package deterministic line ranges from primary and impact files within an estimated source-token budget. Markdown is readable by people and agents; JSON preserves roles, reasons, line ranges, truncation, and omitted-file diagnostics. - **Graph export** — use `fixmap graph` to export the evidence-backed Impact Graph as portable Mermaid or versioned JSON while preserving relationship direction. - **Change scope** — use `fixmap change-scope --touch [--add ]` to expand only caller-selected product work surfaces over bounded dependencies/dependents, then join existing tests, contracts, decisions, reviewers, and policy evidence. Missing additions remain unresolved; no product semantics are inferred. +- **Reviewer suggestions** (preview) — use `fixmap reviewers --diff | --working-tree | --report ` to list suggested reviewers per changed path from CODEOWNERS (last matching rule wins, with the source line), annotation owners, architecture policy, and `.mailmap`-canonical commit authors. `--no-history-authors` drops commit authors. Names print without `@` so nobody is notified; FixMap never requests reviews or infers availability. MCP: `fixmap_reviewers`. - **Product capabilities** — use `fixmap capability create|update|remove` to maintain a locked, atomic `.fixmap/capabilities.json` of human names, explicit anchors, and bounds; use `fixmap capability ` or `fixmap capabilities` to rebuild/show current evidence. `fixmap capability diff ..` compares exact immutable Git objects without checkout mutation. Generated conclusions are never stored. - **Cross-repository workspace** — use `fixmap workspace --config --seed ` to resolve local Node, Python, and Maven package providers and trace downstream consumers with versioned identity, manifest, import, and submodule evidence. - **Repository Q&A** — use `fixmap ask --report --question ` to answer structural context, impact, test, risk, policy, ADR, and annotation questions from bounded report evidence with citations and explicit unknowns. @@ -230,6 +231,7 @@ fixmap supply-chain Import normalized external scanner and SBOM evidence fixmap runtime Map redaction-reviewed runtime evidence to exact files fixmap sandbox Run one explicitly consented command in an isolated container fixmap change-scope Expand explicit planned paths into structural consequences +fixmap reviewers Suggest reviewers per changed path without notifying anyone fixmap capability Create, update, remove, or show one product capability fixmap capabilities List persistent product capability definitions fixmap verify Compare a saved plan with the diff that followed diff --git a/packages/cli/src/cli-runner.ts b/packages/cli/src/cli-runner.ts index 66feda9..b86c0cf 100644 --- a/packages/cli/src/cli-runner.ts +++ b/packages/cli/src/cli-runner.ts @@ -102,6 +102,7 @@ Usage: fixmap validate plan.json fixmap benchmark --repo . --last 50 fixmap change-scope --touch src/auth --touch packages/api --add db/migrations + fixmap reviewers --diff main...HEAD --no-history-authors fixmap editor --issue "Investigate authentication" --repo . fixmap capability create checkout --touch src/routes/checkout.ts --touch packages/payments fixmap capability checkout @@ -129,6 +130,7 @@ Commands: validate Validate a saved FixMap JSON report benchmark Backtest BM25, FixMap, and Impact Graph on pre-change snapshots change-scope Preview: Expand explicit planned paths into bounded structural consequences + reviewers Preview: Suggest reviewers per changed path from CODEOWNERS, owners, policy, and history editor Preview: Serve a local read-only NDJSON editor session capability Preview: Create, update, remove, or show a persistent product capability capabilities Preview: List persistent product capabilities declared by the repository @@ -462,6 +464,15 @@ export async function runCli(args: string[], dependencies: CliDependencies = {}) }); } + if (args[0] === "reviewers") { + const { runReviewersCommand } = await import("./reviewers-command.js"); + return runReviewersCommand(args.slice(1), { + stdout, + stderr, + ...(dependencies.writeReport ? { writeOutput: dependencies.writeReport } : {}) + }); + } + if (args[0] === "change-scope") { const { runChangeScopeCommand } = await import("./change-scope-command.js"); return runChangeScopeCommand(args.slice(1), { diff --git a/packages/cli/src/mcp.ts b/packages/cli/src/mcp.ts index 70326eb..918f8d4 100644 --- a/packages/cli/src/mcp.ts +++ b/packages/cli/src/mcp.ts @@ -48,6 +48,7 @@ import { buildSupplyChainReport, renderSupplyChainMarkdown } from "./supply-chai import { parseRuntimeInput, renderRuntimeMarkdown } from "./runtime-command.js"; import { runWorkspaceCommand } from "./workspace-command.js"; import { runChangeScopeCommand } from "./change-scope-command.js"; +import { runReviewersCommand } from "./reviewers-command.js"; import { runCapabilitiesCommand, runCapabilityCommand } from "./capability-command.js"; import { buildReportForRepository, @@ -304,6 +305,28 @@ const CHANGE_SCOPE_TOOL = { } }; +const REVIEWERS_TOOL = { + name: "fixmap_reviewers", + title: "FixMap reviewer suggestions", + description: + "Preview (may change before v0.10.0): Suggest reviewers per changed path from the highest-precedence CODEOWNERS file (last matching rule wins), active annotation owners, architecture-policy reviewers, and bounded .mailmap-canonical commit authors. " + + "Read-only: it never requests reviews or notifies anyone, prints names without @, and does not treat a name as evidence of identity, employment, or availability. Provide exactly one of report, diff, or workingTree.", + annotations: { readOnlyHint: true, openWorldHint: false }, + inputSchema: { + type: "object" as const, + properties: { + report: { type: "string", description: "Path to a saved FixMap JSON plan; its changed files (or ranked context files) are routed" }, + diff: { type: "string", description: "Git diff spec whose changed files are routed, such as main...HEAD" }, + workingTree: { type: "boolean", description: "Route staged and unstaged changes against HEAD" }, + noHistoryAuthors: { type: "boolean", description: "Leave out commit-author suggestions" }, + repo: { type: "string", description: "Local checkout path (defaults to the MCP server repository)" }, + format: { type: "string", description: "Output format: markdown (default) or json" }, + noCache: { type: "boolean", description: "Bypass repository scan caches" } + }, + additionalProperties: false + } +}; + const CAPABILITY_TOOL = { name: "fixmap_capability", title: "FixMap capability", @@ -516,7 +539,7 @@ export function createFixMapMcpServer( const server = new Server({ name: "fixmap", version: readVersion() }, { capabilities: { tools: {} } }); server.setRequestHandler(ListToolsRequestSchema, async () => ({ - tools: [PLAN_TOOL, CONTEXT_TOOL, GRAPH_TOOL, CHANGE_SCOPE_TOOL, CAPABILITY_TOOL, WORKSPACE_TOOL, ASK_TOOL, MIGRATION_TOOL, REVERSE_DOCS_TOOL, HISTORY_TOOL, SUPPLY_CHAIN_TOOL, RUNTIME_TOOL, VERIFY_TOOL, EXPLAIN_TOOL, COMPARE_TOOL, DOCTOR_TOOL, ANNOTATION_TOOL] + tools: [PLAN_TOOL, CONTEXT_TOOL, GRAPH_TOOL, CHANGE_SCOPE_TOOL, REVIEWERS_TOOL, CAPABILITY_TOOL, WORKSPACE_TOOL, ASK_TOOL, MIGRATION_TOOL, REVERSE_DOCS_TOOL, HISTORY_TOOL, SUPPLY_CHAIN_TOOL, RUNTIME_TOOL, VERIFY_TOOL, EXPLAIN_TOOL, COMPARE_TOOL, DOCTOR_TOOL, ANNOTATION_TOOL] })); server.setRequestHandler(CallToolRequestSchema, async (request) => { @@ -590,6 +613,33 @@ export function createFixMapMcpServer( const exitCode = await runChangeScopeCommand(commandArgs, { stdout: (value) => stdout.push(value), stderr: (value) => stderr.push(value) }); return { ...(exitCode === 0 ? {} : { isError: true }), content: [{ type: "text", text: exitCode === 0 ? stdout.join("") : stderr.join("") }] }; } + if (request.params.name === REVIEWERS_TOOL.name) { + const record = request.params.arguments as Record | undefined; + const invalid = (text: string) => ({ isError: true, content: [{ type: "text", text: `Invalid arguments: ${text}` }] }); + const unknown = Object.keys(record ?? {}).filter((key) => !["report", "diff", "workingTree", "noHistoryAuthors", "repo", "format", "noCache"].includes(key)); + if (unknown.length > 0) return invalid(`unknown argument${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}.`); + for (const key of ["report", "diff", "repo"] as const) { + if (record?.[key] !== undefined && (typeof record[key] !== "string" || !record[key].trim())) return invalid(`"${key}" must be a non-empty string.`); + } + for (const key of ["workingTree", "noHistoryAuthors", "noCache"] as const) { + if (record?.[key] !== undefined && typeof record[key] !== "boolean") return invalid(`"${key}" must be a boolean.`); + } + if (record?.repo && /^https?:\/\//i.test(String(record.repo))) return invalid('"repo" must be a local checkout.'); + const sources = Number(record?.report !== undefined) + Number(record?.diff !== undefined) + Number(record?.workingTree === true); + if (sources !== 1) return invalid('provide exactly one of "report", "diff", or "workingTree": true.'); + const format = normalizeFormat(record?.format); + if (!format.success) return invalid(format.message); + const commandArgs = ["--repo", typeof record?.repo === "string" ? record.repo.trim() : defaultRepo, "--format", format.value ?? "markdown"]; + if (typeof record?.report === "string") commandArgs.push("--report", record.report.trim()); + if (typeof record?.diff === "string") commandArgs.push("--diff", record.diff.trim()); + if (record?.workingTree === true) commandArgs.push("--working-tree"); + if (record?.noHistoryAuthors === true) commandArgs.push("--no-history-authors"); + if (record?.noCache === true) commandArgs.push("--no-cache"); + const stdout: string[] = []; + const stderr: string[] = []; + const exitCode = await runReviewersCommand(commandArgs, { stdout: (value) => stdout.push(value), stderr: (value) => stderr.push(value) }); + return { ...(exitCode === 0 ? {} : { isError: true }), content: [{ type: "text", text: exitCode === 0 ? stdout.join("") : stderr.join("") }] }; + } if (request.params.name === CAPABILITY_TOOL.name) { const record = request.params.arguments as Record | undefined; const unknown = Object.keys(record ?? {}).filter((key) => !["id", "from", "to", "repo", "format", "noCache"].includes(key)); diff --git a/packages/cli/src/reviewers-command.ts b/packages/cli/src/reviewers-command.ts new file mode 100644 index 0000000..6eda141 --- /dev/null +++ b/packages/cli/src/reviewers-command.ts @@ -0,0 +1,164 @@ +import { writeFile } from "node:fs/promises"; +import { resolve } from "node:path"; +import { + renderReviewRoutingMarkdown, + reviewRoutingWithoutMentions, + routeReviewers, + scanRepo, + validateFixMapReport +} from "@aryam/fixmap-core"; +import { describeInputReadError, readDecodedTextFile } from "./decode-input.js"; + +export const REVIEWERS_USAGE = `Usage: fixmap reviewers (--report | --diff | --working-tree) [options] + +Preview: suggests reviewers for each changed path from the highest-precedence CODEOWNERS file +(last matching rule wins), active annotation owners, architecture-policy reviewers, and up to +250 non-merge commits. Commit authors go through the repository's .mailmap when one exists. +FixMap never requests reviews or notifies anyone: names are printed without "@". A name is not +evidence of identity, employment, or current availability. + +Options: + --report Route the changed files (or, if none, the ranked context files) of a saved JSON plan + --diff Route the files changed by a git diff spec, such as main...HEAD + --working-tree Route staged and unstaged changes against HEAD + --no-history-authors Leave out commit-author suggestions; use only CODEOWNERS, annotations, and policy + --repo Local checkout to read (default current directory) + --no-cache Bypass repository scan caches + --format markdown (default) or json + --output Write output to a file instead of stdout + --help, -h Show this help +`; + +type ParsedReviewers = { + report?: string; + diff?: string; + workingTree: boolean; + historyAuthors: boolean; + repo?: string; + noCache: boolean; + format: "markdown" | "json"; + output?: string; +}; + +export async function runReviewersCommand( + args: string[], + io: { + stdout?: (text: string) => void; + stderr?: (text: string) => void; + writeOutput?: (path: string, contents: string) => Promise; + now?: () => string; + } = {} +): Promise { + const stdout = io.stdout ?? ((text: string) => process.stdout.write(text)); + const stderr = io.stderr ?? ((text: string) => process.stderr.write(text)); + if (args.includes("--help") || args.includes("-h")) { + stdout(REVIEWERS_USAGE); + return 0; + } + let parsed: ParsedReviewers; + try { + parsed = parseReviewersArgs(args); + } catch (error) { + stderr(`${error instanceof Error ? error.message : String(error)}\n\n${REVIEWERS_USAGE}`); + return 1; + } + try { + const reportPaths = parsed.report === undefined ? undefined : readReportPaths(parsed.report); + const repo = await scanRepo({ + repoRoot: resolve(parsed.repo ?? process.cwd()), + useCache: !parsed.noCache, + includeHistory: parsed.historyAuthors, + ...(parsed.diff !== undefined ? { diffSpec: parsed.diff } : {}), + ...(parsed.workingTree ? { workingTree: true } : {}) + }); + const scanError = repo.diagnostics.find((diagnostic) => diagnostic.severity === "error"); + if (scanError) throw new Error(scanError.message); + if (parsed.diff !== undefined) { + const unresolved = repo.diagnostics.find((diagnostic) => diagnostic.code === "diff-unavailable"); + if (unresolved) throw new Error(unresolved.message); + } + const result = routeReviewers(repo, { + changedPaths: reportPaths ?? repo.changedFiles, + now: (io.now ?? (() => new Date().toISOString()))(), + includeHistoryAuthors: parsed.historyAuthors + }); + const rendered = parsed.format === "json" + ? `${JSON.stringify(reviewRoutingWithoutMentions(result), null, 2)}\n` + : renderReviewRoutingMarkdown(result); + if (parsed.output) { + await (io.writeOutput ?? ((path, contents) => writeFile(path, contents, "utf8")))(parsed.output, rendered); + } else { + stdout(rendered); + } + return 0; + } catch (error) { + stderr(`${error instanceof Error ? error.message : String(error)}\n`); + return 1; + } +} + +function readReportPaths(path: string): string[] { + let text: string; + try { + text = readDecodedTextFile(path); + } catch (error) { + throw new Error(`Could not read "${path}": ${describeInputReadError(path, error)}`); + } + if (/^\s*#\s*FixMap/i.test(text)) { + throw new Error(`"${path}" is a Markdown report. reviewers --report requires the JSON plan saved with --format json.`); + } + let candidate: unknown; + try { + candidate = JSON.parse(text); + } catch (error) { + throw new Error(`"${path}" is not valid JSON: ${error instanceof Error ? error.message : String(error)}.`); + } + const loaded = validateFixMapReport(candidate, `the JSON in ${path}`); + if (!loaded.success) throw new Error(loaded.message); + const report = loaded.report; + return report.changedFiles.length > 0 ? report.changedFiles : report.contextFiles.map((file) => file.path); +} + +function parseReviewersArgs(args: string[]): ParsedReviewers { + const singles = new Map(); + const booleans = new Set(); + for (let index = 0; index < args.length; index += 1) { + const arg = args[index]!; + if (arg === "--working-tree" || arg === "--no-history-authors" || arg === "--no-cache") { + if (booleans.has(arg)) throw new Error(`Pass ${arg} only once.`); + booleans.add(arg); + continue; + } + const equals = arg.match(/^(--[a-z-]+)=(.*)$/); + const flag = equals?.[1] ?? arg; + if (!["--report", "--diff", "--repo", "--format", "--output"].includes(flag)) { + throw new Error(`Unknown reviewers option: ${arg}`); + } + const value = equals?.[2] ?? args[++index]; + if (typeof value !== "string" || !value.trim() || (!equals && value.startsWith("--"))) { + throw new Error(`${flag} requires a non-blank value.`); + } + if (singles.has(flag)) throw new Error(`Pass ${flag} only once.`); + singles.set(flag, value.trim()); + } + const workingTree = booleans.has("--working-tree"); + const sources = Number(singles.has("--report")) + Number(singles.has("--diff")) + Number(workingTree); + if (sources !== 1) throw new Error("reviewers needs exactly one of --report, --diff, or --working-tree."); + const format = singles.get("--format") ?? "markdown"; + if (format !== "markdown" && format !== "json") throw new Error("--format must be markdown or json."); + const repo = singles.get("--repo"); + if (repo && /^https?:\/\//i.test(repo)) throw new Error("reviewers needs a local checkout; --repo cannot be a URL."); + const report = singles.get("--report"); + const diff = singles.get("--diff"); + const output = singles.get("--output"); + return { + ...(report ? { report } : {}), + ...(diff ? { diff } : {}), + workingTree, + historyAuthors: !booleans.has("--no-history-authors"), + ...(repo ? { repo } : {}), + noCache: booleans.has("--no-cache"), + format, + ...(output ? { output } : {}) + }; +} diff --git a/packages/cli/test/cli-runner.test.ts b/packages/cli/test/cli-runner.test.ts index 7920fb2..450dfce 100644 --- a/packages/cli/test/cli-runner.test.ts +++ b/packages/cli/test/cli-runner.test.ts @@ -199,7 +199,7 @@ describe("CLI argument handling", () => { expect(await runCli(["features", "--format", "json"], catalog.dependencies)).toBe(0); const features = (JSON.parse(catalog.stdout.join("")) as { features: Array<{ name: string; preview?: true }> }).features; expect(features.filter((feature) => feature.preview).map((feature) => feature.name)).toEqual([ - "Change scope", "Product capabilities", "Cross-repository workspace", "Repository Q&A", "Migration planning", + "Change scope", "Reviewer suggestions", "Product capabilities", "Cross-repository workspace", "Repository Q&A", "Migration planning", "Reverse documentation", "Architecture history", "Supply-chain evidence", "Runtime evidence", "Evidence import", "Execution sandbox", "Local hybrid retrieval" ]); @@ -208,7 +208,7 @@ describe("CLI argument handling", () => { const help = capture(); expect(await runCli(["--help"], help.dependencies)).toBe(0); const commands = help.stdout.join("").split("Commands:")[1]?.split("Options:")[0] ?? ""; - for (const command of ["change-scope", "editor", "capability", "capabilities", "workspace", "ask", "migrate", "reverse-docs", "history", "supply-chain", "runtime", "sandbox"]) { + for (const command of ["change-scope", "reviewers", "editor", "capability", "capabilities", "workspace", "ask", "migrate", "reverse-docs", "history", "supply-chain", "runtime", "sandbox"]) { expect(commands).toMatch(new RegExp(`\\n ${command} +Preview: `)); } for (const command of ["plan", "verify", "context", "graph", "annotate", "watch"]) { diff --git a/packages/cli/test/mcp.test.ts b/packages/cli/test/mcp.test.ts index 8c444a5..89c8465 100644 --- a/packages/cli/test/mcp.test.ts +++ b/packages/cli/test/mcp.test.ts @@ -1,4 +1,4 @@ -import { execFile } from "node:child_process"; +import { execFile, execFileSync } from "node:child_process"; import { mkdtemp, mkdir, writeFile, rm, readFile } from "node:fs/promises"; import { createHash } from "node:crypto"; import { tmpdir } from "node:os"; @@ -190,13 +190,38 @@ describe("fixmap mcp server", () => { } }); + it("suggests reviewers read-only and validates fixmap_reviewers arguments", async () => { + const root = await mkdtemp(join(tmpdir(), "fixmap-mcp-reviewers-")); + execFileSync("git", ["init", "-q"], { cwd: root }); + await mkdir(join(root, "src"), { recursive: true }); + await mkdir(join(root, ".github"), { recursive: true }); + await writeFile(join(root, ".github", "CODEOWNERS"), "/src/** @src-team\n"); + await writeFile(join(root, "src", "a.js"), "export const a = 1;\n"); + execFileSync("git", ["add", "-A"], { cwd: root }); + execFileSync("git", ["-c", "user.name=Tester", "-c", "user.email=t@example.com", "-c", "commit.gpgsign=false", "commit", "-q", "-m", "init"], { cwd: root }); + await writeFile(join(root, "src", "a.js"), "export const a = 2;\n"); + const client = await connectClient(); + const { tools } = await client.listTools(); + expect(tools.find((tool) => tool.name === "fixmap_reviewers")?.annotations?.readOnlyHint).toBe(true); + const result = await client.callTool({ name: "fixmap_reviewers", arguments: { workingTree: true, repo: root, noHistoryAuthors: true, noCache: true } }); + expect(result.isError).toBeFalsy(); + const text = (result.content as Array<{ text: string }>)[0]?.text ?? ""; + expect(text).toContain("- `src-team` (high)"); + expect(text).not.toMatch(/(^|[^A-Za-z0-9_.+-])@[A-Za-z0-9]/m); + const invalid = await client.callTool({ name: "fixmap_reviewers", arguments: { workingTree: true, diff: "HEAD", repo: root } }); + expect(invalid.isError).toBe(true); + expect((invalid.content as Array<{ text: string }>)[0]?.text).toContain("exactly one"); + const unknown = await client.callTool({ name: "fixmap_reviewers", arguments: { workingTree: true, requestReviews: true } }); + expect((unknown.content as Array<{ text: string }>)[0]?.text).toContain("unknown argument"); + }); + it("labels every unfinished tool as a preview and leaves finished tools unlabeled", async () => { const client = await connectClient(); const { tools } = await client.listTools(); const preview = tools.filter((tool) => tool.description?.startsWith("Preview (may change before v0.10.0): ")).map((tool) => tool.name).sort(); expect(preview).toEqual([ "fixmap_ask", "fixmap_capability", "fixmap_change_scope", "fixmap_history", "fixmap_migrate", - "fixmap_reverse_docs", "fixmap_runtime", "fixmap_supply_chain", "fixmap_workspace" + "fixmap_reverse_docs", "fixmap_reviewers", "fixmap_runtime", "fixmap_supply_chain", "fixmap_workspace" ]); for (const finished of ["fixmap_plan", "fixmap_context", "fixmap_graph", "fixmap_verify", "fixmap_explain", "fixmap_compare", "fixmap_doctor"]) { expect(preview).not.toContain(finished); @@ -393,7 +418,7 @@ describe("fixmap mcp server", () => { const tools = await client.listTools(); expect(tools.tools.map((tool) => tool.name)).toEqual([ - "fixmap_plan", "fixmap_context", "fixmap_graph", "fixmap_change_scope", "fixmap_capability", "fixmap_workspace", "fixmap_ask", "fixmap_migrate", "fixmap_reverse_docs", "fixmap_history", "fixmap_supply_chain", "fixmap_runtime", "fixmap_verify", "fixmap_explain", "fixmap_compare", "fixmap_doctor", "fixmap_annotate" + "fixmap_plan", "fixmap_context", "fixmap_graph", "fixmap_change_scope", "fixmap_reviewers", "fixmap_capability", "fixmap_workspace", "fixmap_ask", "fixmap_migrate", "fixmap_reverse_docs", "fixmap_history", "fixmap_supply_chain", "fixmap_runtime", "fixmap_verify", "fixmap_explain", "fixmap_compare", "fixmap_doctor", "fixmap_annotate" ]); const plan = tools.tools.find((tool) => tool.name === "fixmap_plan"); const verify = tools.tools.find((tool) => tool.name === "fixmap_verify"); diff --git a/packages/cli/test/reviewers-command.test.ts b/packages/cli/test/reviewers-command.test.ts new file mode 100644 index 0000000..9f1af23 --- /dev/null +++ b/packages/cli/test/reviewers-command.test.ts @@ -0,0 +1,150 @@ +import { execFileSync } from "node:child_process"; +import { mkdir, mkdtemp, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; +import { describe, expect, it } from "vitest"; +import { runReviewersCommand } from "../src/reviewers-command.js"; + +const MENTION = /(^|[^A-Za-z0-9_.+-])@[A-Za-z0-9]/m; + +function git(root: string, args: string[]): string { + return execFileSync("git", ["-c", "commit.gpgsign=false", "-c", "core.autocrlf=false", ...args], { cwd: root, encoding: "utf8" }); +} + +async function commitAs(root: string, author: string, email: string, path: string, contents: string): Promise { + await writeFile(join(root, path), contents); + git(root, ["add", "-A"]); + git(root, ["-c", `user.name=${author}`, "-c", `user.email=${email}`, "commit", "-q", "-m", `edit ${path}`]); +} + +async function fixture(options: { codeowners?: string; mailmap?: string } = {}): Promise { + const root = await mkdtemp(join(tmpdir(), "fixmap-reviewers-")); + git(root, ["init", "-q", "-b", "main"]); + await mkdir(join(root, "src"), { recursive: true }); + await mkdir(join(root, ".github"), { recursive: true }); + await writeFile(join(root, "package.json"), JSON.stringify({ name: "store" })); + if (options.codeowners !== undefined) await writeFile(join(root, ".github", "CODEOWNERS"), options.codeowners); + if (options.mailmap !== undefined) await writeFile(join(root, ".mailmap"), options.mailmap); + await commitAs(root, "alice-laptop", "alice@old.example", "src/auth.js", "export const auth = 1;\n"); + await commitAs(root, "Alice Example", "alice@example.com", "src/auth.js", "export const auth = 2;\n"); + await commitAs(root, "Bob Example", "bob@example.com", "src/auth.js", "export const auth = 3;\n"); + await writeFile(join(root, "src", "auth.js"), "export const auth = 4;\n"); + return root; +} + +function capture() { + const stdout: string[] = []; + const stderr: string[] = []; + return { + stdout, stderr, + io: { stdout: (value: string) => stdout.push(value), stderr: (value: string) => stderr.push(value), now: () => "2026-11-22T00:00:00.000Z" } + }; +} + +type Json = { + changedPaths: string[]; + suggestions: Array<{ reviewer: string; confidence: string; evidence: Array<{ kind: string; detail: string; changedPath?: string; line?: number }> }>; + diagnostics: Array<{ message: string; severity: string }>; +}; + +async function runJson(root: string, extra: string[] = []): Promise { + const output = capture(); + expect(await runReviewersCommand(["--working-tree", "--repo", root, "--format", "json", "--no-cache", ...extra], output.io)).toBe(0); + expect(output.stderr).toEqual([]); + return JSON.parse(output.stdout.join("")) as Json; +} + +describe("fixmap reviewers", () => { + it("routes CODEOWNERS by last matching rule and prints no @ mentions", async () => { + const root = await fixture({ codeowners: "* @global\n/src/** @org/src-team\n/src/auth.js @security dev@example.com\n" }); + const result = await runJson(root); + expect(result.changedPaths).toEqual(["src/auth.js"]); + const high = result.suggestions.filter((entry) => entry.confidence === "high").map((entry) => entry.reviewer); + expect(high.sort()).toEqual(["dev@example.com", "security"]); + expect(result.suggestions.find((entry) => entry.reviewer === "security")?.evidence[0]).toMatchObject({ + kind: "codeowners", line: 3, changedPath: "src/auth.js" + }); + + const markdown = capture(); + expect(await runReviewersCommand(["--working-tree", "--repo", root, "--no-cache"], markdown.io)).toBe(0); + const text = markdown.stdout.join(""); + expect(text).toContain("## `src/auth.js`"); + expect(text).toContain("- `security` (high)"); + expect(text).toContain("`.github/CODEOWNERS:3`"); + expect(text).toContain("does not request reviews"); + expect(text).not.toMatch(MENTION); + expect(JSON.stringify(result)).not.toMatch(/"@|[ (]@[A-Za-z0-9]/); + }); + + it("works without a CODEOWNERS file, from commit history alone", async () => { + const root = await fixture(); + const result = await runJson(root); + expect(result.suggestions.every((entry) => entry.confidence === "low")).toBe(true); + expect(result.suggestions.map((entry) => entry.reviewer).sort()).toEqual(["Alice Example", "Bob Example", "alice-laptop"]); + expect(result.suggestions[0]?.evidence[0]?.detail).toContain("availability or employment is not inferred"); + }); + + it("canonicalizes commit authors through .mailmap before counting", async () => { + const root = await fixture({ mailmap: "Alice Example alice-laptop \n" }); + const result = await runJson(root); + expect(result.suggestions.map((entry) => entry.reviewer)).toEqual(["Alice Example", "Bob Example"]); + expect(result.suggestions[0]?.evidence[0]?.detail).toContain("authored 2 bounded non-merge commits"); + }); + + it("drops commit authors with --no-history-authors", async () => { + const root = await fixture({ codeowners: "/src/** @src-team\n" }); + const result = await runJson(root, ["--no-history-authors"]); + expect(result.suggestions.map((entry) => entry.reviewer)).toEqual(["src-team"]); + expect(result.suggestions.flatMap((entry) => entry.evidence).some((entry) => entry.kind === "git-history")).toBe(false); + expect(result.diagnostics.map((entry) => entry.message).join(" ")).toContain("Commit-author suggestions were turned off"); + }); + + it("warns that a shallow clone only sees part of the history", async () => { + const source = await fixture(); + const parent = await mkdtemp(join(tmpdir(), "fixmap-reviewers-shallow-")); + git(parent, ["clone", "-q", "--depth", "1", pathToFileURL(source).href, "clone"]); + const root = join(parent, "clone"); + await writeFile(join(root, "src", "auth.js"), "export const auth = 5;\n"); + const result = await runJson(root); + expect(result.suggestions.map((entry) => entry.reviewer)).toEqual(["Bob Example"]); + expect(result.diagnostics).toContainEqual(expect.objectContaining({ severity: "warning", message: expect.stringContaining("shallow") })); + }); + + it("routes the changed or ranked files of a saved report and rejects unsafe report paths", async () => { + const root = await fixture({ codeowners: "/src/** @src-team\n" }); + const plan = join(root, "plan.json"); + await writeFile(plan, JSON.stringify({ summary: "", contextFiles: [{ path: "src/auth.js", score: 1, reasons: [] }], testRoutes: [], risks: [], changedFiles: [], diagnostics: [] })); + const output = capture(); + expect(await runReviewersCommand(["--report", plan, "--repo", root, "--format", "json", "--no-cache", "--no-history-authors"], output.io)).toBe(0); + expect((JSON.parse(output.stdout.join("")) as Json).suggestions.map((entry) => entry.reviewer)).toEqual(["src-team"]); + + await writeFile(plan, JSON.stringify({ summary: "", contextFiles: [], testRoutes: [], risks: [], changedFiles: ["../outside.js"], diagnostics: [] })); + const traversal = capture(); + expect(await runReviewersCommand(["--report", plan, "--repo", root, "--no-cache"], traversal.io)).toBe(1); + expect(traversal.stderr.join("")).toContain("safe repository-relative path"); + + await writeFile(plan, "# FixMap report\n"); + const markdown = capture(); + expect(await runReviewersCommand(["--report", plan, "--repo", root], markdown.io)).toBe(1); + expect(markdown.stderr.join("")).toContain("Markdown report"); + }); + + it("validates its arguments", async () => { + for (const args of [[], ["--working-tree", "--diff", "HEAD"], ["--diff"], ["--working-tree", "--format", "yaml"], ["--working-tree", "--bogus"], ["--working-tree", "--repo", "https://github.com/a/b"]]) { + const output = capture(); + expect(await runReviewersCommand(args, output.io)).toBe(1); + expect(output.stderr.join("")).toContain("Usage: fixmap reviewers"); + } + const help = capture(); + expect(await runReviewersCommand(["--help"], help.io)).toBe(0); + expect(help.stdout.join("")).toContain("--no-history-authors"); + }); + + it("fails clearly when a diff spec cannot be resolved", async () => { + const root = await fixture(); + const output = capture(); + expect(await runReviewersCommand(["--diff", "no-such-ref...HEAD", "--repo", root, "--no-cache"], output.io)).toBe(1); + expect(output.stderr.join("")).toContain("no-such-ref"); + }); +}); diff --git a/packages/core/src/browser.ts b/packages/core/src/browser.ts index d524cae..460bbae 100644 --- a/packages/core/src/browser.ts +++ b/packages/core/src/browser.ts @@ -98,8 +98,8 @@ export { addOutcomeRecord, createOutcomeRecord, emptyOutcomeStore, removeOutcome export type { OutcomeCalibration, OutcomeRecord, OutcomeStore, TestOutcomeStatus } from "./outcomes.js"; export { buildChangeDossier, validateChangeDossier } from "./dossier.js"; export type { ChangeDossier, ChangeDossierInput, DossierAssumption } from "./dossier.js"; -export { routeReviewers } from "./ownership.js"; -export type { ReviewEvidence, ReviewRoutingResult, ReviewSuggestion } from "./ownership.js"; +export { renderReviewRoutingMarkdown, reviewRoutingWithoutMentions, routeReviewers, withoutMentions } from "./ownership.js"; +export type { ReviewEvidence, ReviewRoutingInput, ReviewRoutingResult, ReviewSuggestion } from "./ownership.js"; export { analyzeTestReliability, assessReliableCoverage, validateTestHistoryBundle } from "./test-reliability.js"; export type { ReliableCoverageResult, TestHistoryBundle, TestObservationStatus, TestReliabilityAssessment } from "./test-reliability.js"; export { selectCIMatrix } from "./ci-matrix.js"; diff --git a/packages/core/src/feature-catalog.ts b/packages/core/src/feature-catalog.ts index afdea7f..f56c388 100644 --- a/packages/core/src/feature-catalog.ts +++ b/packages/core/src/feature-catalog.ts @@ -16,6 +16,7 @@ export const FIXMAP_FEATURES: readonly FixMapFeature[] = [ { name: "Context Pack", command: "fixmap context --issue --budget 10000", detail: "Select task-aware source ranges from primary and impact files within a deterministic token budget." }, { name: "Graph export", command: "fixmap graph --issue --format mermaid", detail: "Export imports, reverse dependents, routed tests, and co-change evidence as Mermaid or JSON." }, { name: "Change scope", preview: true, command: "fixmap change-scope --touch [--add ]", detail: "Expand explicit planned code surfaces into bounded dependencies, dependents, tests, contracts, decisions, reviewers, and policy evidence without interpreting product requirements." }, + { name: "Reviewer suggestions", preview: true, command: "fixmap reviewers --diff [--no-history-authors]", detail: "Suggest reviewers per changed path from CODEOWNERS (last matching rule wins), annotation owners, architecture policy, and .mailmap-canonical commit authors; names print without @ and never request reviews or imply availability." }, { name: "Product capabilities", preview: true, command: "fixmap capability ", detail: "Persist human-named product capabilities as reviewed path anchors, rebuild their current implementation map, or diff exact Git refs without checkout; generated conclusions never enter the store." }, { name: "Cross-repository workspace", preview: true, command: "fixmap workspace --config .fixmap/workspace.json --seed ", detail: "Resolve Node, Python, and Maven package identities across local checkouts, then trace provider-to-consumer impact with manifest and import evidence." }, { name: "Repository Q&A", preview: true, command: "fixmap ask --report --question ", detail: "Answer structural context, impact, test, risk, and rationale questions from report evidence only, with citations and explicit unknowns." }, @@ -31,7 +32,7 @@ export const FIXMAP_FEATURES: readonly FixMapFeature[] = [ { name: "Verify", command: "fixmap verify --report ", detail: "Compare the completed diff or working tree with the saved plan; add --fail-on warning for a strict CI gate." }, { name: "Validate", command: "fixmap validate ", detail: "Check a saved report against FixMap's structural compatibility contract." }, { name: "Doctor", command: "fixmap doctor", detail: "Diagnose stale local, global, PATH, and npx install shadows." }, - { name: "MCP", command: "fixmap mcp", detail: "Expose Plan, Context, Graph, Change Scope, Capability maps, Workspace, Ask, Migrate, Reverse Docs, History, Supply Chain, Runtime, Explain, Compare, Verify, and Doctor over local stdio." }, + { name: "MCP", command: "fixmap mcp", detail: "Expose Plan, Context, Graph, Change Scope, Reviewers, Capability maps, Workspace, Ask, Migrate, Reverse Docs, History, Supply Chain, Runtime, Explain, Compare, Verify, and Doctor over local stdio." }, { name: "Public tasks", command: "fixmap owner/repository#123", detail: "Fetch public GitHub issue or pull-request text anonymously and scan its repository in an isolated checkout." }, { name: "Repository sources", command: "--repo --ref ", detail: "Map a local checkout, file URL, directory archive, or a named branch or tag from a public GitHub repository." }, { name: "Task files", command: "--issue-file ", detail: "Read long task text from UTF-8, UTF-16, or stdin, including BOM-less UTF-16 from common Windows tools." }, diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index a7cd0cd..68c58a5 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -50,8 +50,8 @@ export { addOutcomeRecord, createOutcomeRecord, emptyOutcomeStore, removeOutcome export type { OutcomeCalibration, OutcomeRecord, OutcomeStore, TestOutcomeStatus } from "./outcomes.js"; export { buildChangeDossier, validateChangeDossier } from "./dossier.js"; export type { ChangeDossier, ChangeDossierInput, DossierAssumption } from "./dossier.js"; -export { routeReviewers } from "./ownership.js"; -export type { ReviewEvidence, ReviewRoutingResult, ReviewSuggestion } from "./ownership.js"; +export { renderReviewRoutingMarkdown, reviewRoutingWithoutMentions, routeReviewers, withoutMentions } from "./ownership.js"; +export type { ReviewEvidence, ReviewRoutingInput, ReviewRoutingResult, ReviewSuggestion } from "./ownership.js"; export { buildSandboxInvocation, runSandbox } from "./sandbox.js"; export type { SandboxInvocation, SandboxLimits, SandboxProcessAdapter, SandboxRawResult, SandboxRequest, SandboxResult } from "./sandbox.js"; export { analyzeTestReliability, assessReliableCoverage, validateTestHistoryBundle } from "./test-reliability.js"; diff --git a/packages/core/src/ownership.ts b/packages/core/src/ownership.ts index f2c6113..2ced153 100644 --- a/packages/core/src/ownership.ts +++ b/packages/core/src/ownership.ts @@ -1,6 +1,7 @@ import { architecturePolicyFromRepo, evaluateArchitecturePolicy } from "./architecture.js"; import { assessAnnotations, validateAnnotationStore } from "./annotations.js"; import { buildPathExcluder } from "./exclude.js"; +import { markdownCode } from "./markdown.js"; import type { RepoMap } from "./types.js"; export type ReviewEvidence = { @@ -9,6 +10,8 @@ export type ReviewEvidence = { detail: string; path?: string; line?: number; + /** The changed path this evidence routes a reviewer for. */ + changedPath?: string; }; export type ReviewSuggestion = { @@ -31,7 +34,14 @@ const CODEOWNERS_PATHS = [".github/CODEOWNERS", "CODEOWNERS", "docs/CODEOWNERS"] const MAX_RULES = 10_000; const MAX_HISTORY_COMMITS = 250; -export function routeReviewers(repo: RepoMap, input: { changedPaths?: readonly string[]; now: string }): ReviewRoutingResult { +export type ReviewRoutingInput = { + changedPaths?: readonly string[]; + now: string; + /** Set false to drop commit-author suggestions and keep only CODEOWNERS, annotations, and policy. */ + includeHistoryAuthors?: boolean; +}; + +export function routeReviewers(repo: RepoMap, input: ReviewRoutingInput): ReviewRoutingResult { if (!Number.isFinite(Date.parse(input.now))) throw new Error("Review routing requires a valid assessment time."); const changedPaths = normalizePaths(input.changedPaths ?? repo.changedFiles); const diagnostics: ReviewRoutingResult["diagnostics"] = []; @@ -39,7 +49,11 @@ export function routeReviewers(repo: RepoMap, input: { changedPaths?: readonly s addCodeOwners(repo, changedPaths, accumulated, diagnostics); addAnnotations(repo, changedPaths, input.now, accumulated, diagnostics); addPolicy(repo, changedPaths, accumulated, diagnostics); - addHistory(repo, changedPaths, accumulated); + if (input.includeHistoryAuthors === false) { + diagnostics.push({ source: "git-history", severity: "info", message: "Commit-author suggestions were turned off; only CODEOWNERS, annotations, and architecture policy were used." }); + } else { + addHistory(repo, changedPaths, accumulated, diagnostics); + } const suggestions = [...accumulated].map(([reviewer, value]): ReviewSuggestion => ({ reviewer, confidence: value.confidence, @@ -169,7 +183,17 @@ function addPolicy( } } -function addHistory(repo: RepoMap, paths: readonly string[], accumulated: Map): void { +function addHistory( + repo: RepoMap, + paths: readonly string[], + accumulated: Map, + diagnostics: ReviewRoutingResult["diagnostics"] +): void { + if (repo.history?.shallow) { + diagnostics.push({ source: "git-history", severity: "warning", message: "Commit history is shallow, so commit-author suggestions only reflect the commits present in this clone." }); + } else if (repo.history?.truncated) { + diagnostics.push({ source: "git-history", severity: "info", message: `Commit-author suggestions use only the newest ${Math.min(repo.history.inspectedCommits, MAX_HISTORY_COMMITS).toLocaleString()} non-merge commits.` }); + } for (const path of paths) { const counts = new Map(); for (const commit of (repo.history?.commits ?? []).slice(0, MAX_HISTORY_COMMITS)) { @@ -205,7 +229,8 @@ function add( const existing = accumulated.get(identity) ?? { confidence, paths: new Set(), evidence: [] }; if (confidenceOrder(confidence) < confidenceOrder(existing.confidence)) existing.confidence = confidence; existing.paths.add(path); - if (!existing.evidence.some((entry) => evidenceKey(entry) === evidenceKey(evidence))) existing.evidence.push(evidence); + const routed = { ...evidence, changedPath: path }; + if (!existing.evidence.some((entry) => evidenceKey(entry) === evidenceKey(routed))) existing.evidence.push(routed); accumulated.set(identity, existing); } function normalizePaths(values: readonly string[]): string[] { @@ -222,6 +247,72 @@ function validOwner(value: string): boolean { return value.length <= 200 && (/^@[A-Za-z0-9][A-Za-z0-9_.-]*(?:\/[A-Za-z0-9][A-Za-z0-9_.-]*)?$/.test(value) || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)); } -function evidenceKey(value: ReviewEvidence): string { return `${value.kind}\0${value.sourceFingerprint}\0${value.path ?? ""}\0${value.line ?? ""}\0${value.detail}`; } -function evidenceOrder(a: ReviewEvidence, b: ReviewEvidence): number { return a.kind.localeCompare(b.kind) || (a.path ?? "").localeCompare(b.path ?? "") || (a.line ?? 0) - (b.line ?? 0); } +function evidenceKey(value: ReviewEvidence): string { return `${value.kind}\0${value.sourceFingerprint}\0${value.path ?? ""}\0${value.line ?? ""}\0${value.changedPath ?? ""}\0${value.detail}`; } +function evidenceOrder(a: ReviewEvidence, b: ReviewEvidence): number { + return a.kind.localeCompare(b.kind) || (a.changedPath ?? "").localeCompare(b.changedPath ?? "") || + (a.path ?? "").localeCompare(b.path ?? "") || (a.line ?? 0) - (b.line ?? 0); +} function confidenceOrder(value: ReviewSuggestion["confidence"]): number { return value === "high" ? 0 : value === "medium" ? 1 : 2; } + +/** + * GitHub notifies anyone written as `@name`. Reviewer output is only a suggestion, so every + * handle-style mention loses its `@`; e-mail addresses (a word character before `@`) stay. + */ +export function withoutMentions(value: string): string { + return value.replace(/(^|[^A-Za-z0-9_.+-])@+(?=[A-Za-z0-9])/g, "$1"); +} + +/** A copy of the routing result that is safe to print or post where `@name` would notify someone. */ +export function reviewRoutingWithoutMentions(result: ReviewRoutingResult): ReviewRoutingResult { + return { + ...result, + suggestions: result.suggestions.map((suggestion) => ({ + ...suggestion, + reviewer: withoutMentions(suggestion.reviewer), + evidence: suggestion.evidence.map((entry) => ({ ...entry, detail: withoutMentions(entry.detail) })) + })).sort((a, b) => confidenceOrder(a.confidence) - confidenceOrder(b.confidence) || a.reviewer.localeCompare(b.reviewer)), + diagnostics: result.diagnostics.map((entry) => ({ ...entry, message: withoutMentions(entry.message) })) + }; +} + +const EVIDENCE_LABEL: Record = { + codeowners: "CODEOWNERS", + annotation: "annotation", + "architecture-policy": "architecture policy", + "git-history": "commit history" +}; + +/** Markdown grouped by changed path. Names are code spans without `@`, so nobody is notified. */ +export function renderReviewRoutingMarkdown(input: ReviewRoutingResult): string { + const result = reviewRoutingWithoutMentions(input); + const lines = [ + "# FixMap reviewer suggestions (preview)", + "", + "Suggestions only. FixMap does not request reviews or notify anyone, and a name is not evidence of identity, employment, or current availability.", + "" + ]; + if (result.changedPaths.length === 0) lines.push("No changed paths, so there is nothing to route.", ""); + for (const path of result.changedPaths) { + lines.push(`## ${markdownCode(path)}`, ""); + const rows = result.suggestions + .map((suggestion) => ({ suggestion, evidence: suggestion.evidence.filter((entry) => entry.changedPath === path) })) + .filter((row) => row.evidence.length > 0); + if (rows.length === 0) lines.push("- No reviewer evidence for this path."); + for (const { suggestion, evidence } of rows) { + lines.push(`- ${markdownCode(suggestion.reviewer)} (${suggestion.confidence})`); + for (const entry of evidence) { + const source = entry.kind !== "git-history" && entry.path + ? ` ${markdownCode(entry.line === undefined ? entry.path : `${entry.path}:${entry.line}`)}` + : ""; + lines.push(` - ${EVIDENCE_LABEL[entry.kind]}${source}: ${entry.detail}`); + } + } + lines.push(""); + } + if (result.diagnostics.length > 0) { + lines.push("## Diagnostics", ""); + for (const entry of result.diagnostics) lines.push(`- ${entry.severity} (${markdownCode(entry.source)}): ${entry.message}`); + lines.push(""); + } + return `${lines.join("\n").trimEnd()}\n`; +} diff --git a/packages/core/test/ownership.test.ts b/packages/core/test/ownership.test.ts index d00db6c..1c6edad 100644 --- a/packages/core/test/ownership.test.ts +++ b/packages/core/test/ownership.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; import { addAnnotation, createAnnotation, emptyAnnotationStore } from "../src/annotations.js"; -import { routeReviewers } from "../src/ownership.js"; +import { renderReviewRoutingMarkdown, reviewRoutingWithoutMentions, routeReviewers, withoutMentions } from "../src/ownership.js"; import type { RepoFile, RepoMap } from "../src/types.js"; function file(path: string, textSample: string, fingerprint = `worktree:${"a".repeat(64)}`): RepoFile { @@ -90,4 +90,36 @@ describe("review routing", () => { expect(() => routeReviewers(current, { changedPaths: ["../outside"], now: "2026-08-21T00:00:00Z" })) .toThrow("Invalid review-routing path"); }); + + it("drops commit authors on request and diagnoses shallow history", () => { + const current = repo([file("src/auth.ts", "code"), file(".github/CODEOWNERS", "/src/** @src\n")]); + const without = routeReviewers(current, { now: "2026-08-21T00:00:00Z", includeHistoryAuthors: false }); + expect(without.suggestions.map((entry) => entry.reviewer)).toEqual(["@src"]); + expect(without.diagnostics[0]?.message).toContain("turned off"); + + current.history!.shallow = true; + const shallow = routeReviewers(current, { now: "2026-08-21T00:00:00Z" }); + expect(shallow.suggestions.map((entry) => entry.reviewer)).toEqual(["@src", "Alice Example", "Bob Example"]); + expect(shallow.diagnostics).toContainEqual(expect.objectContaining({ severity: "warning", message: expect.stringContaining("shallow") })); + }); + + it("records which changed path each piece of evidence routes", () => { + const current = repo([file("src/a.ts", "a"), file("src/b.ts", "b"), file(".github/CODEOWNERS", "/src/** @src\n")]); + current.history = undefined; + const result = routeReviewers(current, { changedPaths: ["src/b.ts", "src/a.ts"], now: "2026-08-21T00:00:00Z" }); + expect(result.suggestions[0]?.evidence.map((entry) => entry.changedPath)).toEqual(["src/a.ts", "src/b.ts"]); + }); + + it("strips handle mentions but keeps e-mail addresses", () => { + expect(withoutMentions("@security and @org/team, (@x) dev@example.com @@twice")).toBe("security and org/team, (x) dev@example.com twice"); + const current = repo([file("src/auth.ts", "code"), file(".github/CODEOWNERS", "/src/** @src ops@example.com\n")]); + const result = routeReviewers(current, { now: "2026-08-21T00:00:00Z" }); + const safe = reviewRoutingWithoutMentions(result); + expect(safe.suggestions.map((entry) => entry.reviewer)).toEqual(["ops@example.com", "src", "Alice Example", "Bob Example"]); + const markdown = renderReviewRoutingMarkdown(result); + expect(markdown).toContain("- `src` (high)"); + expect(markdown).toContain("CODEOWNERS `.github/CODEOWNERS:1`"); + expect(markdown).not.toMatch(/(^|[^A-Za-z0-9_.+-])@[A-Za-z0-9]/m); + expect(renderReviewRoutingMarkdown({ ...result, changedPaths: [], suggestions: [] })).toContain("No changed paths"); + }); });