From 62175bad6f97aa0c061d88795fd8981d171ca9a5 Mon Sep 17 00:00:00 2001 From: Aryam Goyal Date: Mon, 23 Nov 2026 19:48:46 +0530 Subject: [PATCH] feat: plan alternatives and MCP capability editing (preview) Add preview fixmap alternatives (--input, or --report with an explicit --graph-fingerprint), a saved-report adapter, side-by-side Markdown trade-offs without a winner, and the read-only fixmap_alternatives MCP tool. fixmap_capability gains action create|update|remove routed through the CLI write path (lock, atomic replace, containment, link refusal). Co-Authored-By: Claude Opus 5.5 --- packages/cli/README.md | 4 +- packages/cli/src/alternatives-command.ts | 305 ++++++++++++++++++ packages/cli/src/cli-runner.ts | 11 + packages/cli/src/mcp.ts | 110 ++++++- .../cli/test/alternatives-command.test.ts | 142 ++++++++ packages/cli/test/cli-runner.test.ts | 4 +- packages/cli/test/mcp.test.ts | 135 +++++++- packages/core/src/feature-catalog.ts | 3 +- 8 files changed, 704 insertions(+), 10 deletions(-) create mode 100644 packages/cli/src/alternatives-command.ts create mode 100644 packages/cli/test/alternatives-command.test.ts diff --git a/packages/cli/README.md b/packages/cli/README.md index 593d4a4..10e59a7 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -164,10 +164,11 @@ For long task text, use `--issue-file task.md`, pipe it directly to `fixmap plan - **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. +- **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. MCP: `fixmap_capability` reads by default and writes through the same locked path with `action: "create" | "update" | "remove"`. - **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. - **Migration planner** — use `fixmap migrate --input ` to validate and render dependency phases, blast radius, compatibility, verification, and rollback without executing or applying the plan. +- **Plan alternatives** (preview) — use `fixmap alternatives --input `, or `--report ` twice or more with `--graph-fingerprint `, to compare 2-20 plans for the same graph state side by side on edits, blast radius, contract compatibility, policy, tests, reversibility, and uncertainty. FixMap states each trade-off from the evidence and never picks a winner by score. MCP: `fixmap_alternatives`. - **Reverse documentation** — use `fixmap reverse-docs --input ` to create review-only module or architecture drafts from exact structural evidence without writing the requested destination. - **Architecture history** — use `fixmap history --repo . --from --to ` to compare immutable committed snapshots without checkout or worktree mutation. It also reports decision disagreements: edges at `--to` that break an import rule stated by an accepted decision record in `fixmap-deny-imports` frontmatter (one `from-pattern -> denied-pattern` per item). Snapshots are cached per exact commit outside the repository; `--no-cache` rebuilds them. - **Historical plans (preview)** — `fixmap plan --issue --at ` ranks against the repository as it was at that commit, read from Git objects without checking out or changing the worktree. @@ -226,6 +227,7 @@ fixmap graph Export the Impact Graph as Mermaid or JSON fixmap workspace Map package dependencies and impact across local repositories fixmap ask Answer report-only structural questions with citations fixmap migrate Build a dependency-ordered, review-only migration plan +fixmap alternatives Compare alternative plans side by side without picking a winner fixmap reverse-docs Draft review-only documentation from exact structural evidence fixmap history Compare architecture at two committed refs without checkout fixmap supply-chain Import normalized external scanner and SBOM evidence diff --git a/packages/cli/src/alternatives-command.ts b/packages/cli/src/alternatives-command.ts new file mode 100644 index 0000000..63f515d --- /dev/null +++ b/packages/cli/src/alternatives-command.ts @@ -0,0 +1,305 @@ +import { writeFile } from "node:fs/promises"; +import { basename, resolve } from "node:path"; +import { + comparePlanAlternatives, + createGraphIdentity, + validateFixMapReport, + type AlternativePlanComparison, + type FixMapReport, + type PlanAlternative, + type PlanAlternativeAssessment +} from "@aryam/fixmap-core"; +import { describeInputReadError, readDecodedTextFile } from "./decode-input.js"; + +export const ALTERNATIVES_USAGE = `Usage: + fixmap alternatives --input [--format markdown|json] [--output ] + fixmap alternatives --report --report --graph-fingerprint [options] + +Compares 2-20 alternative plans for the same graph state side by side: intended edits, impact, +contract and total blast radius, contract compatibility, policy errors and warnings, planned tests, +reversibility and uncertainty. FixMap never picks a winner or folds the axes into a score; it lists +each trade-off with the evidence behind it and names the plans no other plan beats on every axis. + +Options: + --input Version-1 input: {"alternativesInputVersion": 1, "alternatives": [...]} + --report Saved FixMap JSON plan to compare (repeatable; may be mixed with --input) + --graph-fingerprint Graph state every --report was planned against, such as the commit SHA. + A saved plan does not record it, so you state it. + --format markdown (default) or json + --output Write the comparison to a file instead of stdout +`; + +export type AlternativesSource = { + /** Version-1 input object, or a path to a JSON file holding one. */ + input?: unknown; + /** Saved FixMap JSON plan report paths. */ + reports?: string[]; + graphFingerprint?: string; +}; + +type Dependencies = { + stdout?: (text: string) => void; + stderr?: (text: string) => void; + writeOutput?: (path: string, contents: string) => Promise; +}; + +export async function runAlternativesCommand(args: string[], dependencies: Dependencies = {}): Promise { + const stdout = dependencies.stdout ?? ((text: string) => process.stdout.write(text)); + const stderr = dependencies.stderr ?? ((text: string) => process.stderr.write(text)); + if (args.includes("--help") || args.includes("-h")) { stdout(ALTERNATIVES_USAGE); return 0; } + let parsed: ReturnType; + try { + parsed = parseArgs(args); + } catch (error) { + stderr(`${message(error)}\n\n${ALTERNATIVES_USAGE}`); + return 1; + } + const inputs = [parsed.input, ...parsed.reports].filter((path): path is string => Boolean(path)); + if (parsed.output && inputs.some((path) => samePath(resolve(path), resolve(parsed.output!)))) { + stderr("alternatives --output must not overwrite an input file.\n"); + return 1; + } + try { + const comparison = compareAlternativesFromSources(parsed); + const rendered = parsed.format === "json" ? `${JSON.stringify(comparison, null, 2)}\n` : renderAlternativesMarkdown(comparison); + if (parsed.output) await (dependencies.writeOutput ?? ((path, contents) => writeFile(path, contents, "utf8")))(parsed.output, rendered); + else stdout(rendered); + return 0; + } catch (error) { + stderr(`Could not compare plan alternatives: ${message(error)}\n`); + return 1; + } +} + +/** Shared by the CLI and MCP: loads every source, then lets Core validate and compare them. */ +export function compareAlternativesFromSources(source: AlternativesSource): AlternativePlanComparison { + const reports = source.reports ?? []; + if (source.input === undefined && reports.length === 0) throw new Error("Provide an alternatives input, saved plan reports, or both."); + if (reports.length > 0 && !source.graphFingerprint) { + throw new Error("Comparing saved plans requires a graph fingerprint (for example the commit SHA they were planned at); a saved plan does not record one."); + } + if (reports.length === 0 && source.graphFingerprint) throw new Error("A graph fingerprint applies only to saved plan reports."); + const alternatives: PlanAlternative[] = []; + if (source.input !== undefined) { + const raw = typeof source.input === "string" ? readJson(source.input, "alternatives input") : source.input; + alternatives.push(...parseAlternativesInput(raw)); + } + const used = new Set(alternatives.map((alternative) => alternative.id)); + for (const path of reports) { + const report = loadPlanReport(path); + const alternative = planAlternativeFromReport(report, { id: uniqueId(idFromPath(path), used), graphFingerprint: source.graphFingerprint! }); + used.add(alternative.id); + alternatives.push(alternative); + } + return comparePlanAlternatives(alternatives); +} + +export function parseAlternativesInput(value: unknown): PlanAlternative[] { + if (!isRecord(value) || value.alternativesInputVersion !== 1) throw new Error("Alternatives input alternativesInputVersion must be 1."); + if (!Array.isArray(value.alternatives)) throw new Error("Alternatives input alternatives must be an array."); + return value.alternatives as PlanAlternative[]; +} + +/** + * Report adapter. A saved plan carries ranked files, impact, test routes, risks and policy findings but + * no graph state, contract diff or rollback plan, so each mapping below uses only what the report says. + */ +export function planAlternativeFromReport(report: FixMapReport, options: { id: string; graphFingerprint: string }): PlanAlternative { + const editPaths = [...new Set(report.impact?.seeds.length ? report.impact.seeds : report.contextFiles.map((file) => file.path))]; + if (editPaths.length === 0) throw new Error(`Plan ${options.id} has no ranked context files or impact seeds to treat as intended edits.`); + const edits = new Set(editPaths); + const impactByPath = new Map((report.impact?.files ?? []).map((file) => [file.path, file])); + const breaking = new Map(); + for (const finding of report.policy?.findings ?? []) { + if (finding.code !== "breaking-contract") continue; + for (const path of finding.paths) if (!breaking.has(path)) breaking.set(path, finding.message); + } + const tests = report.testRoutes.filter((route) => route.kind === "test").map((route) => { + const covers = new Set(); + for (const path of route.relatedFiles) { + if (edits.has(path)) covers.add(path); + for (const evidence of impactByPath.get(path)?.evidence ?? []) { + if ((evidence.kind === "test-route" || evidence.kind === "imported-by") && edits.has(evidence.seed)) covers.add(evidence.seed); + } + } + return { command: bounded(route.command), covers: [...covers].map(fileIdentity), reason: bounded(route.reason) }; + }); + const uncertainties: PlanAlternative["uncertainties"] = report.risks.map((risk, index) => ({ + id: `risk-${index + 1}`, + severity: risk.severity, + detail: bounded(`${risk.area}: ${risk.reason}`) + })); + if (report.analysis?.grounding.specificity === "vague") { + uncertainties.push({ id: "vague-task", severity: "high", detail: "The task named nothing FixMap could anchor to a file or identifier." }); + } + const unresolved = report.analysis?.grounding.unresolvedIdentifiers ?? []; + if (unresolved.length > 0) { + uncertainties.push({ id: "unresolved-identifiers", severity: "medium", detail: bounded(`Identifiers not found in the repository: ${unresolved.join(", ")}`) }); + } + return { + planAlternativeVersion: 1, + id: options.id, + graphFingerprint: options.graphFingerprint, + edits: editPaths.map(fileIdentity), + impacts: [...impactByPath.keys()].filter((path) => !edits.has(path)).map(fileIdentity), + contracts: [...breaking].map(([path, reason]) => ({ identity: fileIdentity(path), compatibility: "breaking" as const, reason: bounded(reason) })), + policyFindings: (report.policy?.findings ?? []).map((finding) => ({ ruleId: safeId(finding.ruleId), severity: finding.severity, message: bounded(finding.message) })), + tests, + // Source edits can be reverted in version control; a plan records nothing about deploys or data, so this stays partial. + reversibility: { + mode: "partial", + reason: "A saved plan does not record deploy, data or migration effects; only the source edits are known to be revertible.", + rollbackSteps: ["Revert the planned edits in version control."] + }, + uncertainties + }; +} + +type Direction = "lower" | "higher"; +const AXES: Array<{ axis: string; label: string; direction: Direction; value: (entry: PlanAlternativeAssessment) => number | string }> = [ + { axis: "edit-identities", label: "Intended edits", direction: "lower", value: (entry) => entry.metrics.editIdentities }, + { axis: "impact-identities", label: "Impact identities", direction: "lower", value: (entry) => entry.metrics.impactIdentities }, + { axis: "contract-identities", label: "Contract identities", direction: "lower", value: (entry) => entry.metrics.contractIdentities }, + { axis: "blast-radius-identities", label: "Total blast radius", direction: "lower", value: (entry) => entry.metrics.totalBlastRadiusIdentities }, + { axis: "breaking-contracts", label: "Breaking contracts", direction: "lower", value: (entry) => entry.metrics.breakingContracts }, + { axis: "unknown-contracts", label: "Unknown contracts", direction: "lower", value: (entry) => entry.metrics.unknownContracts }, + { axis: "policy-errors", label: "Policy errors", direction: "lower", value: (entry) => entry.metrics.policyErrors }, + { axis: "policy-warnings", label: "Policy warnings", direction: "lower", value: (entry) => entry.metrics.policyWarnings }, + { axis: "planned-tests", label: "Planned tests", direction: "higher", value: (entry) => entry.metrics.plannedTests }, + { axis: "covered-edit-identities", label: "Edits with test coverage", direction: "higher", value: (entry) => entry.metrics.coveredEditIdentities }, + { axis: "uncovered-edits", label: "Edits without test coverage", direction: "lower", value: (entry) => entry.metrics.uncoveredEditIdentities.length }, + { axis: "reversibility", label: "Reversibility", direction: "higher", value: (entry) => entry.metrics.reversibility }, + { axis: "high-uncertainties", label: "High uncertainties", direction: "lower", value: (entry) => entry.metrics.highUncertainties }, + { axis: "medium-uncertainties", label: "Medium uncertainties", direction: "lower", value: (entry) => entry.metrics.mediumUncertainties } +]; + +export function renderAlternativesMarkdown(comparison: AlternativePlanComparison): string { + const ids = comparison.alternatives.map((entry) => entry.id); + const lines = [ + "# FixMap plan alternatives", + "", + `Graph fingerprint: ${code(comparison.graphFingerprint)}`, + `Comparison fingerprint: ${code(comparison.fingerprint)}`, + "", + "FixMap does not pick a winner. Each axis is compared on its own; which trade-off matters is your call.", + "", + "## Side by side", + "", + `| Axis | ${ids.map(code).join(" | ")} |`, + `| --- | ${ids.map(() => "---").join(" | ")} |`, + ...AXES.map((axis) => `| ${axis.label} (${axis.direction} is better) | ${comparison.alternatives.map((entry) => String(axis.value(entry))).join(" | ")} |`), + "", + "## Trade-offs", + "" + ]; + for (const pair of comparison.pairwise) { + const leftBetter: string[] = []; + const rightBetter: string[] = []; + for (const difference of pair.differences) { + const axis = AXES.find((entry) => entry.axis === difference.axis); + if (!axis) continue; + // Each line reads from the better plan's side: " vs ". + if (better(axis.direction, difference.left, difference.right)) leftBetter.push(`${axis.label.toLowerCase()} (${difference.left} vs ${difference.right})`); + else rightBetter.push(`${axis.label.toLowerCase()} (${difference.right} vs ${difference.left})`); + } + if (leftBetter.length === 0 && rightBetter.length === 0) { + lines.push(`- ${code(pair.left)} and ${code(pair.right)} are equal on every compared axis.`); + continue; + } + lines.push(`- ${code(pair.left)} vs ${code(pair.right)}:`); + lines.push(` - ${code(pair.left)} is better on ${leftBetter.length > 0 ? leftBetter.join(", ") : "no axis"}.`); + lines.push(` - ${code(pair.right)} is better on ${rightBetter.length > 0 ? rightBetter.join(", ") : "no axis"}.`); + } + lines.push( + "", + `Not beaten on every axis by another plan: ${comparison.nonDominatedAlternatives.map(code).join(", ")}.`, + "Planned-test and coverage counts are shown but do not decide this; more tests are not automatically better.", + "", + "## Evidence", + "" + ); + for (const entry of comparison.alternatives) { + lines.push(`### ${code(entry.id)}`, ""); + for (const evidence of entry.evidence) { + const identities = evidence.identities && evidence.identities.length > 0 && evidence.axis !== "edits" && evidence.axis !== "impact" + ? ` ${evidence.axis === "tests" ? "Uncovered" : "Identities"}: ${evidence.identities.slice(0, 10).map(code).join(", ")}${evidence.identities.length > 10 ? `, and ${evidence.identities.length - 10} more` : ""}.` + : ""; + lines.push(`- **${evidence.axis}**: ${evidence.detail}${identities}`); + } + lines.push(""); + } + lines.push("> Review-only comparison. FixMap did not execute, apply or rank these plans."); + return `${lines.join("\n")}\n`; +} + +function better(direction: Direction, left: string | number, right: string | number): boolean { + if (typeof left === "string" || typeof right === "string") { + const rank = (value: string | number) => (value === "full" ? 2 : value === "partial" ? 1 : 0); + return rank(left) > rank(right); + } + return direction === "lower" ? left < right : left > right; +} + +function parseArgs(args: string[]) { + const reports: string[] = []; + const singles = new Map(); + for (let index = 0; index < args.length; index += 1) { + const raw = args[index]!; + const equals = raw.match(/^(--[a-z-]+)=(.*)$/); + const flag = equals?.[1] ?? raw; + if (!["--input", "--report", "--graph-fingerprint", "--format", "--output"].includes(flag)) throw new Error(`Unknown alternatives option: ${raw}`); + const value = equals?.[2] ?? args[++index]; + if (typeof value !== "string" || !value.trim() || (!equals && value.startsWith("--"))) throw new Error(`${flag} requires a value.`); + if (flag === "--report") reports.push(value.trim()); + else if (singles.has(flag)) throw new Error(`Pass ${flag} only once.`); + else singles.set(flag, value.trim()); + } + const format = (singles.get("--format") ?? "markdown").toLowerCase(); + if (format !== "markdown" && format !== "json") throw new Error("--format must be markdown or json."); + const input = singles.get("--input"); + if (!input && reports.length === 0) throw new Error("alternatives requires --input or --report (repeatable)."); + const graphFingerprint = singles.get("--graph-fingerprint"); + const output = singles.get("--output"); + return { + format: format as "markdown" | "json", + reports, + ...(input ? { input } : {}), + ...(graphFingerprint ? { graphFingerprint } : {}), + ...(output ? { output } : {}) + }; +} + +function loadPlanReport(path: string): FixMapReport { + const loaded = validateFixMapReport(readJson(path, "plan report"), `"${path}"`); + if (!loaded.success) throw new Error(loaded.message); + return loaded.report; +} + +function readJson(path: string, label: string): unknown { + let text: string; + try { + text = readDecodedTextFile(path); + } catch (error) { + throw new Error(`Could not read ${label} ${describeInputReadError(path, error)}`); + } + try { + return JSON.parse(text) as unknown; + } catch { + throw new Error(`${label} "${path}" is not valid JSON.`); + } +} + +function fileIdentity(path: string): string { return createGraphIdentity({ workspace: "local", kind: "file", key: path }); } +function idFromPath(path: string): string { return safeId(basename(path).replace(/\.json$/i, "")); } +function safeId(value: string): string { + return value.replace(/[^A-Za-z0-9._:-]+/g, "-").replace(/^[^A-Za-z0-9]+/, "").slice(0, 120) || "plan"; +} +function uniqueId(base: string, used: Set): string { + if (!used.has(base)) return base; + for (let suffix = 2; ; suffix += 1) if (!used.has(`${base}-${suffix}`)) return `${base}-${suffix}`; +} +function bounded(value: string): string { return value.trim().slice(0, 1_000) || "Not stated in the plan."; } +function code(value: string): string { return `\`${value.replaceAll("`", "'")}\``; } +function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } +function samePath(left: string, right: string): boolean { return process.platform === "win32" ? left.toLowerCase() === right.toLowerCase() : left === right; } +function message(error: unknown): string { return error instanceof Error ? error.message : String(error); } diff --git a/packages/cli/src/cli-runner.ts b/packages/cli/src/cli-runner.ts index 7fea78c..10548ab 100644 --- a/packages/cli/src/cli-runner.ts +++ b/packages/cli/src/cli-runner.ts @@ -114,6 +114,7 @@ Usage: fixmap workspace --config .fixmap/workspace.json --seed auth --format json fixmap ask --report plan.json --question "Which tests should I run?" fixmap migrate --input migration.json --format markdown + fixmap alternatives --report plan-a.json --report plan-b.json --graph-fingerprint fixmap reverse-docs --input reverse-docs.json --format markdown fixmap history --repo . --from v0.9.0 --to HEAD fixmap contracts diff v0.9.0..HEAD @@ -144,6 +145,7 @@ Commands: workspace Preview: Map package dependencies and impact across local repositories ask Preview: Answer structural questions from a saved report with citations migrate Preview: Build a dependency-ordered, review-only migration plan + alternatives Preview: Compare alternative plans side by side without picking a winner reverse-docs Preview: Draft review-only documentation from exact structural evidence history Preview: Compare architecture at two committed Git refs without checkout contracts Preview: List API/schema contracts or diff them across Git refs without checkout @@ -555,6 +557,15 @@ export async function runCli(args: string[], dependencies: CliDependencies = {}) }); } + if (args[0] === "alternatives") { + const { runAlternativesCommand } = await import("./alternatives-command.js"); + return runAlternativesCommand(args.slice(1), { + stdout, + stderr, + ...(dependencies.writeReport ? { writeOutput: dependencies.writeReport } : {}) + }); + } + if (args[0] === "reverse-docs") { const { runReverseDocsCommand } = await import("./reverse-docs-command.js"); return runReverseDocsCommand(args.slice(1), { diff --git a/packages/cli/src/mcp.ts b/packages/cli/src/mcp.ts index d775a70..f7017d5 100644 --- a/packages/cli/src/mcp.ts +++ b/packages/cli/src/mcp.ts @@ -51,6 +51,7 @@ 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 { compareAlternativesFromSources, renderAlternativesMarkdown } from "./alternatives-command.js"; import { runContractsCommand } from "./contracts-command.js"; import { buildReportForRepository, @@ -341,11 +342,22 @@ const CAPABILITY_TOOL = { title: "FixMap capability", description: "Preview (may change before v0.10.0): List human-owned product capabilities, rebuild one current capability map, or compare it across exact Git refs from .fixmap/capabilities.json. " + + "With action create, update, or remove it writes .fixmap/capabilities.json through the same locked, atomic, symlink-refusing path as fixmap capability; use an action only when the user asks for that change. " + "The store contains explicit names, anchors, and bounds only; no generated conclusions, API, LLM, semantic inference, or account.", + annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false }, inputSchema: { type: "object" as const, properties: { - id: { type: "string", description: "Capability id to show; omit to list definitions" }, + action: { type: "string", enum: ["create", "update", "remove"], description: "Change the store; omit to read" }, + id: { type: "string", description: "Capability id to show or change; omit to list definitions" }, + name: { type: "string", description: "Human-facing capability name (create/update)" }, + touch: { type: "array", items: { type: "string" }, description: "Existing implementation anchors (create/update)" }, + add: { type: "array", items: { type: "string" }, description: "Planned path anchors; missing paths stay unresolved (create/update)" }, + direction: { type: "string", enum: ["dependencies", "dependents", "both"], description: "Traversal direction (create/update)" }, + depth: { type: "integer", minimum: 0, maximum: 8, description: "Maximum traversal depth (create/update)" }, + maxNodes: { type: "integer", minimum: 1, maximum: 2000, description: "Maximum selected plus affected nodes (create/update)" }, + workspace: { type: "string", description: "Store workspace identity when creating the first capability" }, + repository: { type: "string", description: "Store repository identity when creating the first capability" }, from: { type: "string", description: "Earlier exact Git ref; requires id and to" }, to: { type: "string", description: "Later exact Git ref; requires id and from" }, repo: { type: "string", description: "Local checkout path (defaults to the MCP server repository)" }, @@ -356,6 +368,29 @@ const CAPABILITY_TOOL = { } }; +const ALTERNATIVES_TOOL = { + name: "fixmap_alternatives", + title: "FixMap plan alternatives", + description: + "Preview (may change before v0.10.0): Compare 2-20 alternative plans on the same exact graph fingerprint side by side: intended edits, impact, contract and total blast radius, contract compatibility, policy errors and warnings, planned tests, reversibility, and uncertainty. " + + "Provide a version-1 alternatives input, saved FixMap JSON plan paths with the graphFingerprint they were planned against, or both. " + + "It never picks a winner or scores plans; it states each trade-off from the evidence. Read-only.", + annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }, + inputSchema: { + type: "object" as const, + properties: { + input: { + description: "Version-1 alternatives input object or path to a local JSON input file", + anyOf: [{ type: "object" }, { type: "string" }] + }, + reports: { type: "array", items: { type: "string" }, description: "Paths to saved FixMap JSON plans, one alternative each" }, + graphFingerprint: { type: "string", description: "Graph state every report was planned against, such as the commit SHA; required with reports" }, + format: { type: "string", description: "Output format: markdown (default) or json, case-insensitive" } + }, + additionalProperties: false + } +}; + const ASK_TOOL = { name: "fixmap_ask", title: "FixMap ask", @@ -572,7 +607,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, REVIEWERS_TOOL, CAPABILITY_TOOL, WORKSPACE_TOOL, ASK_TOOL, MIGRATION_TOOL, REVERSE_DOCS_TOOL, HISTORY_TOOL, CONTRACTS_TOOL, SUPPLY_CHAIN_TOOL, RUNTIME_TOOL, VERIFY_TOOL, EXPLAIN_TOOL, COMPARE_TOOL, DOCTOR_TOOL, ANNOTATION_TOOL, OUTCOMES_TOOL, DOSSIER_TOOL] + tools: [PLAN_TOOL, CONTEXT_TOOL, GRAPH_TOOL, CHANGE_SCOPE_TOOL, REVIEWERS_TOOL, CAPABILITY_TOOL, WORKSPACE_TOOL, ASK_TOOL, MIGRATION_TOOL, ALTERNATIVES_TOOL, REVERSE_DOCS_TOOL, HISTORY_TOOL, CONTRACTS_TOOL, SUPPLY_CHAIN_TOOL, RUNTIME_TOOL, VERIFY_TOOL, EXPLAIN_TOOL, COMPARE_TOOL, DOCTOR_TOOL, ANNOTATION_TOOL, OUTCOMES_TOOL, DOSSIER_TOOL] })); server.setRequestHandler(CallToolRequestSchema, async (request) => { @@ -675,6 +710,36 @@ export function createFixMapMcpServer( 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 === ALTERNATIVES_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) => !["input", "reports", "graphFingerprint", "format"].includes(key)); + if (unknown.length > 0) return invalid(`unknown argument${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}.`); + const input = record?.input; + if (input !== undefined && !(typeof input === "string" && input.trim()) && (typeof input !== "object" || input === null || Array.isArray(input))) { + return invalid('"input" must be an alternatives object or a local JSON path.'); + } + const reports = validateStringList(record?.reports, "reports"); + if (!reports.success) return invalid(reports.message); + if (reports.values.length > 20) return invalid('"reports" accepts at most 20 paths.'); + const graphFingerprint = record?.graphFingerprint; + if (graphFingerprint !== undefined && (typeof graphFingerprint !== "string" || !graphFingerprint.trim())) return invalid('"graphFingerprint" must be a non-empty string.'); + const format = normalizeFormat(record?.format); + if (!format.success) return invalid(format.message); + try { + const comparison = compareAlternativesFromSources({ + ...(input !== undefined ? { input: typeof input === "string" ? input.trim() : input } : {}), + reports: reports.values, + ...(typeof graphFingerprint === "string" ? { graphFingerprint: graphFingerprint.trim() } : {}) + }); + return { content: [{ type: "text", text: format.value === "json" ? `${JSON.stringify(comparison, null, 2)}\n` : renderAlternativesMarkdown(comparison) }] }; + } catch (error) { + return { isError: true, content: [{ type: "text", text: `Could not compare plan alternatives: ${error instanceof Error ? error.message : String(error)}` }] }; + } + } + if (request.params.name === CAPABILITY_TOOL.name && (request.params.arguments as Record | undefined)?.action !== undefined) { + return runCapabilityMutationTool(request.params.arguments as Record, defaultRepo); + } 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)); @@ -1442,6 +1507,47 @@ function validateStringList( return { success: true, values: candidate.map((entry) => String(entry).trim()) }; } +/** Same validation and errors as `fixmap capability create|update|remove`: arguments become CLI flags. */ +async function runCapabilityMutationTool(record: Record, defaultRepo: string) { + const invalid = (text: string) => ({ isError: true, content: [{ type: "text", text: `Invalid arguments: ${text}` }] }); + const action = record.action; + if (action !== "create" && action !== "update" && action !== "remove") return invalid('"action" must be create, update, or remove.'); + const allowed = action === "remove" + ? ["action", "id", "repo", "format"] + : ["action", "id", "name", "touch", "add", "direction", "depth", "maxNodes", "workspace", "repository", "repo", "format"]; + const unknown = Object.keys(record).filter((key) => !allowed.includes(key)); + if (unknown.length > 0) return invalid(`argument${unknown.length === 1 ? "" : "s"} not allowed for ${action}: ${unknown.join(", ")}.`); + if (typeof record.id !== "string" || !record.id.trim()) return invalid(`capability ${action} requires "id".`); + for (const key of ["name", "direction", "workspace", "repository", "repo"] as const) { + const value = record[key]; + if (value !== undefined && (typeof value !== "string" || !value.trim())) return invalid(`"${key}" must be a non-empty string.`); + } + for (const key of ["depth", "maxNodes"] as const) { + if (record[key] !== undefined && !Number.isSafeInteger(record[key])) return invalid(`"${key}" must be an integer.`); + } + if (typeof record.repo === "string" && /^https?:\/\//i.test(record.repo)) return invalid('"repo" must be a local checkout.'); + const touch = validateStringList(record.touch, "touch"); + if (!touch.success) return invalid(touch.message); + const add = validateStringList(record.add, "add"); + if (!add.success) return invalid(add.message); + const format = normalizeFormat(record.format); + if (!format.success) return invalid(format.message); + const commandArgs = [action, record.id.trim()]; + if (typeof record.name === "string") commandArgs.push("--name", record.name.trim()); + for (const path of touch.values) commandArgs.push("--touch", path); + for (const path of add.values) commandArgs.push("--add", path); + if (typeof record.direction === "string") commandArgs.push("--direction", record.direction.trim()); + if (record.depth !== undefined) commandArgs.push("--depth", String(record.depth)); + if (record.maxNodes !== undefined) commandArgs.push("--max-nodes", String(record.maxNodes)); + if (typeof record.workspace === "string") commandArgs.push("--workspace", record.workspace.trim()); + if (typeof record.repository === "string") commandArgs.push("--repository", record.repository.trim()); + commandArgs.push("--repo", typeof record.repo === "string" ? record.repo.trim() : defaultRepo, "--format", format.value ?? "markdown"); + const stdout: string[] = []; + const stderr: string[] = []; + const exitCode = await runCapabilityCommand(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("") }] }; +} + function normalizeFormat(candidate: unknown): { success: true; value: "markdown" | "json" | undefined } | { success: false; message: string } { if (candidate === undefined) return { success: true, value: undefined }; if (typeof candidate !== "string") return { success: false, message: '"format" must be either "markdown" or "json".' }; diff --git a/packages/cli/test/alternatives-command.test.ts b/packages/cli/test/alternatives-command.test.ts new file mode 100644 index 0000000..2b05d0d --- /dev/null +++ b/packages/cli/test/alternatives-command.test.ts @@ -0,0 +1,142 @@ +import { mkdtemp, readFile, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { createGraphIdentity, type FixMapReport, type PlanAlternative } from "@aryam/fixmap-core"; +import { planAlternativeFromReport, runAlternativesCommand } from "../src/alternatives-command.js"; + +const file = (path: string) => createGraphIdentity({ workspace: "local", kind: "file", key: path }); + +function alternative(id: string, overrides: Partial = {}): PlanAlternative { + return { + planAlternativeVersion: 1, + id, + graphFingerprint: "graph:abcdef", + edits: [file("src/a.ts")], + impacts: [], + contracts: [], + policyFindings: [], + tests: [{ command: "npm test", covers: [file("src/a.ts")], reason: "covers a" }], + reversibility: { mode: "full", reason: "source only", rollbackSteps: ["git revert"] }, + uncertainties: [], + ...overrides + }; +} + +function report(overrides: Partial = {}): FixMapReport { + return { + reportVersion: 1, + summary: "Fix checkout", + contextFiles: [{ rank: 1, path: "src/checkout.ts", score: 10, confidence: "high", reasons: ["named in task"] }], + testRoutes: [{ command: "npm test -- checkout", kind: "test", reason: "tests import checkout", relatedFiles: ["test/checkout.test.ts"] }], + risks: [], + impact: { + seeds: ["src/checkout.ts"], + files: [{ path: "test/checkout.test.ts", score: 5, confidence: "high", evidence: [{ kind: "test-route", seed: "src/checkout.ts", reason: "routed test" }] }], + inspectionOrder: ["src/checkout.ts", "test/checkout.test.ts"], + history: { available: false, eligibleCommits: 0, shallow: false, truncated: false } + }, + changedFiles: [], + diagnostics: [], + ...overrides + }; +} + +function capture() { + const stdout: string[] = []; + const stderr: string[] = []; + return { stdout, stderr, io: { stdout: (value: string) => stdout.push(value), stderr: (value: string) => stderr.push(value) } }; +} + +async function writeJson(name: string, value: unknown): Promise { + const directory = await mkdtemp(join(tmpdir(), "fixmap-alternatives-")); + const path = join(directory, name); + await writeFile(path, JSON.stringify(value)); + return path; +} + +describe("fixmap alternatives", () => { + it("compares inputs side by side and states trade-offs without naming a winner", async () => { + const narrow = alternative("narrow", { uncertainties: [{ id: "u1", severity: "high", detail: "unverified caller" }] }); + const broad = alternative("broad", { + edits: [file("src/a.ts"), file("src/b.ts")], + tests: [{ command: "npm test", covers: [file("src/a.ts"), file("src/b.ts")], reason: "covers both" }] + }); + const input = await writeJson("alternatives.json", { alternativesInputVersion: 1, alternatives: [narrow, broad] }); + + const json = capture(); + expect(await runAlternativesCommand(["--input", input, "--format", "json"], json.io)).toBe(0); + const comparison = JSON.parse(json.stdout.join("")); + expect(comparison).toMatchObject({ alternativePlanComparisonVersion: 1, graphFingerprint: "graph:abcdef" }); + expect(comparison.alternatives.map((entry: { id: string }) => entry.id)).toEqual(["broad", "narrow"]); + expect(comparison.nonDominatedAlternatives).toEqual(["broad", "narrow"]); + + const markdown = capture(); + expect(await runAlternativesCommand(["--input", input], markdown.io)).toBe(0); + const text = markdown.stdout.join(""); + expect(text).toContain("FixMap does not pick a winner"); + expect(text).toContain("| Total blast radius (lower is better) | 2 | 1 |"); + expect(text).toContain("`broad` is better on edits with test coverage (2 vs 1), high uncertainties (0 vs 1)."); + expect(text).toContain("`narrow` is better on intended edits (1 vs 2), total blast radius (1 vs 2)."); + expect(text).not.toMatch(/recommend|winner is|best plan/i); + }); + + it("builds alternatives from saved plan reports with an explicit graph fingerprint", async () => { + const small = await writeJson("small.json", report()); + const wideReport = report({ + contextFiles: [ + { rank: 1, path: "src/checkout.ts", score: 10, confidence: "high", reasons: ["named"] }, + { rank: 2, path: "src/cart.ts", score: 8, confidence: "medium", reasons: ["imports"] } + ], + impact: undefined, + risks: [{ area: "payments", reason: "touches billing", severity: "high" }], + policy: { policyFingerprint: `git:${"a".repeat(40)}`, findings: [{ code: "breaking-contract", severity: "error", ruleId: "api-stability", message: "Public API changed", paths: ["src/cart.ts"], evidence: [] }] } + }); + const wide = await writeJson("wide.json", wideReport); + + const io = capture(); + expect(await runAlternativesCommand(["--report", small, "--report", wide, "--graph-fingerprint", "commit:0123456789", "--format", "json"], io.io), io.stderr.join("")).toBe(0); + const comparison = JSON.parse(io.stdout.join("")); + expect(comparison.graphFingerprint).toBe("commit:0123456789"); + const byId = Object.fromEntries(comparison.alternatives.map((entry: { id: string; metrics: unknown }) => [entry.id, entry.metrics])); + expect(byId.small).toMatchObject({ editIdentities: 1, impactIdentities: 1, coveredEditIdentities: 1, breakingContracts: 0, policyErrors: 0 }); + expect(byId.wide).toMatchObject({ editIdentities: 2, breakingContracts: 1, policyErrors: 1, highUncertainties: 1, coveredEditIdentities: 0 }); + expect(comparison.nonDominatedAlternatives).toEqual(["small"]); + + const adapted = planAlternativeFromReport(wideReport, { id: "wide", graphFingerprint: "commit:0123456789" }); + expect(adapted.contracts).toEqual([{ identity: file("src/cart.ts"), compatibility: "breaking", reason: "Public API changed" }]); + expect(adapted.reversibility.mode).toBe("partial"); + + const missing = capture(); + expect(await runAlternativesCommand(["--report", small, "--report", wide], missing.io)).toBe(1); + expect(missing.stderr.join("")).toContain("requires a graph fingerprint"); + }); + + it("rejects alternatives planned against different graph fingerprints", async () => { + const input = await writeJson("mismatch.json", { + alternativesInputVersion: 1, + alternatives: [alternative("a"), alternative("b", { graphFingerprint: "graph:other1" })] + }); + const io = capture(); + expect(await runAlternativesCommand(["--input", input], io.io)).toBe(1); + expect(io.stderr.join("")).toContain("same exact graph fingerprint"); + + const mixed = await writeJson("one.json", { alternativesInputVersion: 1, alternatives: [alternative("a")] }); + const plan = await writeJson("plan.json", report()); + const mixedIo = capture(); + expect(await runAlternativesCommand(["--input", mixed, "--report", plan, "--graph-fingerprint", "commit:different"], mixedIo.io)).toBe(1); + expect(mixedIo.stderr.join("")).toContain("same exact graph fingerprint"); + }); + + it("refuses to overwrite an input and rejects unknown options", async () => { + const input = await writeJson("alternatives.json", { alternativesInputVersion: 1, alternatives: [alternative("a"), alternative("b")] }); + const overwrite = capture(); + expect(await runAlternativesCommand(["--input", input, "--output", input], overwrite.io)).toBe(1); + expect(overwrite.stderr.join("")).toContain("must not overwrite"); + expect(JSON.parse(await readFile(input, "utf8")).alternativesInputVersion).toBe(1); + + const unknown = capture(); + expect(await runAlternativesCommand(["--input", input, "--score"], unknown.io)).toBe(1); + expect(unknown.stderr.join("")).toContain("Unknown alternatives option"); + }); +}); diff --git a/packages/cli/test/cli-runner.test.ts b/packages/cli/test/cli-runner.test.ts index 3f516b7..82f5f0d 100644 --- a/packages/cli/test/cli-runner.test.ts +++ b/packages/cli/test/cli-runner.test.ts @@ -200,7 +200,7 @@ describe("CLI argument handling", () => { 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", "Reviewer suggestions", "Product capabilities", "Cross-repository workspace", "Repository Q&A", "Migration planning", - "Reverse documentation", "Architecture history", "Historical plans", "Contract Guardian", "Supply-chain evidence", "Runtime evidence", "Evidence import", "Outcome feedback loop", "Change dossier", "Execution sandbox", + "Plan alternatives", "Reverse documentation", "Architecture history", "Historical plans", "Contract Guardian", "Supply-chain evidence", "Runtime evidence", "Evidence import", "Outcome feedback loop", "Change dossier", "Execution sandbox", "Local hybrid retrieval" ]); expect(features.find((feature) => feature.name === "Plan")?.preview).toBeUndefined(); @@ -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", "reviewers", "editor", "capability", "capabilities", "workspace", "ask", "migrate", "reverse-docs", "history", "contracts", "supply-chain", "runtime", "sandbox"]) { + for (const command of ["change-scope", "reviewers", "editor", "capability", "capabilities", "workspace", "ask", "migrate", "alternatives", "reverse-docs", "history", "contracts", "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 1dcae56..b397708 100644 --- a/packages/cli/test/mcp.test.ts +++ b/packages/cli/test/mcp.test.ts @@ -1,5 +1,5 @@ import { execFile, execFileSync } from "node:child_process"; -import { mkdtemp, mkdir, writeFile, rm, readFile } from "node:fs/promises"; +import { mkdtemp, mkdir, writeFile, rm, readFile, symlink } from "node:fs/promises"; import { createHash } from "node:crypto"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -220,7 +220,7 @@ describe("fixmap mcp server", () => { 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_contracts", "fixmap_dossier", "fixmap_history", "fixmap_migrate", + "fixmap_alternatives", "fixmap_ask", "fixmap_capability", "fixmap_change_scope", "fixmap_contracts", "fixmap_dossier", "fixmap_history", "fixmap_migrate", "fixmap_outcomes", "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"]) { @@ -418,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_reviewers", "fixmap_capability", "fixmap_workspace", "fixmap_ask", "fixmap_migrate", "fixmap_reverse_docs", "fixmap_history", "fixmap_contracts", "fixmap_supply_chain", "fixmap_runtime", "fixmap_verify", "fixmap_explain", "fixmap_compare", "fixmap_doctor", "fixmap_annotate", "fixmap_outcomes", "fixmap_dossier" + "fixmap_plan", "fixmap_context", "fixmap_graph", "fixmap_change_scope", "fixmap_reviewers", "fixmap_capability", "fixmap_workspace", "fixmap_ask", "fixmap_migrate", "fixmap_alternatives", "fixmap_reverse_docs", "fixmap_history", "fixmap_contracts", "fixmap_supply_chain", "fixmap_runtime", "fixmap_verify", "fixmap_explain", "fixmap_compare", "fixmap_doctor", "fixmap_annotate", "fixmap_outcomes", "fixmap_dossier" ]); const plan = tools.tools.find((tool) => tool.name === "fixmap_plan"); const verify = tools.tools.find((tool) => tool.name === "fixmap_verify"); @@ -445,7 +445,13 @@ describe("fixmap mcp server", () => { expect(changeScope?.description).toContain("does not interpret product requirements"); expect(changeScope?.inputSchema.additionalProperties).toBe(false); const capability = tools.tools.find((tool) => tool.name === "fixmap_capability"); - expect(Object.keys(capability?.inputSchema.properties ?? {}).sort()).toEqual(["id", "from", "to", "repo", "format", "noCache"].sort()); + expect(Object.keys(capability?.inputSchema.properties ?? {}).sort()).toEqual([ + "action", "id", "name", "touch", "add", "direction", "depth", "maxNodes", "workspace", "repository", "from", "to", "repo", "format", "noCache" + ].sort()); + expect(capability?.annotations).toMatchObject({ readOnlyHint: false, destructiveHint: true, openWorldHint: false }); + const alternatives = tools.tools.find((tool) => tool.name === "fixmap_alternatives"); + expect(Object.keys(alternatives?.inputSchema.properties ?? {}).sort()).toEqual(["input", "reports", "graphFingerprint", "format"].sort()); + expect(alternatives?.annotations).toMatchObject({ readOnlyHint: true, destructiveHint: false, openWorldHint: false }); expect(capability?.inputSchema.additionalProperties).toBe(false); const workspace = tools.tools.find((tool) => tool.name === "fixmap_workspace"); expect(Object.keys(workspace?.inputSchema.properties ?? {}).sort()).toEqual(["config", "seeds", "format", "noCache"].sort()); @@ -1325,3 +1331,124 @@ describe("MCP surface parity", () => { expect(parsePlanArguments({ issue: "https://github.com/o/r/pull/158.patch" }).success).toBe(false); }); }); + +describe("fixmap mcp alternatives and capability editing", () => { + const text = (result: { content?: unknown }) => (result.content as Array<{ text: string }>)[0]!.text; + const identity = (path: string) => createGraphIdentity({ workspace: "local", kind: "file", key: path }); + const alternative = (id: string, graphFingerprint = "graph:abcdef") => ({ + planAlternativeVersion: 1, id, graphFingerprint, + edits: [identity(`src/${id}.ts`)], impacts: [], contracts: [], policyFindings: [], + tests: [{ command: "npm test", covers: [identity(`src/${id}.ts`)], reason: "unit" }], + reversibility: { mode: "full", reason: "source only", rollbackSteps: ["git revert"] }, uncertainties: [] + }); + + it("compares alternatives from an input object and from saved plans, rejecting mismatched graphs", { timeout: 30_000 }, async () => { + const root = await createAuthFixture(); + const client = await connectClient(); + try { + const compared = await client.callTool({ name: "fixmap_alternatives", arguments: { + input: { alternativesInputVersion: 1, alternatives: [alternative("a"), alternative("b")] }, format: "json" + } }); + expect(compared.isError).toBeFalsy(); + expect(JSON.parse(text(compared))).toMatchObject({ alternativePlanComparisonVersion: 1, nonDominatedAlternatives: ["a", "b"] }); + + const mismatched = await client.callTool({ name: "fixmap_alternatives", arguments: { + input: { alternativesInputVersion: 1, alternatives: [alternative("a"), alternative("b", "graph:other1")] } + } }); + expect(mismatched.isError).toBe(true); + expect(text(mismatched)).toContain("same exact graph fingerprint"); + + const planned = await client.callTool({ name: "fixmap_plan", arguments: { issue: "sendResetEmail fails", repo: root, format: "json" } }); + await writeFile(join(root, "plan-a.json"), text(planned)); + await writeFile(join(root, "plan-b.json"), text(planned)); + const fromReports = await client.callTool({ name: "fixmap_alternatives", arguments: { + reports: [join(root, "plan-a.json"), join(root, "plan-b.json")], graphFingerprint: "commit:0123456789" + } }); + expect(fromReports.isError).toBeFalsy(); + expect(text(fromReports)).toContain("`plan-a` and `plan-b` are equal on every compared axis."); + const withoutGraph = await client.callTool({ name: "fixmap_alternatives", arguments: { reports: [join(root, "plan-a.json"), join(root, "plan-b.json")] } }); + expect(withoutGraph.isError).toBe(true); + expect(text(withoutGraph)).toContain("requires a graph fingerprint"); + } finally { + await client.close(); + await rm(root, { recursive: true, force: true }); + } + }); + + it("creates, updates, and removes capabilities through the CLI write path", { timeout: 30_000 }, async () => { + const root = await createAuthFixture(); + const client = await connectClient(); + const store = async () => JSON.parse(await readFile(join(root, ".fixmap", "capabilities.json"), "utf8")); + try { + const created = await client.callTool({ name: "fixmap_capability", arguments: { + action: "create", id: "password-recovery", name: "Password recovery", touch: ["src/auth/reset-password.ts"], repo: root + } }); + expect(created.isError).toBeFalsy(); + expect(text(created)).toContain("Created capability password-recovery in .fixmap/capabilities.json."); + expect((await store()).capabilities).toEqual([{ + id: "password-recovery", name: "Password recovery", anchors: [{ operation: "touch", path: "src/auth/reset-password.ts" }] + }]); + + const updated = await client.callTool({ name: "fixmap_capability", arguments: { + action: "update", id: "password-recovery", name: "Account recovery", depth: 1, repo: root, format: "json" + } }); + expect(updated.isError).toBeFalsy(); + expect(JSON.parse(text(updated)).capabilities[0]).toMatchObject({ name: "Account recovery", traversal: { maxDepth: 1 } }); + + const duplicate = await client.callTool({ name: "fixmap_capability", arguments: { + action: "create", id: "password-recovery", touch: ["src/auth/reset-password.ts"], repo: root + } }); + expect(duplicate.isError).toBe(true); + expect(text(duplicate)).toContain("already exists; use capability update"); + + const removeWithAnchors = await client.callTool({ name: "fixmap_capability", arguments: { + action: "remove", id: "password-recovery", touch: ["src/auth/reset-password.ts"], repo: root + } }); + expect(removeWithAnchors.isError).toBe(true); + expect(text(removeWithAnchors)).toContain("not allowed for remove: touch"); + + const removed = await client.callTool({ name: "fixmap_capability", arguments: { action: "remove", id: "password-recovery", repo: root } }); + expect(removed.isError).toBeFalsy(); + expect(text(removed)).toContain("Removed capability password-recovery"); + expect((await store()).capabilities).toEqual([]); + } finally { + await client.close(); + await rm(root, { recursive: true, force: true }); + } + }); + + it("refuses capability writes under a lock, with traversal anchors, or through a linked .fixmap", { timeout: 30_000 }, async () => { + const root = await createAuthFixture(); + const outside = await mkdtemp(join(tmpdir(), "fixmap-mcp-capability-outside-")); + const client = await connectClient(); + try { + const traversal = await client.callTool({ name: "fixmap_capability", arguments: { + action: "create", id: "escape", touch: ["../outside.ts"], repo: root + } }); + expect(traversal.isError).toBe(true); + expect(text(traversal)).toContain("Invalid capability anchor path: ../outside.ts"); + + await mkdir(join(root, ".fixmap"), { recursive: true }); + await writeFile(join(root, ".fixmap", "capabilities.lock"), "busy\n"); + const locked = await client.callTool({ name: "fixmap_capability", arguments: { + action: "create", id: "password-recovery", touch: ["src/auth/reset-password.ts"], repo: root + } }); + expect(locked.isError).toBe(true); + expect(text(locked)).toContain("Another FixMap capability update is in progress"); + await expect(readFile(join(root, ".fixmap", "capabilities.json"), "utf8")).rejects.toMatchObject({ code: "ENOENT" }); + + await rm(join(root, ".fixmap"), { recursive: true, force: true }); + await symlink(outside, join(root, ".fixmap"), process.platform === "win32" ? "junction" : "dir"); + const linked = await client.callTool({ name: "fixmap_capability", arguments: { + action: "create", id: "password-recovery", touch: ["src/auth/reset-password.ts"], repo: root + } }); + expect(linked.isError).toBe(true); + expect(text(linked)).toContain("resolves outside the repository"); + await expect(readFile(join(outside, "capabilities.json"), "utf8")).rejects.toMatchObject({ code: "ENOENT" }); + } finally { + await client.close(); + await rm(root, { recursive: true, force: true }); + await rm(outside, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/core/src/feature-catalog.ts b/packages/core/src/feature-catalog.ts index 160cb4e..0e9b9f8 100644 --- a/packages/core/src/feature-catalog.ts +++ b/packages/core/src/feature-catalog.ts @@ -21,6 +21,7 @@ export const FIXMAP_FEATURES: readonly FixMapFeature[] = [ { 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." }, { name: "Migration planning", preview: true, command: "fixmap migrate --input ", detail: "Validate an exact identity graph and explicit steps, then order compatibility windows, tests, rollback points, and blast radius without applying changes." }, + { name: "Plan alternatives", preview: true, command: "fixmap alternatives --input ", detail: "Compare 2-20 alternative plans on the same graph state, or saved Plan reports, side by side on edits, blast radius, contract compatibility, policy, tests, reversibility and uncertainty; trade-offs are stated from evidence and no winner is picked by score." }, { name: "Reverse documentation", preview: true, command: "fixmap reverse-docs --input ", detail: "Draft review-only module or architecture Markdown from exact file fingerprints, structural edges, and authored decisions without writing repository files." }, { name: "Architecture history", preview: true, command: "fixmap history --repo . --from --to ", detail: "Compare exact committed architecture snapshots without checking out either ref or changing the worktree, including decision disagreements with accepted ADR import rules and a per-commit snapshot cache." }, { name: "Historical plans", preview: true, command: "fixmap plan --issue --at ", detail: "Rank context files against the repository as it was at a committed ref, read from Git objects without checkout or worktree changes." }, @@ -36,7 +37,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, Reviewers, Capability maps, Workspace, Ask, Migrate, Reverse Docs, History, Contracts, Supply Chain, Runtime, Outcomes, Dossiers, 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, Alternatives, Reverse Docs, History, Contracts, Supply Chain, Runtime, Outcomes, Dossiers, 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." },