From 187a3a476eca3a831ceec720b1c4001f91bf9f63 Mon Sep 17 00:00:00 2001 From: Aryam Goyal Date: Sun, 22 Nov 2026 20:07:51 +0530 Subject: [PATCH 1/9] feat: architecture drift and historical plans over Git refs (preview) - fixmap history / fixmap_history report decision disagreements: edges at the later ref that break a fixmap-deny-imports rule stated by an accepted decision record, with ADR path, rule, edge, and whether it was introduced. - Per-commit architecture snapshot cache outside the repository (scan cache location rules), checksummed; corrupt entries are ignored and rebuilt. --no-cache / noCache bypass it. - fixmap plan --at and fixmap_plan `at` (preview) rank against a committed state read from Git objects, honoring that commit's .fixmapignore and package scripts, without checkout or worktree changes. - Real temporary Git repository tests for drift, cycles, policy and ADR violations, odd paths, cache hit/corruption, unknown refs, and unchanged HEAD/status. Co-Authored-By: Claude Opus 5.5 --- packages/action/dist/index.mjs | 425 ++++++++++++++---- packages/cli/README.md | 3 +- packages/cli/src/cli-runner.ts | 30 +- packages/cli/src/history-command.ts | 35 +- packages/cli/src/mcp.ts | 37 +- packages/cli/src/repository-source.ts | 5 +- packages/cli/test/cli-runner.test.ts | 2 +- packages/cli/test/history-drift.test.ts | 183 ++++++++ packages/cli/test/mcp.test.ts | 4 +- packages/core/src/architecture-history.ts | 255 +++++++++-- packages/core/src/browser.ts | 1 + packages/core/src/decisions.ts | 33 ++ packages/core/src/feature-catalog.ts | 3 +- packages/core/src/index.ts | 9 +- packages/core/src/plan.ts | 39 +- packages/core/src/types.ts | 1 + packages/core/src/validate.ts | 5 +- packages/core/test/architecture-drift.test.ts | 214 +++++++++ 18 files changed, 1141 insertions(+), 143 deletions(-) create mode 100644 packages/cli/test/history-drift.test.ts create mode 100644 packages/core/test/architecture-drift.test.ts diff --git a/packages/action/dist/index.mjs b/packages/action/dist/index.mjs index ea848e6f..2600aab8 100644 --- a/packages/action/dist/index.mjs +++ b/packages/action/dist/index.mjs @@ -5,11 +5,11 @@ import { randomUUID as randomUUID3 } from "node:crypto"; // packages/action/src/annotations.ts import { realpath as realpath3, stat as stat3 } from "node:fs/promises"; -import { isAbsolute as isAbsolute2, relative as relative2, resolve as resolve4 } from "node:path"; +import { isAbsolute as isAbsolute3, relative as relative3, resolve as resolve5 } from "node:path"; // packages/core/dist/plan.js import { readFile as readFile2 } from "node:fs/promises"; -import { join as join2, resolve as resolve2 } from "node:path"; +import { join as join3, resolve as resolve3 } from "node:path"; // packages/core/dist/exclude.js var COMMENT = /^\s*#/; @@ -1333,11 +1333,11 @@ function resolveComposerSymbol(project, symbol, repoPaths, suffixPaths) { for (const mapping of project.psr4) { if (!symbol.startsWith(mapping.prefix)) continue; - const relative3 = symbol.slice(mapping.prefix.length).replace(/\\/g, "/"); - if (!relative3) + const relative4 = symbol.slice(mapping.prefix.length).replace(/\\/g, "/"); + if (!relative4) continue; for (const root of mapping.roots) { - const candidate = [root, `${relative3}.php`].filter(Boolean).join("/"); + const candidate = [root, `${relative4}.php`].filter(Boolean).join("/"); if (repoPaths.has(candidate)) targets.add(candidate); } @@ -1637,23 +1637,23 @@ function buildRubyProjects(files) { if (/^\s*gem\s*(?:\(|\s)\s*["']rails["']/im.test(manifest.textSample)) railsEvidence.add(manifest.path); for (const file of scoped) { - const relative3 = root ? file.path.slice(root.length + 1) : file.path; - if (relative3.toLowerCase() === ".rspec" || /(?:^|\/)spec\/(?:spec_helper|rails_helper)\.rb$/i.test(relative3) || /_spec\.rb$/i.test(relative3)) { + const relative4 = root ? file.path.slice(root.length + 1) : file.path; + if (relative4.toLowerCase() === ".rspec" || /(?:^|\/)spec\/(?:spec_helper|rails_helper)\.rb$/i.test(relative4) || /_spec\.rb$/i.test(relative4)) { rspecEvidence.add(file.path); } - if (/(?:^|\/)test\/test_helper\.rb$/i.test(relative3) || /_test\.rb$/i.test(relative3) || /^(?:\s*require\s*\(?\s*["']minitest|\s*class\s+[^\n<]+<\s*(?:Minitest::Test|MiniTest::Unit)\b)/m.test(file.textSample)) { + if (/(?:^|\/)test\/test_helper\.rb$/i.test(relative4) || /_test\.rb$/i.test(relative4) || /^(?:\s*require\s*\(?\s*["']minitest|\s*class\s+[^\n<]+<\s*(?:Minitest::Test|MiniTest::Unit)\b)/m.test(file.textSample)) { minitestEvidence.add(file.path); } } const application = scoped.find((file) => { - const relative3 = root ? file.path.slice(root.length + 1) : file.path; - return relative3.toLowerCase() === "config/application.rb" && /\bclass\s+Application\s*<\s*Rails::Application\b/.test(file.textSample); + const relative4 = root ? file.path.slice(root.length + 1) : file.path; + return relative4.toLowerCase() === "config/application.rb" && /\bclass\s+Application\s*<\s*Rails::Application\b/.test(file.textSample); }); if (application) railsEvidence.add(application.path); const autoloadFiles = railsEvidence.size === 2 ? scoped.filter((file) => { - const relative3 = root ? file.path.slice(root.length + 1) : file.path; - return /^app\/(?!assets(?:\/|$)|javascript(?:\/|$)|views(?:\/|$))[^/]+\/.+\.rb$/i.test(relative3); + const relative4 = root ? file.path.slice(root.length + 1) : file.path; + return /^app\/(?!assets(?:\/|$)|javascript(?:\/|$)|views(?:\/|$))[^/]+\/.+\.rb$/i.test(relative4); }).map((file) => file.path).sort((left, right) => left.localeCompare(right)) : []; const rakefile = scoped.find((file) => file.path.split("/").pop()?.toLowerCase() === "rakefile"); const rakeTestPath = rakefile && /\b(?:Rake::TestTask|task\s*(?:\(|\s)\s*:test\b)/.test(rakefile.textSample) ? rakefile.path : void 0; @@ -1701,9 +1701,9 @@ function rubyTestCommandForProject(project, relatedTests = []) { const testPath = relatedMinitest[0] ?? project.minitestEvidence.find((path) => /_test\.rb$/i.test(path)); if (!testPath) return void 0; - const relative3 = project.root ? testPath.slice(project.root.length + 1) : testPath; + const relative4 = project.root ? testPath.slice(project.root.length + 1) : testPath; return { - command: scopedBundleCommand(project.root, `ruby -Itest ${relative3}`), + command: scopedBundleCommand(project.root, `ruby -Itest ${relative4}`), reason: `${testPath} provides executable Minitest evidence for ${project.path}`, scopeDir: project.root }; @@ -4727,6 +4727,7 @@ function parseDecisionRecord(input) { const heading = documentHeadings(body).find((entry) => entry.level === 1); const titleDate = heading ? /^\s*Date:[ \t]*(\d{4}-\d{2}-\d{2})[ \t]*(?:\r?\n|$)/i.exec(body.slice(heading.end))?.[1] : void 0; const date = normalizeDate(frontmatter.date ?? section(sections, ["date"]) ?? titleDate); + const dependencyRules = parseDependencyRules(frontmatter["fixmap-deny-imports"]); const sourceUrl = frontmatter["fixmap-source-pr"]; if (sourceUrl !== void 0 && !isDecisionPullRequestUrl(sourceUrl)) throw new Error("Invalid decision pull-request source."); @@ -4743,6 +4744,7 @@ function parseDecisionRecord(input) { ...consequences ? { consequences: normalizeProse(consequences, 8e3) } : {}, targets, supersedes: parseReferences(supersedesText), + ...dependencyRules.length > 0 ? { dependencyRules } : {}, sourceFingerprint: input.fingerprint, ...sourceUrl ? { source: { kind: "pull-request", url: sourceUrl, verification: "unverified-local-attribution" } } : {} } @@ -4863,6 +4865,28 @@ function targetKey(target) { return `symbol:${target.path ?? ""}:${target.name}`; return `${target.kind}:${target.name}`; } +var MAX_DEPENDENCY_RULES = 100; +function parseDependencyRules(text) { + if (text === void 0 || !text.trim()) + return []; + const rules = text.split("\n").map((line) => line.trim()).filter(Boolean).map((line) => { + const match = /^(.+?)\s*->\s*(.+)$/.exec(unquote(line.replace(/^`|`$/g, ""))); + if (!match) + throw new Error(`Invalid fixmap-deny-imports rule: ${line}`); + return { from: dependencyPattern(match[1]), deny: dependencyPattern(match[2]) }; + }); + if (rules.length > MAX_DEPENDENCY_RULES) + throw new Error(`fixmap-deny-imports exceeds the ${MAX_DEPENDENCY_RULES}-rule bound.`); + const unique = new Map(rules.map((rule) => [`${rule.from}\0${rule.deny}`, rule])); + return [...unique.values()].sort((a, b) => a.from.localeCompare(b.from) || a.deny.localeCompare(b.deny)); +} +function dependencyPattern(value) { + const pattern = value.trim().replace(/^`|`$/g, "").replace(/\\/g, "/"); + if (!pattern || pattern.length > 500 || pattern.startsWith("!") || pattern.includes("\0") || pattern.includes("->") || /^(?:\/|[A-Za-z]:)/.test(pattern) || pattern.split("/").includes("..")) { + throw new Error(`Invalid fixmap-deny-imports pattern: ${value}`); + } + return pattern; +} function parseReferences(text) { return [...new Set(text.split(/[\n,]/).map((value) => value.replace(/^\s*[-*]\s+/, "").trim()).filter(Boolean))].sort(); } @@ -6985,6 +7009,233 @@ function normalizePath3(path) { return path.split(sep).join("/"); } +// packages/core/dist/architecture-history.js +import { execFile as execFile2, spawn } from "node:child_process"; +import { dirname as dirname2, extname as extname2, isAbsolute as isAbsolute2, join as join2, relative as relative2, resolve as resolve2, sep as sep2 } from "node:path"; +import { promisify as promisify2 } from "node:util"; +var exec2 = promisify2(execFile2); +var MAX_REF_LENGTH = 500; +var MAX_TREE_BYTES = 32 * 1024 * 1024; +var MAX_FILES = 25e3; +var MAX_TEXT_SAMPLE_BYTES2 = 64e3; +var MAX_BATCH_BYTES = 64 * 1024 * 1024; +var MAX_BATCH_OUTPUT_BYTES = MAX_BATCH_BYTES + 2 * 1024 * 1024; +var ARCHITECTURE_CACHE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3; +async function scanRepoAtRef(input) { + const repoRoot = resolve2(input.repoRoot); + const requestedRef = validateRef(input.ref); + return scanCommit(repoRoot, requestedRef, await resolveCommit(repoRoot, requestedRef)); +} +async function scanCommit(repoRoot, requestedRef, commit) { + const { stdout } = await exec2("git", ["ls-tree", "-r", "-z", "-l", "--full-tree", commit, "--"], { + cwd: repoRoot, + encoding: "utf8", + maxBuffer: MAX_TREE_BYTES + }); + const allEntries = parseTree(stdout).filter((entry) => entry.mode !== "120000"); + const entries = allEntries.slice(0, MAX_FILES); + const diagnostics = []; + if (allEntries.length > entries.length) + diagnostics.push({ + code: "scan-limit-reached", + severity: "warning", + message: `Historical scan stopped after ${MAX_FILES.toLocaleString()} files at ${commit}.` + }); + const readable = []; + let scheduledBytes = 0; + for (const entry of entries) { + if (!isSourcePath(entry.path) && entry.path !== ".fixmapignore" || entry.size > MAX_TEXT_SAMPLE_BYTES2) + continue; + if (scheduledBytes + entry.size > MAX_BATCH_BYTES) + continue; + readable.push(entry); + scheduledBytes += entry.size; + } + const content = await readBlobs(repoRoot, readable); + const files = entries.map((entry) => buildRepoFile(entry, content.get(entry.oid))); + const ignoreEntry = entries.find((entry) => entry.path === ".fixmapignore"); + const ignoreBytes = ignoreEntry ? content.get(ignoreEntry.oid) : void 0; + return { + requestedRef, + commit, + repo: { + root: repoRoot, + files, + trackedFiles: entries.map((entry) => entry.path), + packageScripts: historicalPackageScripts(files, diagnostics), + changedFiles: [], + diffText: "", + packageManager: inferPackageManager(entries), + diagnostics + }, + ...ignoreBytes ? { ignoreFile: ignoreBytes.toString("utf8") } : {} + }; +} +function isRecord6(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function historicalPackageScripts(files, diagnostics) { + return files.filter((file) => file.path === "package.json" || file.path.endsWith("/package.json")).flatMap((manifest) => { + if (manifest.textSampleComplete !== true) + return []; + try { + const parsed = JSON.parse(manifest.textSample.replace(/^/, "")); + const packageDir = manifest.path.includes("/") ? manifest.path.slice(0, manifest.path.lastIndexOf("/")) : ""; + const packageName = typeof parsed.name === "string" && parsed.name.trim() ? parsed.name.trim() : void 0; + const scripts = isRecord6(parsed.scripts) ? parsed.scripts : {}; + return Object.entries(scripts).flatMap(([name, command]) => typeof command === "string" ? [{ name, command, packageDir, ...packageName ? { packageName } : {} }] : []); + } catch { + diagnostics.push({ + code: "package-json-invalid", + severity: "warning", + message: `Could not parse ${manifest.path} at this commit; scripts from that package were skipped.` + }); + return []; + } + }); +} +function validateRef(value) { + const ref = value.trim(); + if (!ref || ref.length > MAX_REF_LENGTH || /[\0\r\n]/.test(ref)) + throw new Error("Git ref must be a bounded single-line value."); + return ref; +} +async function resolveCommit(repoRoot, ref) { + try { + const { stdout } = await exec2("git", ["rev-parse", "--verify", "--end-of-options", `${ref}^{commit}`], { + cwd: repoRoot, + encoding: "utf8", + maxBuffer: 1024 * 1024 + }); + const commit = stdout.trim(); + if (!/^[a-f0-9]{40,64}$/i.test(commit)) + throw new Error("Git returned an invalid commit identity."); + return commit.toLowerCase(); + } catch (error) { + throw new Error(`Could not resolve Git ref ${JSON.stringify(ref)}: ${error instanceof Error ? error.message : String(error)}`); + } +} +function parseTree(value) { + return value.split("\0").flatMap((record3) => { + if (!record3) + return []; + const tab = record3.indexOf(" "); + const header = tab === -1 ? "" : record3.slice(0, tab); + const path = tab === -1 ? "" : record3.slice(tab + 1).replace(/\\/g, "/"); + const match = /^(\d+) blob ([a-f0-9]{40,64})\s+(\d+)$/.exec(header); + if (!match || !safePath(path)) + return []; + return [{ mode: match[1], oid: match[2].toLowerCase(), size: Number(match[3]), path }]; + }); +} +async function readBlobs(repoRoot, entries) { + if (entries.length === 0) + return /* @__PURE__ */ new Map(); + const uniqueOids = [...new Set(entries.map((entry) => entry.oid))]; + const child = spawn("git", ["cat-file", "--batch"], { cwd: repoRoot, stdio: ["pipe", "pipe", "pipe"], windowsHide: true }); + const stdout = []; + const stderr = []; + let outputBytes = 0; + child.stdout.on("data", (chunk) => { + outputBytes += chunk.length; + if (outputBytes > MAX_BATCH_OUTPUT_BYTES) + child.kill(); + else + stdout.push(chunk); + }); + child.stderr.on("data", (chunk) => stderr.push(chunk)); + child.stdin.end(`${uniqueOids.join("\n")} +`); + const exitCode = await new Promise((resolveExit, reject) => { + child.once("error", reject); + child.once("close", resolveExit); + }); + if (exitCode !== 0 || outputBytes > MAX_BATCH_OUTPUT_BYTES) { + throw new Error(`git cat-file failed while reading historical sources: ${Buffer.concat(stderr).toString("utf8").trim() || `exit ${exitCode}`}`); + } + return parseBatch(Buffer.concat(stdout), uniqueOids); +} +function parseBatch(output, oids) { + const result = /* @__PURE__ */ new Map(); + let offset = 0; + for (const expected of oids) { + const newline = output.indexOf(10, offset); + if (newline === -1) + throw new Error("git cat-file returned a truncated header."); + const header = output.subarray(offset, newline).toString("ascii"); + const match = /^([a-f0-9]{40,64}) blob (\d+)$/.exec(header); + if (!match || match[1].toLowerCase() !== expected) + throw new Error("git cat-file returned an unexpected object."); + const size = Number(match[2]); + const start = newline + 1; + const end = start + size; + if (!Number.isSafeInteger(size) || end >= output.length || output[end] !== 10) { + throw new Error("git cat-file returned a truncated object."); + } + result.set(expected, output.subarray(start, end)); + offset = end + 1; + } + if (offset !== output.length) + throw new Error("git cat-file returned trailing output."); + return result; +} +function buildRepoFile(entry, bytes) { + const extension = extname2(entry.path).toLowerCase(); + const isSource = isSourcePath(entry.path); + let textSample = ""; + let textSampleComplete; + let textSampleSkipReason; + if (isSource) { + if (!bytes) { + textSampleComplete = false; + textSampleSkipReason = "too-large"; + } else { + try { + textSample = new TextDecoder("utf-8", { fatal: true }).decode(bytes); + textSampleComplete = true; + } catch { + textSampleComplete = false; + textSampleSkipReason = "not-text"; + } + } + } + return { + path: entry.path, + contentFingerprint: `git:${entry.oid}`, + extension, + sizeBytes: entry.size, + isTest: isLanguageTestPath(entry.path, extension) || /(?:^|\/)(?:__tests__|tests?|spec)(?:\/|$)/i.test(entry.path), + isSource, + kind: classify(entry.path, extension), + textSample, + ...textSampleComplete !== void 0 ? { textSampleComplete } : {}, + ...textSampleSkipReason ? { textSampleSkipReason } : {} + }; +} +function isSourcePath(path) { + return SOURCE_FILE_EXTENSIONS.has(extname2(path).toLowerCase()) || /(?:^|\/)(?:dockerfile|makefile|pom\.xml|pyproject\.toml)$/i.test(path); +} +function classify(path, extension) { + if (/\.(?:md|mdx)$/i.test(extension) || /(?:^|\/)docs?\//i.test(path)) + return "documentation"; + if (/\.(?:json|ya?ml|toml)$/i.test(extension) || /(?:^|\/)(?:dockerfile|makefile|pom\.xml)$/i.test(path)) + return "config"; + return isSourcePath(path) ? "code" : "other"; +} +function inferPackageManager(entries) { + const names = new Set(entries.map((entry) => entry.path.split("/").at(-1)?.toLowerCase())); + if (names.has("pnpm-lock.yaml")) + return "pnpm"; + if (names.has("yarn.lock")) + return "yarn"; + if (names.has("bun.lock") || names.has("bun.lockb")) + return "bun"; + return "npm"; +} +function safePath(path) { + return Boolean(path) && !path.includes("\0") && !path.includes("\uFFFD") && !/^[\/]/.test(path) && path.split("/").every((part) => part && part !== "." && part !== ".."); +} + // packages/core/dist/custom-language-context.js var KINDS = /* @__PURE__ */ new Set(["function", "method", "class", "interface", "type", "variable"]); var record = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value); @@ -7196,7 +7447,7 @@ async function collectEvidence(providers, context, options = {}) { }; } function validateProviderResult(result) { - if (!isRecord6(result) || !Array.isArray(result.items) || !(result.relationships === void 0 || Array.isArray(result.relationships))) { + if (!isRecord7(result) || !Array.isArray(result.items) || !(result.relationships === void 0 || Array.isArray(result.relationships))) { return { success: false, message: "expected { items, relationships? } arrays" }; } const items = result.items; @@ -7228,7 +7479,7 @@ function validateProviderResult(result) { }; } function validateEvidenceItem(candidate) { - if (!isRecord6(candidate) || typeof candidate.id !== "string" || !LOCAL_ID.test(candidate.id)) + if (!isRecord7(candidate) || typeof candidate.id !== "string" || !LOCAL_ID.test(candidate.id)) return "an item has an invalid ID"; if (!isEvidenceKind(candidate.kind)) return `item ${candidate.id} has an invalid kind`; @@ -7245,7 +7496,7 @@ function validateEvidenceItem(candidate) { return void 0; } function validateRelationship(candidate, itemIds) { - if (!isRecord6(candidate) || typeof candidate.id !== "string" || !LOCAL_ID.test(candidate.id)) + if (!isRecord7(candidate) || typeof candidate.id !== "string" || !LOCAL_ID.test(candidate.id)) return "a relationship has an invalid ID"; if (typeof candidate.from !== "string" || !itemIds.has(candidate.from) || typeof candidate.to !== "string" || !itemIds.has(candidate.to)) return `relationship ${candidate.id} references an unknown item`; @@ -7258,7 +7509,7 @@ function validateRelationship(candidate, itemIds) { return void 0; } function isEvidenceSubject(candidate) { - if (!isRecord6(candidate)) + if (!isRecord7(candidate)) return false; if (candidate.kind === "repository") return typeof candidate.repository === "string" && candidate.repository.trim().length > 0; @@ -7278,7 +7529,7 @@ function isSafeRelativePath(path) { return path.replace(/\\/g, "/").split("/").every((segment) => segment.length > 0 && segment !== "." && segment !== ".."); } function isScalarMetadata(candidate) { - if (!isRecord6(candidate) || Object.keys(candidate).length > 50) + if (!isRecord7(candidate) || Object.keys(candidate).length > 50) return false; return Object.entries(candidate).every(([key, value]) => key.length > 0 && key.length <= 100 && (typeof value === "string" && value.length <= 1e3 || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value))); } @@ -7302,21 +7553,21 @@ function positiveInteger2(value, fallback) { return value !== void 0 && Number.isSafeInteger(value) && value > 0 ? value : fallback; } function withTimeout(promise, timeoutMs, controller) { - return new Promise((resolve6, reject) => { + return new Promise((resolve7, reject) => { const timer = setTimeout(() => { controller.abort(); reject(new Error(`timed out after ${timeoutMs.toLocaleString()} ms`)); }, timeoutMs); promise.then((value) => { clearTimeout(timer); - resolve6(value); + resolve7(value); }, (error) => { clearTimeout(timer); reject(error); }); }); } -function isRecord6(candidate) { +function isRecord7(candidate) { return typeof candidate === "object" && candidate !== null && !Array.isArray(candidate); } @@ -7350,7 +7601,8 @@ async function buildFixMapReport(input) { return (await buildFixMapAnalysis(input)).report; } async function buildFixMapAnalysis(input) { - const scannedRepo = await scanRepo({ ...input, includeHistory: input.includeHistory !== false }); + const historical = input.atRef === void 0 ? void 0 : await scanHistoricalRepo(input.repoRoot, input.atRef, input); + const scannedRepo = historical?.repo ?? await scanRepo({ ...input, includeHistory: input.includeHistory !== false }); const generatedArtifacts = scannedRepo.files.filter(isFixMapArtifact); const generatedPaths = new Set(generatedArtifacts.map((file) => file.path)); const repo = generatedArtifacts.length === 0 ? scannedRepo : { @@ -7359,7 +7611,7 @@ async function buildFixMapAnalysis(input) { changedFiles: scannedRepo.changedFiles.filter((path) => !generatedPaths.has(path)), ...scannedRepo.trackedFiles ? { trackedFiles: scannedRepo.trackedFiles.filter((path) => !generatedPaths.has(path)) } : {} }; - const requestedExclude = await resolveExclusions(input.repoRoot, input.exclude ?? []); + const requestedExclude = historical ? excluderFor(input.repoRoot, [...parseIgnoreFile(historical.ignoreFile ?? ""), ...input.exclude ?? []]) : await resolveExclusions(input.repoRoot, input.exclude ?? []); const internalExclude = buildPathExcluder((input.internalExclude ?? []).map((pattern) => normalizeAbsolutePattern(input.repoRoot, pattern))); const exclude = combineExclusions(requestedExclude, internalExclude); const languageContext = input.languageRegistry ? createCustomLanguageContext(input.languageRegistry) : void 0; @@ -7437,14 +7689,29 @@ function combineExclusions(primary, internal) { }; } async function resolveExclusions(repoRoot, patterns2) { - const combined = [...await readIgnoreFile(repoRoot), ...patterns2].map((pattern) => normalizeAbsolutePattern(repoRoot, pattern)); + return excluderFor(repoRoot, [...await readIgnoreFile(repoRoot), ...patterns2]); +} +function excluderFor(repoRoot, patterns2) { + const combined = patterns2.map((pattern) => normalizeAbsolutePattern(repoRoot, pattern)); return combined.length > 0 ? buildPathExcluder(combined) : NO_EXCLUSIONS; } +async function scanHistoricalRepo(repoRoot, ref, input) { + if (input.diffSpec !== void 0 || input.baseRef !== void 0 || input.headRef !== void 0 || input.workingTree || input.includeUntracked) { + throw new Error("A historical plan ranks one committed state, so it cannot be combined with a diff or the working tree."); + } + const historical = await scanRepoAtRef({ repoRoot, ref }); + historical.repo.diagnostics.unshift({ + code: "historical-plan", + severity: "info", + message: `Preview: ranked against ${markdownCode(historical.requestedRef)} at commit ${markdownCode(historical.commit)}, read from committed Git objects without checking out or changing the worktree. Co-change history and uncommitted files were not used.` + }); + return historical; +} function normalizeAbsolutePattern(repoRoot, pattern) { const trimmed = pattern.trim(); const negated = trimmed.startsWith("!"); const body = (negated ? trimmed.slice(1) : trimmed).replace(/\\/g, "/"); - const normalizedRoot = resolve2(repoRoot).replace(/\\/g, "/").replace(/\/$/, ""); + const normalizedRoot = resolve3(repoRoot).replace(/\\/g, "/").replace(/\/$/, ""); const caseInsensitive = /^[A-Za-z]:\//.test(normalizedRoot); const comparableBody = caseInsensitive ? body.toLowerCase() : body; const comparableRoot = caseInsensitive ? normalizedRoot.toLowerCase() : normalizedRoot; @@ -7454,7 +7721,7 @@ function normalizeAbsolutePattern(repoRoot, pattern) { } async function readIgnoreFile(repoRoot) { try { - return parseIgnoreFile(await readFile2(join2(repoRoot, ".fixmapignore"), "utf8")); + return parseIgnoreFile(await readFile2(join3(repoRoot, ".fixmapignore"), "utf8")); } catch { return []; } @@ -7773,7 +8040,7 @@ function renderVerifyMarkdown(result) { // packages/core/dist/annotation-store.js import { mkdir as mkdir2, open as open2, readFile as readFile3, realpath as realpath2, rename as rename2, rm, stat as stat2, lstat } from "node:fs/promises"; -import { resolve as resolve3 } from "node:path"; +import { resolve as resolve4 } from "node:path"; import { randomUUID as randomUUID2 } from "node:crypto"; async function readAnnotationStore(repoRoot) { return readStore(await annotationRoot(repoRoot)); @@ -7794,7 +8061,7 @@ async function annotationRoot(path) { } async function readStore(repoRoot) { await assertStoreBoundary(repoRoot); - const path = resolve3(repoRoot, ".fixmap", "annotations.json"); + const path = resolve4(repoRoot, ".fixmap", "annotations.json"); try { return validateAnnotationStore(JSON.parse(await readFile3(path, "utf8"))); } catch (error) { @@ -7806,11 +8073,11 @@ async function readStore(repoRoot) { } } async function writeStore(repoRoot, store) { - const directory = resolve3(repoRoot, ".fixmap"); + const directory = resolve4(repoRoot, ".fixmap"); await mkdir2(directory, { recursive: true }); await assertStoreBoundary(repoRoot); - const target = resolve3(directory, "annotations.json"); - const temporary = resolve3(directory, `.annotations.${process.pid}.${randomUUID2()}.tmp`); + const target = resolve4(directory, "annotations.json"); + const temporary = resolve4(directory, `.annotations.${process.pid}.${randomUUID2()}.tmp`); const handle = await open2(temporary, "wx", 384); try { await handle.writeFile(`${JSON.stringify(validateAnnotationStore(store), null, 2)} @@ -7828,10 +8095,10 @@ async function writeStore(repoRoot, store) { } async function withStoreLock(repoRoot, operation) { await assertStoreBoundary(repoRoot); - const directory = resolve3(repoRoot, ".fixmap"); + const directory = resolve4(repoRoot, ".fixmap"); await mkdir2(directory, { recursive: true }); await assertStoreBoundary(repoRoot); - const lockPath = resolve3(directory, "annotations.lock"); + const lockPath = resolve4(directory, "annotations.lock"); let handle; try { handle = await open2(lockPath, "wx", 384); @@ -7854,7 +8121,7 @@ async function withStoreLock(repoRoot, operation) { } } async function assertStoreBoundary(repoRoot) { - const directory = resolve3(repoRoot, ".fixmap"); + const directory = resolve4(repoRoot, ".fixmap"); const directoryInfo = await lstat(directory).catch((error) => { if (isNodeError(error, "ENOENT")) return void 0; @@ -7866,7 +8133,7 @@ async function assertStoreBoundary(repoRoot) { throw new Error("Annotation store directory must be a real repository-local .fixmap directory, not a link or junction."); } for (const name of ["annotations.json", "annotations.lock"]) { - const info = await lstat(resolve3(directory, name)).catch((error) => { + const info = await lstat(resolve4(directory, name)).catch((error) => { if (isNodeError(error, "ENOENT")) return void 0; throw error; @@ -7881,9 +8148,9 @@ function isNodeError(error, code) { } // packages/core/dist/sandbox.js -import { execFile as execFile2, spawn } from "node:child_process"; -import { promisify as promisify2 } from "node:util"; -var exec2 = promisify2(execFile2); +import { execFile as execFile3, spawn as spawn2 } from "node:child_process"; +import { promisify as promisify3 } from "node:util"; +var exec3 = promisify3(execFile3); var DEFAULT_LIMITS = { timeoutMs: 5 * 6e4, outputBytes: 1e6, @@ -7927,7 +8194,7 @@ function validateFixMapReport(candidate, label) { } const versioned = record3.reportVersion === 1; const contextFiles = candidate.contextFiles; - const unsafeContextPath = contextFiles.findIndex((file) => isRecord7(file) && typeof file.path === "string" && file.path.trim().length > 0 && !isRepositoryRelativePath(file.path)); + const unsafeContextPath = contextFiles.findIndex((file) => isRecord8(file) && typeof file.path === "string" && file.path.trim().length > 0 && !isRepositoryRelativePath(file.path)); if (unsafeContextPath !== -1) { const path = contextFiles[unsafeContextPath].path; return { @@ -7936,7 +8203,7 @@ function validateFixMapReport(candidate, label) { }; } const invalid = contextFiles.findIndex((file) => { - if (!isRecord7(file)) + if (!isRecord8(file)) return true; const ranked = file; if (!isRepositoryRelativePath(ranked.path)) @@ -7979,7 +8246,7 @@ function validateFixMapReport(candidate, label) { } const testRoutes = record3.testRoutes; const invalidRoute = testRoutes.findIndex((route) => { - if (!isRecord7(route)) + if (!isRecord8(route)) return true; return typeof route.command !== "string" || !route.command.trim() || !isRepositoryRelativePathArray(route.relatedFiles) || (versioned || route.kind !== void 0) && route.kind !== "test" && route.kind !== "validation" || (versioned || route.reason !== void 0) && typeof route.reason !== "string"; }); @@ -7991,7 +8258,7 @@ function validateFixMapReport(candidate, label) { } const risks = record3.risks; const invalidRisk = risks.findIndex((risk) => { - if (!isRecord7(risk)) + if (!isRecord8(risk)) return true; return typeof risk.area !== "string" || !risk.area.trim() || (versioned || risk.reason !== void 0) && typeof risk.reason !== "string" || (versioned || risk.severity !== void 0) && risk.severity !== "low" && risk.severity !== "medium" && risk.severity !== "high"; }); @@ -8003,14 +8270,14 @@ function validateFixMapReport(candidate, label) { } if (record3.impact !== void 0) { const impact = record3.impact; - const history = isRecord7(impact) ? impact.history : void 0; - if (!isRecord7(impact) || !isRepositoryRelativePathArray(impact.seeds) || !Array.isArray(impact.files) || !isRepositoryRelativePathArray(impact.inspectionOrder) || !isRecord7(history) || typeof history.available !== "boolean" || typeof history.eligibleCommits !== "number" || !Number.isSafeInteger(history.eligibleCommits) || history.eligibleCommits < 0 || typeof history.shallow !== "boolean" || typeof history.truncated !== "boolean") { + const history = isRecord8(impact) ? impact.history : void 0; + if (!isRecord8(impact) || !isRepositoryRelativePathArray(impact.seeds) || !Array.isArray(impact.files) || !isRepositoryRelativePathArray(impact.inspectionOrder) || !isRecord8(history) || typeof history.available !== "boolean" || typeof history.eligibleCommits !== "number" || !Number.isSafeInteger(history.eligibleCommits) || history.eligibleCommits < 0 || typeof history.shallow !== "boolean" || typeof history.truncated !== "boolean") { return { success: false, message: `${label} has an invalid impact graph envelope.` }; } const invalidImpact = impact.files.findIndex((file) => { - if (!isRecord7(file) || !isRepositoryRelativePath(file.path) || typeof file.score !== "number" || !Number.isFinite(file.score) || file.score < 0 || file.confidence !== "high" && file.confidence !== "medium" && file.confidence !== "low" || !Array.isArray(file.evidence)) + if (!isRecord8(file) || !isRepositoryRelativePath(file.path) || typeof file.score !== "number" || !Number.isFinite(file.score) || file.score < 0 || file.confidence !== "high" && file.confidence !== "medium" && file.confidence !== "low" || !Array.isArray(file.evidence)) return true; - return file.evidence.some((evidence) => !isRecord7(evidence) || !["imports", "imported-by", "co-change", "test-route"].includes(String(evidence.kind)) || !isRepositoryRelativePath(evidence.seed) || typeof evidence.reason !== "string" || !evidence.reason.trim() || evidence.occurrences !== void 0 && (!Number.isSafeInteger(evidence.occurrences) || evidence.occurrences < 0) || evidence.seedChanges !== void 0 && (!Number.isSafeInteger(evidence.seedChanges) || evidence.seedChanges < 0)); + return file.evidence.some((evidence) => !isRecord8(evidence) || !["imports", "imported-by", "co-change", "test-route"].includes(String(evidence.kind)) || !isRepositoryRelativePath(evidence.seed) || typeof evidence.reason !== "string" || !evidence.reason.trim() || evidence.occurrences !== void 0 && (!Number.isSafeInteger(evidence.occurrences) || evidence.occurrences < 0) || evidence.seedChanges !== void 0 && (!Number.isSafeInteger(evidence.seedChanges) || evidence.seedChanges < 0)); }); if (invalidImpact !== -1) { return { success: false, message: `${label} has an invalid impact.files entry at index ${invalidImpact}.` }; @@ -8019,7 +8286,7 @@ function validateFixMapReport(candidate, label) { const primaryPaths = new Set(contextFiles.map((file) => file.path)); const seenEdges = /* @__PURE__ */ new Set(); if (!Array.isArray(impact.primaryImports) || impact.primaryImports.some((edge) => { - if (!isRecord7(edge) || !isRepositoryRelativePath(edge.from) || !isRepositoryRelativePath(edge.to) || edge.from === edge.to || !primaryPaths.has(edge.from) || !primaryPaths.has(edge.to)) + if (!isRecord8(edge) || !isRepositoryRelativePath(edge.from) || !isRepositoryRelativePath(edge.to) || edge.from === edge.to || !primaryPaths.has(edge.from) || !primaryPaths.has(edge.to)) return true; const key = JSON.stringify([edge.from, edge.to]); if (seenEdges.has(key)) @@ -8036,24 +8303,24 @@ function validateFixMapReport(candidate, label) { } if (record3.evidence !== void 0) { const evidence = record3.evidence; - const validSubject = (subject) => isRecord7(subject) && typeof subject.kind === "string" && (subject.path === void 0 || isRepositoryRelativePath(subject.path)); - if (!isRecord7(evidence) || evidence.evidenceVersion !== 1 || typeof evidence.collectedAt !== "string" || !Array.isArray(evidence.sources) || !evidence.sources.every((source) => isRecord7(source) && typeof source.provider === "string" && typeof source.version === "string" && (source.documentSha256 === void 0 || typeof source.documentSha256 === "string" && /^[a-f0-9]{64}$/.test(source.documentSha256))) || !Array.isArray(evidence.items) || evidence.items.length > 50 || !evidence.items.every((item) => isRecord7(item) && typeof item.id === "string" && typeof item.summary === "string" && typeof item.kind === "string" && ["high", "medium", "low"].includes(String(item.confidence)) && isRecord7(item.provider) && Array.isArray(item.subjects) && item.subjects.length > 0 && item.subjects.every(validSubject)) || !Number.isSafeInteger(evidence.omittedItems) || evidence.omittedItems < 0 || !Array.isArray(evidence.diagnostics)) { + const validSubject = (subject) => isRecord8(subject) && typeof subject.kind === "string" && (subject.path === void 0 || isRepositoryRelativePath(subject.path)); + if (!isRecord8(evidence) || evidence.evidenceVersion !== 1 || typeof evidence.collectedAt !== "string" || !Array.isArray(evidence.sources) || !evidence.sources.every((source) => isRecord8(source) && typeof source.provider === "string" && typeof source.version === "string" && (source.documentSha256 === void 0 || typeof source.documentSha256 === "string" && /^[a-f0-9]{64}$/.test(source.documentSha256))) || !Array.isArray(evidence.items) || evidence.items.length > 50 || !evidence.items.every((item) => isRecord8(item) && typeof item.id === "string" && typeof item.summary === "string" && typeof item.kind === "string" && ["high", "medium", "low"].includes(String(item.confidence)) && isRecord8(item.provider) && Array.isArray(item.subjects) && item.subjects.length > 0 && item.subjects.every(validSubject)) || !Number.isSafeInteger(evidence.omittedItems) || evidence.omittedItems < 0 || !Array.isArray(evidence.diagnostics)) { return { success: false, message: `${label} has invalid evidence; it needs evidenceVersion 1, sources, at most 50 items with safe repository-relative subjects, omittedItems, and diagnostics.` }; } } if (record3.languageAdapters !== void 0) { const adapters = record3.languageAdapters; - if (!Array.isArray(adapters) || adapters.length > 32 || !adapters.every((adapter) => isRecord7(adapter) && Object.keys(adapter).every((key) => key === "id" || key === "version" || key === "extensions") && typeof adapter.id === "string" && /^custom:[a-z][a-z0-9-]{0,63}$/.test(adapter.id) && typeof adapter.version === "string" && /^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(adapter.version) && Array.isArray(adapter.extensions) && adapter.extensions.length > 0 && adapter.extensions.length <= 32 && adapter.extensions.every((extension) => typeof extension === "string" && /^\.[a-z0-9][a-z0-9_-]{0,15}$/.test(extension)))) { + if (!Array.isArray(adapters) || adapters.length > 32 || !adapters.every((adapter) => isRecord8(adapter) && Object.keys(adapter).every((key) => key === "id" || key === "version" || key === "extensions") && typeof adapter.id === "string" && /^custom:[a-z][a-z0-9-]{0,63}$/.test(adapter.id) && typeof adapter.version === "string" && /^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(adapter.version) && Array.isArray(adapter.extensions) && adapter.extensions.length > 0 && adapter.extensions.length <= 32 && adapter.extensions.every((extension) => typeof extension === "string" && /^\.[a-z0-9][a-z0-9_-]{0,15}$/.test(extension)))) { return { success: false, message: `${label} has invalid languageAdapters; each entry needs a custom: id, a version, and lowercase extensions.` }; } } if (record3.annotations !== void 0) { const annotations = record3.annotations; - if (!isRecord7(annotations) || typeof annotations.asOf !== "string" || !Number.isFinite(Date.parse(annotations.asOf)) || !isRepositoryRelativePath(annotations.sourcePath) || typeof annotations.sourceFingerprint !== "string" || !/^(?:git|worktree):[a-f0-9]{40,64}$/i.test(annotations.sourceFingerprint) || !Array.isArray(annotations.entries)) { + if (!isRecord8(annotations) || typeof annotations.asOf !== "string" || !Number.isFinite(Date.parse(annotations.asOf)) || !isRepositoryRelativePath(annotations.sourcePath) || typeof annotations.sourceFingerprint !== "string" || !/^(?:git|worktree):[a-f0-9]{40,64}$/i.test(annotations.sourceFingerprint) || !Array.isArray(annotations.entries)) { return { success: false, message: `${label} has an invalid annotations envelope.` }; } const invalidAnnotation = annotations.entries.findIndex((assessment) => { - if (!isRecord7(assessment) || !isRecord7(assessment.annotation) || typeof assessment.message !== "string" || !["active", "expired", "missing-target", "renamed-target"].includes(String(assessment.status)) || assessment.suggestedPath !== void 0 && !isRepositoryRelativePath(assessment.suggestedPath)) + if (!isRecord8(assessment) || !isRecord8(assessment.annotation) || typeof assessment.message !== "string" || !["active", "expired", "missing-target", "renamed-target"].includes(String(assessment.status)) || assessment.suggestedPath !== void 0 && !isRepositoryRelativePath(assessment.suggestedPath)) return true; try { validateAnnotationStore({ annotationStoreVersion: 1, annotations: [assessment.annotation] }); @@ -8070,12 +8337,12 @@ function validateFixMapReport(candidate, label) { if (!Array.isArray(record3.decisions)) return { success: false, message: `${label} has invalid decisions; expected an array.` }; const invalidDecision = record3.decisions.findIndex((decision) => { - if (!isRecord7(decision) || typeof decision.id !== "string" || !/^decision:[a-f0-9]{16}$/.test(decision.id) || !isRepositoryRelativePath(decision.path) || typeof decision.title !== "string" || !decision.title.trim() || !["proposed", "accepted", "rejected", "deprecated", "superseded", "unknown"].includes(String(decision.status)) || typeof decision.decision !== "string" || !decision.decision.trim() || typeof decision.sourceFingerprint !== "string" || !/^(?:git|worktree):[a-f0-9]{40,64}$/i.test(decision.sourceFingerprint) || !Array.isArray(decision.targets) || !Array.isArray(decision.supersedes) || !decision.supersedes.every((value) => typeof value === "string" && value.trim()) || decision.date !== void 0 && (typeof decision.date !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(decision.date)) || decision.context !== void 0 && typeof decision.context !== "string" || decision.authoredStatus !== void 0 && (typeof decision.authoredStatus !== "string" || !decision.authoredStatus.trim() || decision.authoredStatus.length > 500 || decision.authoredStatus.includes("\0")) || decision.consequences !== void 0 && typeof decision.consequences !== "string") + if (!isRecord8(decision) || typeof decision.id !== "string" || !/^decision:[a-f0-9]{16}$/.test(decision.id) || !isRepositoryRelativePath(decision.path) || typeof decision.title !== "string" || !decision.title.trim() || !["proposed", "accepted", "rejected", "deprecated", "superseded", "unknown"].includes(String(decision.status)) || typeof decision.decision !== "string" || !decision.decision.trim() || typeof decision.sourceFingerprint !== "string" || !/^(?:git|worktree):[a-f0-9]{40,64}$/i.test(decision.sourceFingerprint) || !Array.isArray(decision.targets) || !Array.isArray(decision.supersedes) || !decision.supersedes.every((value) => typeof value === "string" && value.trim()) || decision.date !== void 0 && (typeof decision.date !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(decision.date)) || decision.context !== void 0 && typeof decision.context !== "string" || decision.authoredStatus !== void 0 && (typeof decision.authoredStatus !== "string" || !decision.authoredStatus.trim() || decision.authoredStatus.length > 500 || decision.authoredStatus.includes("\0")) || decision.consequences !== void 0 && typeof decision.consequences !== "string" || decision.dependencyRules !== void 0 && (!Array.isArray(decision.dependencyRules) || !decision.dependencyRules.every((rule) => isRecord8(rule) && typeof rule.from === "string" && rule.from.trim() && typeof rule.deny === "string" && rule.deny.trim()))) return true; - if (decision.source !== void 0 && (!isRecord7(decision.source) || decision.source.kind !== "pull-request" || decision.source.verification !== "unverified-local-attribution" || !isDecisionPullRequestUrl(decision.source.url))) + if (decision.source !== void 0 && (!isRecord8(decision.source) || decision.source.kind !== "pull-request" || decision.source.verification !== "unverified-local-attribution" || !isDecisionPullRequestUrl(decision.source.url))) return true; return decision.targets.some((target) => { - if (!isRecord7(target) || !["explicit", "literal-mention"].includes(String(target.evidence))) + if (!isRecord8(target) || !["explicit", "literal-mention"].includes(String(target.evidence))) return true; if (target.kind === "file") return !isRepositoryRelativePath(target.path); @@ -8089,13 +8356,13 @@ function validateFixMapReport(candidate, label) { } if (record3.policy !== void 0) { const policy = record3.policy; - if (!isRecord7(policy) || typeof policy.policyFingerprint !== "string" || !/^(?:git|worktree):[a-f0-9]{40,64}$/i.test(policy.policyFingerprint) || !Array.isArray(policy.findings)) { + if (!isRecord8(policy) || typeof policy.policyFingerprint !== "string" || !/^(?:git|worktree):[a-f0-9]{40,64}$/i.test(policy.policyFingerprint) || !Array.isArray(policy.findings)) { return { success: false, message: `${label} has an invalid architecture policy envelope.` }; } const invalidPolicyFinding = policy.findings.findIndex((finding) => { - if (!isRecord7(finding) || !["boundary-violation", "required-test-missing", "review-required", "breaking-contract"].includes(String(finding.code)) || !["info", "warning", "error"].includes(String(finding.severity)) || typeof finding.ruleId !== "string" || !/^[a-z0-9][a-z0-9._-]{0,63}$/.test(finding.ruleId) || typeof finding.message !== "string" || !finding.message.trim() || !isRepositoryRelativePathArray(finding.paths) || !Array.isArray(finding.evidence)) + if (!isRecord8(finding) || !["boundary-violation", "required-test-missing", "review-required", "breaking-contract"].includes(String(finding.code)) || !["info", "warning", "error"].includes(String(finding.severity)) || typeof finding.ruleId !== "string" || !/^[a-z0-9][a-z0-9._-]{0,63}$/.test(finding.ruleId) || typeof finding.message !== "string" || !finding.message.trim() || !isRepositoryRelativePathArray(finding.paths) || !Array.isArray(finding.evidence)) return true; - return finding.evidence.some((evidence) => !isRecord7(evidence) || !["import", "changed-file", "test-pattern", "reviewer", "contract-change", "decision-record"].includes(String(evidence.kind)) || typeof evidence.detail !== "string" || !evidence.detail.trim() || evidence.path !== void 0 && !isRepositoryRelativePath(evidence.path) || evidence.relatedPath !== void 0 && !isRepositoryRelativePath(evidence.relatedPath)); + return finding.evidence.some((evidence) => !isRecord8(evidence) || !["import", "changed-file", "test-pattern", "reviewer", "contract-change", "decision-record"].includes(String(evidence.kind)) || typeof evidence.detail !== "string" || !evidence.detail.trim() || evidence.path !== void 0 && !isRepositoryRelativePath(evidence.path) || evidence.relatedPath !== void 0 && !isRepositoryRelativePath(evidence.relatedPath)); }); if (invalidPolicyFinding !== -1) { return { success: false, message: `${label} has an invalid architecture policy finding at index ${invalidPolicyFinding}.` }; @@ -8103,7 +8370,7 @@ function validateFixMapReport(candidate, label) { } const diagnostics = record3.diagnostics; const invalidDiagnostic = diagnostics.findIndex((diagnostic) => { - if (!isRecord7(diagnostic)) + if (!isRecord8(diagnostic)) return true; return typeof diagnostic.code !== "string" || !diagnostic.code.trim() || typeof diagnostic.message !== "string" || diagnostic.severity !== "info" && diagnostic.severity !== "warning" && diagnostic.severity !== "error" || diagnostic.paths !== void 0 && !isRepositoryRelativePathArray(diagnostic.paths); }); @@ -8115,21 +8382,21 @@ function validateFixMapReport(candidate, label) { } if (record3.analysis !== void 0) { const analysis = record3.analysis; - const grounding = isRecord7(analysis) ? analysis.grounding : void 0; - const specificity = isRecord7(grounding) ? grounding.specificity : void 0; + const grounding = isRecord8(analysis) ? analysis.grounding : void 0; + const specificity = isRecord8(grounding) ? grounding.specificity : void 0; if (specificity !== "anchored" && specificity !== "descriptive" && specificity !== "vague") { return { success: false, message: `${label} has invalid analysis.grounding.specificity; expected anchored, descriptive, or vague.` }; } - if (!isRecord7(analysis) || !isRecord7(grounding) || !Array.isArray(grounding.identifiers) || !isStringArray(grounding.unresolvedIdentifiers) || !isStringArray(grounding.partiallyResolvedIdentifiers) || !isStringArray(grounding.unverifiedIdentifiers) || typeof grounding.scanComplete !== "boolean" || !isRecord7(analysis.ranking) || !isNullableFiniteNumber(analysis.ranking.topScore) || !isNullableFiniteNumber(analysis.ranking.runnerUpScore) || !isNullableFiniteNumber(analysis.ranking.topGap) || typeof analysis.ranking.clustered !== "boolean" || typeof analysis.nextAction !== "string") { + if (!isRecord8(analysis) || !isRecord8(grounding) || !Array.isArray(grounding.identifiers) || !isStringArray(grounding.unresolvedIdentifiers) || !isStringArray(grounding.partiallyResolvedIdentifiers) || !isStringArray(grounding.unverifiedIdentifiers) || typeof grounding.scanComplete !== "boolean" || !isRecord8(analysis.ranking) || !isNullableFiniteNumber(analysis.ranking.topScore) || !isNullableFiniteNumber(analysis.ranking.runnerUpScore) || !isNullableFiniteNumber(analysis.ranking.topGap) || typeof analysis.ranking.clustered !== "boolean" || typeof analysis.nextAction !== "string") { return { success: false, message: `${label} has incomplete or invalid analysis grounding, ranking, or nextAction fields.` }; } - const invalidIdentifier = grounding.identifiers.findIndex((identifier) => !isRecord7(identifier) || typeof identifier.identifier !== "string" || !identifier.identifier.trim() || !isIdentifierStatus(identifier.status) || !isRepositoryRelativePathArray(identifier.matchedFiles)); + const invalidIdentifier = grounding.identifiers.findIndex((identifier) => !isRecord8(identifier) || typeof identifier.identifier !== "string" || !identifier.identifier.trim() || !isIdentifierStatus(identifier.status) || !isRepositoryRelativePathArray(identifier.matchedFiles)); if (invalidIdentifier !== -1) { return { success: false, @@ -8138,15 +8405,15 @@ function validateFixMapReport(candidate, label) { } if (analysis.retrievalRanking !== void 0) { const retrievalRanking = analysis.retrievalRanking; - if (!isRecord7(retrievalRanking) || !isNullableFiniteNumber(retrievalRanking.topFusionScore) || !isNullableFiniteNumber(retrievalRanking.runnerUpFusionScore) || !isNullableFiniteNumber(retrievalRanking.topGap)) { + if (!isRecord8(retrievalRanking) || !isNullableFiniteNumber(retrievalRanking.topFusionScore) || !isNullableFiniteNumber(retrievalRanking.runnerUpFusionScore) || !isNullableFiniteNumber(retrievalRanking.topGap)) { return { success: false, message: `${label} has invalid analysis.retrievalRanking fields.` }; } } } if (record3.retrieval !== void 0) { const retrieval = record3.retrieval; - const weights = isRecord7(retrieval) ? retrieval.weights : void 0; - if (!isRecord7(retrieval) || retrieval.mode !== "structural-lexical" && retrieval.mode !== "structural-lexical-semantic" || !isRecord7(weights) || !isPositiveFiniteNumber(weights.structural) || !isPositiveFiniteNumber(weights.lexical) || !isPositiveFiniteNumber(weights.semantic) || !isPositiveFiniteNumber(weights.reciprocalRankConstant)) { + const weights = isRecord8(retrieval) ? retrieval.weights : void 0; + if (!isRecord8(retrieval) || retrieval.mode !== "structural-lexical" && retrieval.mode !== "structural-lexical-semantic" || !isRecord8(weights) || !isPositiveFiniteNumber(weights.structural) || !isPositiveFiniteNumber(weights.lexical) || !isPositiveFiniteNumber(weights.semantic) || !isPositiveFiniteNumber(weights.reciprocalRankConstant)) { return { success: false, message: `${label} has an invalid retrieval envelope.` }; } if (retrieval.mode === "structural-lexical-semantic" && !isSemanticProvenance(retrieval.semantic)) { @@ -8158,7 +8425,7 @@ function validateFixMapReport(candidate, label) { } return { success: true, report: candidate }; } -function isRecord7(candidate) { +function isRecord8(candidate) { return typeof candidate === "object" && candidate !== null && !Array.isArray(candidate); } function isStringArray(candidate) { @@ -8181,7 +8448,7 @@ function isIdentifierStatus(candidate) { return candidate === "exact-definition" || candidate === "exact-text" || candidate === "partial-definition" || candidate === "not-found" || candidate === "unverified"; } function isRetrievalSignal(candidate) { - if (!isRecord7(candidate)) + if (!isRecord8(candidate)) return false; const ranks = [candidate.structuralRank, candidate.lexicalRank, candidate.semanticRank]; if (ranks.every((rank) => rank === void 0)) @@ -8193,7 +8460,7 @@ function isRetrievalSignal(candidate) { return candidate.semanticSimilarity === void 0 || typeof candidate.semanticSimilarity === "number" && Number.isFinite(candidate.semanticSimilarity) && candidate.semanticSimilarity >= -1 && candidate.semanticSimilarity <= 1; } function isSemanticProvenance(candidate) { - if (!isRecord7(candidate)) + if (!isRecord8(candidate)) return false; return typeof candidate.id === "string" && candidate.id.trim().length > 0 && typeof candidate.version === "string" && candidate.version.trim().length > 0 && typeof candidate.model === "string" && candidate.model.trim().length > 0 && typeof candidate.artifactHash === "string" && /^[a-f0-9]{64}$/.test(candidate.artifactHash) && typeof candidate.runtime === "string" && candidate.runtime.trim().length > 0 && Number.isSafeInteger(candidate.dimensions) && Number(candidate.dimensions) > 0 && (candidate.normalization === "l2" || candidate.normalization === "none") && typeof candidate.local === "boolean" && typeof candidate.cacheKey === "string" && candidate.cacheKey.trim().length > 0 && Number.isSafeInteger(candidate.indexedFiles) && Number(candidate.indexedFiles) >= 0 && Number.isSafeInteger(candidate.truncatedFiles) && Number(candidate.truncatedFiles) >= 0; } @@ -8204,14 +8471,6 @@ function isPositiveFiniteNumber(candidate) { // packages/core/dist/editor-transport.js var EDITOR_RESPONSE_MAX_BYTES = 4 * 1024 * 1024; -// packages/core/dist/architecture-history.js -import { execFile as execFile3, spawn as spawn2 } from "node:child_process"; -import { promisify as promisify3 } from "node:util"; -var exec3 = promisify3(execFile3); -var MAX_TREE_BYTES = 32 * 1024 * 1024; -var MAX_BATCH_BYTES = 64 * 1024 * 1024; -var MAX_BATCH_OUTPUT_BYTES = MAX_BATCH_BYTES + 2 * 1024 * 1024; - // packages/action/src/annotations.ts async function runAnnotationAction(input, repoRoot, allowWrite) { if (Buffer.byteLength(input, "utf8") > 32768) throw new Error("annotation-request exceeds 32 KiB."); @@ -8254,9 +8513,9 @@ async function runAnnotationAction(input, repoRoot, allowWrite) { }); if ("path" in annotation.scope && annotation.scope.path) { const root = await realpath3(repoRoot); - const target = await realpath3(resolve4(root, annotation.scope.path)); - const inside = relative2(root, target); - if (!inside || isAbsolute2(inside) || inside === ".." || inside.startsWith("../") || inside.startsWith("..\\") || !(await stat3(target)).isFile()) { + const target = await realpath3(resolve5(root, annotation.scope.path)); + const inside = relative3(root, target); + if (!inside || isAbsolute3(inside) || inside === ".." || inside.startsWith("../") || inside.startsWith("..\\") || !(await stat3(target)).isFile()) { throw new Error("Annotation target must be an existing file inside the checkout."); } } @@ -8270,7 +8529,7 @@ function record2(value) { // packages/action/src/runner.ts import { appendFileSync, readFileSync, statSync } from "node:fs"; -import { resolve as resolve5 } from "node:path"; +import { resolve as resolve6 } from "node:path"; // packages/action/src/github.ts var FIXMAP_REPORT_MARKER = ""; @@ -8667,7 +8926,7 @@ async function runVerifyMode(context) { includeUntracked: context.includeUntracked, useCache: !context.noCache, includeHistory: true, - internalExclude: [resolve5(repoRoot, reportPath)] + internalExclude: [resolve6(repoRoot, reportPath)] }); const diffFailure = repo.diagnostics.find((diagnostic) => diagnostic.code === "diff-unavailable"); if (diffFailure) { diff --git a/packages/cli/README.md b/packages/cli/README.md index e2047251..4020b9a3 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -168,7 +168,8 @@ For long task text, use `--issue-file task.md`, pipe it directly to `fixmap plan - **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. - **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. +- **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. - **Supply-chain evidence** — use `fixmap supply-chain --input ` to validate normalized package/security/license evidence without executing a scanner or inventing advisory truth. - **Runtime evidence** — use `fixmap runtime --input ` to map redaction-reviewed traces and profiles only through exact repository paths and fingerprints. - **Execution sandbox** — use `fixmap sandbox --request --execute-declared-command` to run one exact reviewed command with a pinned local image, network off, read-only source/root, and resource limits. diff --git a/packages/cli/src/cli-runner.ts b/packages/cli/src/cli-runner.ts index 66feda9a..41cae3b3 100644 --- a/packages/cli/src/cli-runner.ts +++ b/packages/cli/src/cli-runner.ts @@ -43,6 +43,7 @@ export type CliOptions = { baseRef?: string | undefined; headRef?: string | undefined; checkoutRef?: string | undefined; + atRef?: string | undefined; format: "markdown" | "json" | "agent"; output?: string | undefined; explainPath?: string | undefined; @@ -95,6 +96,7 @@ Usage: fixmap plan --issue "Fix login" --format agent fixmap plan --issue "Fix login in auth middleware" --compare plan.json fixmap plan --base main --head HEAD --format json + fixmap plan --issue "Fix login" --at v0.9.0 fixmap verify --report plan.json --diff main...HEAD fixmap verify --report plan.json --working-tree fixmap verify --report plan.json --working-tree --fail-on warning @@ -162,6 +164,7 @@ Options: --evidence Attach a version-1 evidence bundle from another tool (repeatable; data only, never executed) --repo Local path or public GitHub HTTPS URL (defaults to current directory) --ref Branch or tag to scan when --repo is a remote GitHub URL + --at Preview: Rank against a local committed ref, read from Git objects without checkout --limit Maximum context files to report (default 8, max 20) --exclude Path pattern to leave out of ranking (repeatable) --format Output format: markdown (default), json, or compact agent @@ -631,7 +634,7 @@ export async function runCli(args: string[], dependencies: CliDependencies = {}) return 1; } if (options.command === "verify") { - const planOnly = [options.issueText && "--issue", options.issueFile && "--issue-file", options.comparePath && "--compare", options.limit !== undefined && "--limit", options.exclude.length > 0 && "--exclude", options.explainPath && "--explain", options.semanticModelPath && "--semantic-model", options.evidencePaths.length > 0 && "--evidence"].filter(Boolean); + const planOnly = [options.issueText && "--issue", options.issueFile && "--issue-file", options.comparePath && "--compare", options.limit !== undefined && "--limit", options.exclude.length > 0 && "--exclude", options.explainPath && "--explain", options.semanticModelPath && "--semantic-model", options.evidencePaths.length > 0 && "--evidence", options.atRef && "--at"].filter(Boolean); if (planOnly.length > 0) { stderr(`verify does not accept plan-only option(s): ${planOnly.join(", ")}.\n`); return 1; } const outputCollision = await describeOutputInputCollision(options); if (outputCollision) { stderr(`${outputCollision}\n`); return 1; } @@ -699,6 +702,22 @@ export async function runCli(args: string[], dependencies: CliDependencies = {}) stderr("--ref only applies when --repo is a remote GitHub URL or the issue URL infers one.\n"); return 1; } + if (options.atRef) { + const conflicting = [ + (options.diffSpec || options.baseRef || options.headRef) && "--diff/--base/--head", + options.workingTree && "--working-tree", + options.explainPath && "--explain", + remoteRepository && "a remote repository" + ].filter(Boolean); + if (conflicting.length > 0) { + stderr(`--at ranks one local committed state and cannot be combined with ${conflicting.join(", ")}.\n`); + return 1; + } + if (!options.issueText) { + stderr("--at needs --issue or --issue-file so there is a task to rank against.\n"); + return 1; + } + } const unsupportedTaskUrl = describeUnsupportedTaskUrl(options.issueText); if (unsupportedTaskUrl) { stderr(`${unsupportedTaskUrl}\n`); return 1; } @@ -775,6 +794,7 @@ export async function runCli(args: string[], dependencies: CliDependencies = {}) baseRef: options.baseRef, headRef: options.headRef, checkoutRef: options.checkoutRef, + ...(options.atRef ? { atRef: options.atRef } : {}), workingTree: options.workingTree, includeUntracked: options.includeUntracked, useCache: !options.noCache, @@ -1026,6 +1046,7 @@ const SINGLE_VALUE_FLAGS = new Set([ "--base", "--head", "--ref", + "--at", "--repo", "--semantic-model", "--evidence", @@ -1067,6 +1088,7 @@ export function parseArgs(args: string[]): CliOptions { let baseRef: string | undefined; let headRef: string | undefined; let checkoutRef: string | undefined; + let atRef: string | undefined; let format: "markdown" | "json" | "agent" = "markdown"; let output: string | undefined; let explainPath: string | undefined; @@ -1149,6 +1171,11 @@ export function parseArgs(args: string[]): CliOptions { } else { invalidValues.push("--ref requires a safe branch or tag name"); } + } else if (arg === "--at") { + consumeValue(); + const trimmed = value?.trim(); + if (trimmed && trimmed.length <= 500 && !/[\0\r\n]/.test(trimmed) && !trimmed.startsWith("-")) atRef = trimmed; + else invalidValues.push("--at requires a bounded single-line Git ref"); } else if (arg === "--repo") { consumeValue(); if (value?.trim()) repo = expandHomePath(value.trim()); @@ -1234,6 +1261,7 @@ export function parseArgs(args: string[]): CliOptions { baseRef, headRef, checkoutRef, + atRef, format, output, explainPath, diff --git a/packages/cli/src/history-command.ts b/packages/cli/src/history-command.ts index 862779dd..54664790 100644 --- a/packages/cli/src/history-command.ts +++ b/packages/cli/src/history-command.ts @@ -1,18 +1,17 @@ import { realpath, stat, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; import { resolve } from "node:path"; -import { compareArchitectureRefs, type ArchitectureDrift, type HistoricalArchitectureSnapshot } from "@aryam/fixmap-core"; +import { compareArchitectureRefs, type ArchitectureRefComparison } from "@aryam/fixmap-core"; -export const HISTORY_USAGE = `Usage: fixmap history --from --to [--repo ] [--coupling-delta ] [--no-policy] [--format markdown|json] [--output ] +export const HISTORY_USAGE = `Usage: fixmap history --from --to [--repo ] [--coupling-delta ] [--no-policy] [--no-cache] [--format markdown|json] [--output ] -Compares exact committed architecture snapshots through Git objects without checking out either ref or changing the worktree. +Preview: Compares exact committed architecture snapshots through Git objects without checking out either ref or changing the worktree. +Reports added/removed import edges, new/resolved cycles, .fixmap/policy.json boundary violations, coupling growth, and +decision disagreements: edges at --to that break a fixmap-deny-imports rule stated by an accepted decision record. +Snapshots are cached per exact commit outside the repository (FIXMAP_CACHE_DIR); --no-cache rebuilds them. `; -type HistoryResult = { - from: HistoricalArchitectureSnapshot; - to: HistoricalArchitectureSnapshot; - drift: ArchitectureDrift; -}; +type HistoryResult = ArchitectureRefComparison; export async function runHistoryCommand( args: string[], @@ -42,7 +41,8 @@ export async function runHistoryCommand( fromRef: parsed.from, toRef: parsed.to, applyRepositoryPolicy: parsed.applyPolicy, - couplingDelta: parsed.couplingDelta + couplingDelta: parsed.couplingDelta, + useCache: parsed.useCache }); const rendered = parsed.format === "json" ? `${JSON.stringify(result, null, 2)}\n` : renderHistoryMarkdown(result); if (parsed.output) await (dependencies.writeOutput ?? ((path, contents) => writeFile(path, contents, "utf8")))(parsed.output, rendered); @@ -75,6 +75,12 @@ export function renderHistoryMarkdown(result: HistoryResult): string { ...section("New boundary violations", drift.newBoundaryViolations, (entry) => `\`${entry.ruleId}\`: \`${entry.from}\` -> \`${entry.to}\``), ...section("Resolved boundary violations", drift.resolvedBoundaryViolations, (entry) => `\`${entry.ruleId}\`: \`${entry.from}\` -> \`${entry.to}\``), ...section("Coupling growth", drift.couplingGrowth, (entry) => `\`${entry.path}\`: ${entry.before} -> ${entry.after} (+${entry.delta})`), + ...section("Decision disagreements", result.decisionDisagreements, (entry) => + `\`${entry.decisionPath}\` (${entry.decisionTitle}) denies \`${entry.rule.from}\` -> \`${entry.rule.deny}\`; ` + + `\`${entry.edge.from}\` -> \`${entry.edge.to}\` ${entry.introduced ? "was introduced in this range" : "already existed at the earlier ref"}`), + ...(result.to.decisionDiagnostics.length > 0 + ? section("Decision records not evaluated", result.to.decisionDiagnostics, (entry) => entry.message) + : []), "> Read-only historical comparison. FixMap read committed Git objects and did not checkout a ref or change the worktree." ].join("\n")}\n`; } @@ -86,6 +92,7 @@ type ParsedArgs = { repo: string; couplingDelta: number; applyPolicy: boolean; + useCache: boolean; format: "markdown" | "json"; output?: string; } | { ok: false; message: string }; @@ -96,15 +103,17 @@ function parseArgs(args: string[]): ParsedArgs { let repo = "."; let couplingDelta = 2; let applyPolicy = true; + let useCache = true; let format: "markdown" | "json" = "markdown"; let output: string | undefined; const seen = new Set(); for (let index = 0; index < args.length; index += 1) { const raw = args[index]!; - if (raw === "--no-policy") { - if (seen.has(raw)) return { ok: false, message: "Pass --no-policy only once." }; + if (raw === "--no-policy" || raw === "--no-cache") { + if (seen.has(raw)) return { ok: false, message: `Pass ${raw} only once.` }; seen.add(raw); - applyPolicy = false; + if (raw === "--no-policy") applyPolicy = false; + else useCache = false; continue; } const separator = raw.indexOf("="); @@ -134,7 +143,7 @@ function parseArgs(args: string[]): ParsedArgs { } } if (!from || !to) return { ok: false, message: "history requires both --from and --to ." }; - return { ok: true, from, to, repo, couplingDelta, applyPolicy, format, ...(output ? { output } : {}) }; + return { ok: true, from, to, repo, couplingDelta, applyPolicy, useCache, format, ...(output ? { output } : {}) }; } function historyError(repo: string, error: unknown): string { diff --git a/packages/cli/src/mcp.ts b/packages/cli/src/mcp.ts index 70326eb1..738874c5 100644 --- a/packages/cli/src/mcp.ts +++ b/packages/cli/src/mcp.ts @@ -65,6 +65,7 @@ type PlanArguments = { head?: string; repo?: string; ref?: string; + at?: string; format?: "markdown" | "json" | "agent"; limit?: number; exclude?: string[]; @@ -149,6 +150,12 @@ const PLAN_TOOL = { "GitHub URLs support issue-only analysis and are removed after scanning." }, ref: { type: "string", description: "Branch or tag to scan when repo is a remote GitHub URL" }, + at: { + type: "string", + description: + "Preview (may change before v0.10.0): Rank against this committed Git ref of a local repo, read from Git objects " + + "without checking out or changing the worktree. Needs issue; cannot be combined with diff, base/head, workingTree, or a remote repo." + }, format: { type: "string", description: "Output format: markdown (default), json, or compact agent, case-insensitive" @@ -391,7 +398,9 @@ const HISTORY_TOOL = { title: "FixMap history", description: "Preview (may change before v0.10.0): Compare architecture at two exact committed Git refs without checking out either ref or changing the worktree. " + - "Returns immutable commit IDs plus added/removed edges, cycle and boundary drift, and coupling growth.", + "Returns immutable commit IDs plus added/removed edges, cycle and boundary drift, coupling growth, and decision disagreements: " + + "edges at the later ref that break a fixmap-deny-imports rule stated by an accepted decision record. " + + "Snapshots are cached per exact commit outside the repository.", inputSchema: { type: "object" as const, properties: { @@ -400,6 +409,7 @@ const HISTORY_TOOL = { to: { type: "string", description: "Later committed Git ref" }, couplingDelta: { type: "integer", minimum: 1, maximum: 10000, description: "Minimum coupling growth to report (default 2)" }, applyPolicy: { type: "boolean", description: "Apply the repository architecture policy when present (default true)" }, + noCache: { type: "boolean", description: "Rebuild both snapshots instead of reusing the per-commit cache" }, format: { type: "string", description: "Output format: markdown (default) or json, case-insensitive" } }, required: ["from", "to"], @@ -749,7 +759,7 @@ export function createFixMapMcpServer( } if (request.params.name === HISTORY_TOOL.name) { const record = request.params.arguments as Record | undefined; - const unknown = Object.keys(record ?? {}).filter((key) => !["repo", "from", "to", "couplingDelta", "applyPolicy", "format"].includes(key)); + const unknown = Object.keys(record ?? {}).filter((key) => !["repo", "from", "to", "couplingDelta", "applyPolicy", "noCache", "format"].includes(key)); if (unknown.length > 0) { return { isError: true, content: [{ type: "text", text: `Invalid arguments: unknown argument${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}.` }] }; } @@ -763,8 +773,10 @@ export function createFixMapMcpServer( if (record.couplingDelta !== undefined && (!Number.isSafeInteger(record.couplingDelta) || Number(record.couplingDelta) < 1 || Number(record.couplingDelta) > 10_000)) { return { isError: true, content: [{ type: "text", text: 'Invalid arguments: "couplingDelta" must be an integer from 1 to 10000.' }] }; } - if (record.applyPolicy !== undefined && typeof record.applyPolicy !== "boolean") { - return { isError: true, content: [{ type: "text", text: 'Invalid arguments: "applyPolicy" must be a boolean.' }] }; + for (const name of ["applyPolicy", "noCache"] as const) { + if (record[name] !== undefined && typeof record[name] !== "boolean") { + return { isError: true, content: [{ type: "text", text: `Invalid arguments: "${name}" must be a boolean.` }] }; + } } const format = normalizeFormat(record.format); if (!format.success) return { isError: true, content: [{ type: "text", text: `Invalid arguments: ${format.message}` }] }; @@ -775,7 +787,8 @@ export function createFixMapMcpServer( fromRef: record.from.trim(), toRef: record.to.trim(), couplingDelta: record.couplingDelta === undefined ? 2 : Number(record.couplingDelta), - applyRepositoryPolicy: record.applyPolicy === undefined ? true : record.applyPolicy + applyRepositoryPolicy: record.applyPolicy !== false, + useCache: record.noCache !== true }); return { content: [{ type: "text", text: format.value === "json" ? `${JSON.stringify(result, null, 2)}\n` : renderHistoryMarkdown(result) }] }; } catch (error) { @@ -981,6 +994,7 @@ export function createFixMapMcpServer( report = await buildReportForRepository({ repo: args.repo ?? (tryParseGitHubIssueSource(args.issue ?? "") ? undefined : defaultRepo), checkoutRef: args.ref, + ...(args.at ? { atRef: args.at } : {}), issueText: args.issue, diffSpec: args.diff, baseRef: args.base, @@ -1033,7 +1047,7 @@ export function parsePlanArguments(input: unknown): PlanArgumentsValidation { } const record = input as Record; - const allowed = new Set(["issue", "diff", "base", "head", "repo", "ref", "format", "limit", "exclude", "workingTree", "includeUntracked", "noCache", "semanticModel", "evidence"]); + const allowed = new Set(["issue", "diff", "base", "head", "repo", "ref", "format", "limit", "exclude", "workingTree", "includeUntracked", "noCache", "semanticModel", "evidence", "at"]); const unknown = Object.keys(record).filter((key) => !allowed.has(key)); if (unknown.length > 0) { return { @@ -1101,6 +1115,17 @@ export function parsePlanArguments(input: unknown): PlanArgumentsValidation { return { success: false, message: '"ref" must be a safe branch or tag name.' }; } if (value.issue && /^https?:\/\/\S+$/i.test(value.issue) && !tryParseGitHubIssueSource(value.issue)) return { success: false, message: '"issue" URL must be a canonical public GitHub issue or pull request URL.' }; + if (record.at !== undefined) { + if (typeof record.at !== "string" || !record.at.trim() || record.at.length > 500 || /[\0\r\n]/.test(record.at) || record.at.trim().startsWith("-")) { + return { success: false, message: '"at" must be a bounded single-line Git ref.' }; + } + if (value.diff || value.base || value.head || value.workingTree) return { success: false, message: '"at" cannot be combined with diff, base/head, or workingTree.' }; + if (/^https?:\/\//i.test(value.repo ?? "") || (!value.repo && tryParseGitHubIssueSource(value.issue ?? ""))) { + return { success: false, message: '"at" needs a local repository, not a remote GitHub URL.' }; + } + if (!value.issue) return { success: false, message: '"at" needs "issue" so there is a task to rank against.' }; + value.at = record.at.trim(); + } return { success: true, value }; } diff --git a/packages/cli/src/repository-source.ts b/packages/cli/src/repository-source.ts index ab8f47f4..674fba4b 100644 --- a/packages/cli/src/repository-source.ts +++ b/packages/cli/src/repository-source.ts @@ -31,6 +31,8 @@ export type RepositoryPlanInput = { baseRef?: string | undefined; headRef?: string | undefined; checkoutRef?: string | undefined; + /** Preview: rank against this local committed ref without checking it out. */ + atRef?: string | undefined; workingTree?: boolean | undefined; includeUntracked?: boolean | undefined; useCache?: boolean | undefined; @@ -574,7 +576,8 @@ export async function buildReportForRepository( exclude: input.exclude, internalExclude: input.internalExclude, embeddingProvider, - ...(evidenceSources.length > 0 ? { evidenceSources } : {}) + ...(evidenceSources.length > 0 ? { evidenceSources } : {}), + ...(input.atRef ? { atRef: input.atRef } : {}) }); reportProgress(`ranked ${report.contextFiles.length} context files`); const sourceDiagnostics = [issueDiagnostic, resolvedSource.diagnostic].filter( diff --git a/packages/cli/test/cli-runner.test.ts b/packages/cli/test/cli-runner.test.ts index 7920fb22..45185a9f 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", "Product capabilities", "Cross-repository workspace", "Repository Q&A", "Migration planning", - "Reverse documentation", "Architecture history", "Supply-chain evidence", "Runtime evidence", "Evidence import", "Execution sandbox", + "Reverse documentation", "Architecture history", "Historical plans", "Supply-chain evidence", "Runtime evidence", "Evidence import", "Execution sandbox", "Local hybrid retrieval" ]); expect(features.find((feature) => feature.name === "Plan")?.preview).toBeUndefined(); diff --git a/packages/cli/test/history-drift.test.ts b/packages/cli/test/history-drift.test.ts new file mode 100644 index 00000000..c95ab7b8 --- /dev/null +++ b/packages/cli/test/history-drift.test.ts @@ -0,0 +1,183 @@ +import { execFile } from "node:child_process"; +import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { promisify } from "node:util"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { runCli } from "../src/cli-runner.js"; +import { createFixMapMcpServer, parsePlanArguments } from "../src/mcp.js"; + +const exec = promisify(execFile); +const TIMEOUT = process.platform === "win32" ? 60_000 : 30_000; +const ODD = "space dir/ünïcode/deep/er/still"; +const roots: string[] = []; +let previousCacheDir: string | undefined; +let cacheDir: string; + +beforeEach(async () => { + previousCacheDir = process.env.FIXMAP_CACHE_DIR; + cacheDir = await mkdtemp(join(tmpdir(), "fixmap-cli-arch-cache-")); + roots.push(cacheDir); + process.env.FIXMAP_CACHE_DIR = cacheDir; +}); + +afterEach(async () => { + if (previousCacheDir === undefined) delete process.env.FIXMAP_CACHE_DIR; + else process.env.FIXMAP_CACHE_DIR = previousCacheDir; + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }))); +}); + +async function put(root: string, path: string, content: string): Promise { + await mkdir(dirname(join(root, path)), { recursive: true }); + await writeFile(join(root, path), content, "utf8"); +} + +async function commit(root: string, message: string): Promise { + await exec("git", ["add", "-A"], { cwd: root }); + await exec("git", ["commit", "--quiet", "-m", message], { cwd: root }); + return (await exec("git", ["rev-parse", "HEAD"], { cwd: root })).stdout.trim(); +} + +async function fixture(): Promise<{ root: string; before: string; after: string }> { + const root = await mkdtemp(join(tmpdir(), "fixmap-cli-drift-")); + roots.push(root); + await exec("git", ["init", "--quiet"], { cwd: root }); + await exec("git", ["config", "user.email", "fixmap@example.test"], { cwd: root }); + await exec("git", ["config", "user.name", "FixMap Test"], { cwd: root }); + await put(root, "src/api/handler.ts", "export const handler = 1;\n"); + await put(root, `${ODD}/legacy.ts`, "export const legacy = 1;\n"); + await put(root, "docs/adr/0007-api-no-legacy.md", + `---\nstatus: accepted\nfixmap-deny-imports:\n - "src/api/** -> space dir/**"\n---\n# API never imports legacy\n\n## Decision\n\nThe API stays independent.\n`); + const before = await commit(root, "before"); + await put(root, "src/api/handler.ts", `import { legacy } from '../../${ODD}/legacy';\nexport const handler = legacy;\n`); + await put(root, "src/api/password-reset.ts", "export function passwordReset() { return 'reset'; }\n"); + const after = await commit(root, "after"); + return { root, before, after }; +} + +async function gitState(root: string): Promise<{ head: string; status: string }> { + return { + head: (await exec("git", ["rev-parse", "HEAD"], { cwd: root })).stdout.trim(), + status: (await exec("git", ["status", "--porcelain=v1", "--untracked-files=all"], { cwd: root })).stdout + }; +} + +function capture() { + const stdout: string[] = []; + const stderr: string[] = []; + return { stdout, stderr, dependencies: { stdout: (text: string) => stdout.push(text), stderr: (text: string) => stderr.push(text) } }; +} + +describe("fixmap history drift and decision disagreements", () => { + it("renders decision disagreements in Markdown and JSON with exact commits", async () => { + const { root, before, after } = await fixture(); + const state = await gitState(root); + const markdown = capture(); + const json = capture(); + + expect(await runCli(["history", "--repo", root, "--from", before, "--to", after], markdown.dependencies)).toBe(0); + const text = markdown.stdout.join(""); + expect(text).toContain(`at \`${before}\``); + expect(text).toContain(`at \`${after}\``); + expect(text).toContain("## Decision disagreements"); + expect(text).toContain(`\`docs/adr/0007-api-no-legacy.md\` (API never imports legacy) denies \`src/api/**\` -> \`space dir/**\`; \`src/api/handler.ts\` -> \`${ODD}/legacy.ts\` was introduced in this range`); + expect((await readdir(cacheDir)).filter((name) => name.startsWith("architecture-"))).toHaveLength(2); + + expect(await runCli(["history", "--repo", root, "--from", before, "--to", after, "--format", "json", "--no-cache"], json.dependencies)).toBe(0); + const result = JSON.parse(json.stdout.join("")); + expect(result.decisionDisagreements).toEqual([expect.objectContaining({ + decisionPath: "docs/adr/0007-api-no-legacy.md", + edge: { from: "src/api/handler.ts", to: `${ODD}/legacy.ts` }, + introduced: true + })]); + expect(result.drift.addedEdges).toContainEqual({ from: "src/api/handler.ts", to: `${ODD}/legacy.ts` }); + expect(await gitState(root)).toEqual(state); + }, TIMEOUT); + + it("rejects a repeated --no-cache and unknown refs cleanly", async () => { + const { root, before } = await fixture(); + const repeated = capture(); + const unknown = capture(); + expect(await runCli(["history", "--repo", root, "--from", before, "--to", "HEAD", "--no-cache", "--no-cache"], repeated.dependencies)).toBe(1); + expect(repeated.stderr.join("")).toContain("Pass --no-cache only once."); + expect(await runCli(["history", "--repo", root, "--from", before, "--to", "does-not-exist"], unknown.dependencies)).toBe(1); + expect(unknown.stderr.join("")).toContain("Could not resolve one of the requested Git refs"); + expect(unknown.stderr.join("")).not.toContain("rev-parse"); + }, TIMEOUT); +}); + +describe("fixmap plan --at", () => { + it("ranks the committed state at the ref and leaves HEAD and status unchanged", async () => { + const { root, before, after } = await fixture(); + const state = await gitState(root); + const atBefore = capture(); + const atAfter = capture(); + + expect(await runCli(["plan", "--issue", "password reset", "--repo", root, "--at", before, "--format", "json"], atBefore.dependencies)).toBe(0); + const old = JSON.parse(atBefore.stdout.join("")); + expect(old.contextFiles.map((file: { path: string }) => file.path)).not.toContain("src/api/password-reset.ts"); + expect(old.diagnostics.find((entry: { code: string }) => entry.code === "historical-plan").message).toContain(before); + + expect(await runCli(["plan", "--issue", "password reset", "--repo", root, `--at=${after}`, "--format", "json"], atAfter.dependencies)).toBe(0); + expect(JSON.parse(atAfter.stdout.join("")).contextFiles[0].path).toBe("src/api/password-reset.ts"); + expect(await gitState(root)).toEqual(state); + }, TIMEOUT); + + it("rejects --at with diffs, the working tree, verify, or no task", async () => { + const { root } = await fixture(); + for (const [args, message] of [ + [["plan", "--issue", "x", "--repo", root, "--at", "HEAD", "--working-tree"], "cannot be combined with --working-tree"], + [["plan", "--issue", "x", "--repo", root, "--at", "HEAD", "--diff", "HEAD~1...HEAD"], "cannot be combined with --diff/--base/--head"], + [["plan", "--repo", root, "--at", "HEAD", "--explain", "src/api/handler.ts"], "cannot be combined with --explain"], + [["plan", "--repo", root, "--at", "HEAD", "--diff", "HEAD~1"], "cannot be combined"], + [["plan", "--issue", "x", "--repo", root, "--at", "--working-tree"], "--at requires a bounded single-line Git ref"], + [["verify", "--report", "plan.json", "--at", "HEAD"], "--at"] + ] as const) { + const io = capture(); + expect(await runCli([...args], io.dependencies)).toBe(1); + expect(io.stderr.join("")).toContain(message); + } + const unknown = capture(); + expect(await runCli(["plan", "--issue", "x", "--repo", root, "--at", "nope-ref"], unknown.dependencies)).toBe(1); + expect(unknown.stderr.join("")).toContain("Could not resolve Git ref"); + }, TIMEOUT); +}); + +describe("MCP history drift and historical plans", () => { + it("returns decision disagreements from fixmap_history and ranks fixmap_plan at a ref", async () => { + const { root, before, after } = await fixture(); + const state = await gitState(root); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const server = createFixMapMcpServer({}, root); + const client = new Client({ name: "fixmap-test-client", version: "0.0.0" }); + await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]); + + const history = await client.callTool({ name: "fixmap_history", arguments: { from: before, to: after, format: "json", noCache: true } }); + expect(history.isError).toBeFalsy(); + const result = JSON.parse((history.content as Array<{ text: string }>)[0]!.text); + expect(result.to.commit).toBe(after); + expect(result.decisionDisagreements).toHaveLength(1); + const badCache = await client.callTool({ name: "fixmap_history", arguments: { from: before, to: after, noCache: "yes" } }); + expect(badCache.isError).toBe(true); + + const plan = await client.callTool({ name: "fixmap_plan", arguments: { issue: "password reset", repo: root, at: before, format: "json" } }); + expect(plan.isError).toBeFalsy(); + const report = JSON.parse((plan.content as Array<{ text: string }>)[0]!.text); + expect(report.diagnostics.some((entry: { code: string }) => entry.code === "historical-plan")).toBe(true); + expect(report.contextFiles.map((file: { path: string }) => file.path)).not.toContain("src/api/password-reset.ts"); + expect(await gitState(root)).toEqual(state); + await client.close(); + }, TIMEOUT); + + it("validates the at argument", () => { + expect(parsePlanArguments({ issue: "x", at: "v1" })).toEqual({ success: true, value: { issue: "x", at: "v1" } }); + expect(parsePlanArguments({ issue: "x", at: "" })).toMatchObject({ success: false }); + expect(parsePlanArguments({ issue: "x", at: "a\nb" })).toMatchObject({ success: false }); + expect(parsePlanArguments({ issue: "x", at: 3 })).toMatchObject({ success: false }); + expect(parsePlanArguments({ at: "v1", diff: "main...HEAD" })).toMatchObject({ success: false, message: expect.stringContaining("cannot be combined") }); + expect(parsePlanArguments({ at: "v1" })).toMatchObject({ success: false, message: expect.stringContaining("needs \"issue\"") }); + expect(parsePlanArguments({ issue: "x", at: "v1", repo: "https://github.com/a/b" })).toMatchObject({ success: false, message: expect.stringContaining("local repository") }); + }); +}); diff --git a/packages/cli/test/mcp.test.ts b/packages/cli/test/mcp.test.ts index 8c444a51..7d4ddac3 100644 --- a/packages/cli/test/mcp.test.ts +++ b/packages/cli/test/mcp.test.ts @@ -402,7 +402,7 @@ describe("fixmap mcp server", () => { expect(plan).toBeDefined(); expect(plan?.description).toContain("test commands"); expect(Object.keys(plan?.inputSchema.properties ?? {}).sort()).toEqual( - ["issue", "diff", "base", "head", "repo", "ref", "format", "limit", "exclude", "workingTree", "includeUntracked", "noCache", "semanticModel", "evidence"].sort() + ["issue", "diff", "base", "head", "repo", "ref", "at", "format", "limit", "exclude", "workingTree", "includeUntracked", "noCache", "semanticModel", "evidence"].sort() ); expect(plan?.inputSchema.additionalProperties).toBe(false); expect(plan?.inputSchema.properties?.repo?.description).toContain("public GitHub HTTPS"); @@ -439,7 +439,7 @@ describe("fixmap mcp server", () => { expect(reverseDocs?.inputSchema.required).toEqual(["input"]); expect(reverseDocs?.inputSchema.additionalProperties).toBe(false); const history = tools.tools.find((tool) => tool.name === "fixmap_history"); - expect(Object.keys(history?.inputSchema.properties ?? {}).sort()).toEqual(["repo", "from", "to", "couplingDelta", "applyPolicy", "format"].sort()); + expect(Object.keys(history?.inputSchema.properties ?? {}).sort()).toEqual(["repo", "from", "to", "couplingDelta", "applyPolicy", "noCache", "format"].sort()); expect(history?.inputSchema.required).toEqual(["from", "to"]); expect(history?.inputSchema.additionalProperties).toBe(false); const supplyChain = tools.tools.find((tool) => tool.name === "fixmap_supply_chain"); diff --git a/packages/core/src/architecture-history.ts b/packages/core/src/architecture-history.ts index 2fa9726a..a913cb19 100644 --- a/packages/core/src/architecture-history.ts +++ b/packages/core/src/architecture-history.ts @@ -1,11 +1,17 @@ import { execFile, spawn } from "node:child_process"; -import { extname, resolve } from "node:path"; +import { createHash, randomUUID } from "node:crypto"; +import { mkdir, readdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises"; +import { homedir } from "node:os"; +import { dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path"; import { promisify } from "node:util"; import { architecturePolicyFromRepo, buildArchitectureSnapshot, compareArchitectureSnapshots } from "./architecture.js"; import type { ArchitectureDrift, ArchitectureSnapshot } from "./architecture.js"; +import { inventoryDecisionRecords } from "./decisions.js"; +import type { DecisionDiagnostic } from "./decisions.js"; +import { buildPathExcluder } from "./exclude.js"; import { isLanguageTestPath } from "./language-adapters.js"; import { SOURCE_FILE_EXTENSIONS } from "./paths.js"; -import type { RepoFile, RepoMap, ScanDiagnostic } from "./types.js"; +import type { PackageScript, RepoFile, RepoMap, ScanDiagnostic } from "./types.js"; const exec = promisify(execFile); const MAX_REF_LENGTH = 500; @@ -14,6 +20,12 @@ const MAX_FILES = 25_000; const MAX_TEXT_SAMPLE_BYTES = 64_000; const MAX_BATCH_BYTES = 64 * 1024 * 1024; const MAX_BATCH_OUTPUT_BYTES = MAX_BATCH_BYTES + 2 * 1024 * 1024; +// Bump whenever the import graph, snapshot, or decision-rule derivation changes. A commit's +// tree never changes, so this version and the commit ID are the whole invalidation key. +const ARCHITECTURE_CACHE_VERSION = 1; +const ARCHITECTURE_CACHE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000; +const ARCHITECTURE_CACHE_FILE = /^architecture-v\d+-[a-f0-9]{40,64}-(?:policy|no-policy)\.json$/; +const ARCHITECTURE_CACHE_TEMP_FILE = /^architecture-v\d+-[a-f0-9]{40,64}-(?:policy|no-policy)\.json\.\d+-[0-9a-f-]{36}\.tmp$/; type TreeEntry = { mode: string; oid: string; size: number; path: string }; @@ -21,19 +33,55 @@ export type HistoricalRepoMap = { requestedRef: string; commit: string; repo: RepoMap; + /** Root `.fixmapignore` text as committed, when present and readable. */ + ignoreFile?: string; +}; + +/** An import rule stated by an accepted decision record at this commit. */ +export type HistoricalDecisionRule = { + decisionId: string; + decisionPath: string; + decisionTitle: string; + from: string; + deny: string; }; export type HistoricalArchitectureSnapshot = { requestedRef: string; commit: string; snapshot: ArchitectureSnapshot; + decisionRules: HistoricalDecisionRule[]; + /** Decision records at this commit that could not be read as authored rules. */ + decisionDiagnostics: DecisionDiagnostic[]; +}; + +export type DecisionDisagreement = { + decisionId: string; + decisionPath: string; + decisionTitle: string; + rule: { from: string; deny: string }; + edge: { from: string; to: string }; + /** True when the violating edge is absent from the earlier snapshot. */ + introduced: boolean; }; +export type ArchitectureRefComparison = { + from: HistoricalArchitectureSnapshot; + to: HistoricalArchitectureSnapshot; + drift: ArchitectureDrift; + decisionDisagreements: DecisionDisagreement[]; +}; + +type ArchitectureEntry = Omit; + /** Read a committed repository state through Git objects without checking it out. */ export async function scanRepoAtRef(input: { repoRoot: string; ref: string }): Promise { const repoRoot = resolve(input.repoRoot); const requestedRef = validateRef(input.ref); - const commit = await resolveCommit(repoRoot, requestedRef); + return scanCommit(repoRoot, requestedRef, await resolveCommit(repoRoot, requestedRef)); +} + +async function scanCommit(repoRoot: string, requestedRef: string, commit: string): Promise { const { stdout } = await exec("git", ["ls-tree", "-r", "-z", "-l", "--full-tree", commit, "--"], { cwd: repoRoot, encoding: "utf8", @@ -51,13 +99,15 @@ export async function scanRepoAtRef(input: { repoRoot: string; ref: string }): P const readable: TreeEntry[] = []; let scheduledBytes = 0; for (const entry of entries) { - if (!isSourcePath(entry.path) || entry.size > MAX_TEXT_SAMPLE_BYTES) continue; + if ((!isSourcePath(entry.path) && entry.path !== ".fixmapignore") || entry.size > MAX_TEXT_SAMPLE_BYTES) continue; if (scheduledBytes + entry.size > MAX_BATCH_BYTES) continue; readable.push(entry); scheduledBytes += entry.size; } const content = await readBlobs(repoRoot, readable); const files = entries.map((entry): RepoFile => buildRepoFile(entry, content.get(entry.oid))); + const ignoreEntry = entries.find((entry) => entry.path === ".fixmapignore"); + const ignoreBytes = ignoreEntry ? content.get(ignoreEntry.oid) : undefined; return { requestedRef, commit, @@ -65,12 +115,13 @@ export async function scanRepoAtRef(input: { repoRoot: string; ref: string }): P root: repoRoot, files, trackedFiles: entries.map((entry) => entry.path), - packageScripts: [], + packageScripts: historicalPackageScripts(files, diagnostics), changedFiles: [], diffText: "", packageManager: inferPackageManager(entries), diagnostics - } + }, + ...(ignoreBytes ? { ignoreFile: ignoreBytes.toString("utf8") } : {}) }; } @@ -78,14 +129,37 @@ export async function buildArchitectureSnapshotAtRef(input: { repoRoot: string; ref: string; applyRepositoryPolicy?: boolean; + /** Reuse and store per-commit snapshots outside the repository (default true). */ + useCache?: boolean; }): Promise { - const historical = await scanRepoAtRef(input); - const policy = input.applyRepositoryPolicy === false ? undefined : architecturePolicyFromRepo(historical.repo); - return { - requestedRef: historical.requestedRef, - commit: historical.commit, - snapshot: buildArchitectureSnapshot(historical.repo, policy) + const repoRoot = resolve(input.repoRoot); + const requestedRef = validateRef(input.ref); + const commit = await resolveCommit(repoRoot, requestedRef); + const applyPolicy = input.applyRepositoryPolicy !== false; + const cachePath = input.useCache === false ? undefined : architectureCachePath(repoRoot, commit, applyPolicy); + const cached = cachePath ? await readArchitectureCache(cachePath, commit, applyPolicy) : undefined; + if (cached) return { requestedRef, commit, ...cached }; + + const historical = await scanCommit(repoRoot, requestedRef, commit); + const policy = applyPolicy ? architecturePolicyFromRepo(historical.repo) : undefined; + const inventory = inventoryDecisionRecords(historical.repo); + const entry: ArchitectureEntry = { + snapshot: buildArchitectureSnapshot(historical.repo, policy), + // Only accepted records state intent. Proposed, rejected, superseded, and unlabeled + // records are history, and treating them as rules would invent disagreements. + decisionRules: inventory.records.filter((record) => record.status === "accepted").flatMap((record) => + (record.dependencyRules ?? []).map((rule) => ({ + decisionId: record.id, + decisionPath: record.path, + decisionTitle: record.title, + from: rule.from, + deny: rule.deny + })) + ), + decisionDiagnostics: inventory.diagnostics.filter((diagnostic) => diagnostic.code !== "decision-target-missing") }; + if (cachePath) await writeArchitectureCache(cachePath, commit, applyPolicy, entry); + return { requestedRef, commit, ...entry }; } export async function compareArchitectureRefs(input: { @@ -94,32 +168,157 @@ export async function compareArchitectureRefs(input: { toRef: string; applyRepositoryPolicy?: boolean; couplingDelta?: number; -}): Promise<{ - from: HistoricalArchitectureSnapshot; - to: HistoricalArchitectureSnapshot; - drift: ArchitectureDrift; -}> { + useCache?: boolean; +}): Promise { + const options = { + repoRoot: input.repoRoot, + ...(input.applyRepositoryPolicy !== undefined ? { applyRepositoryPolicy: input.applyRepositoryPolicy } : {}), + ...(input.useCache !== undefined ? { useCache: input.useCache } : {}) + }; const [from, to] = await Promise.all([ - buildArchitectureSnapshotAtRef({ - repoRoot: input.repoRoot, - ref: input.fromRef, - ...(input.applyRepositoryPolicy !== undefined ? { applyRepositoryPolicy: input.applyRepositoryPolicy } : {}) - }), - buildArchitectureSnapshotAtRef({ - repoRoot: input.repoRoot, - ref: input.toRef, - ...(input.applyRepositoryPolicy !== undefined ? { applyRepositoryPolicy: input.applyRepositoryPolicy } : {}) - }) + buildArchitectureSnapshotAtRef({ ...options, ref: input.fromRef }), + buildArchitectureSnapshotAtRef({ ...options, ref: input.toRef }) ]); return { from, to, drift: compareArchitectureSnapshots(from.snapshot, to.snapshot, { ...(input.couplingDelta !== undefined ? { couplingDelta: input.couplingDelta } : {}) - }) + }), + decisionDisagreements: findDecisionDisagreements(from.snapshot, to) }; } +/** Rules come from the later commit's accepted records and are checked against its edges. */ +function findDecisionDisagreements( + previous: ArchitectureSnapshot, + current: HistoricalArchitectureSnapshot +): DecisionDisagreement[] { + const earlier = new Set(previous.edges.map((edge) => `${edge.from}\0${edge.to}`)); + return current.decisionRules.flatMap((rule) => { + const from = buildPathExcluder([rule.from]); + const deny = buildPathExcluder([rule.deny]); + return current.snapshot.edges.filter((edge) => from.excludes(edge.from) && deny.excludes(edge.to)).map((edge) => ({ + decisionId: rule.decisionId, + decisionPath: rule.decisionPath, + decisionTitle: rule.decisionTitle, + rule: { from: rule.from, deny: rule.deny }, + edge: { from: edge.from, to: edge.to }, + introduced: !earlier.has(`${edge.from}\0${edge.to}`) + })); + }).sort((a, b) => a.decisionPath.localeCompare(b.decisionPath) || a.rule.from.localeCompare(b.rule.from) || + a.rule.deny.localeCompare(b.rule.deny) || a.edge.from.localeCompare(b.edge.from) || a.edge.to.localeCompare(b.edge.to)); +} + +function architectureCacheRoot(): string { + // Same location rules as the repository scan cache: FIXMAP_CACHE_DIR, else the user cache. + return resolve(process.env.FIXMAP_CACHE_DIR ?? join( + process.env.LOCALAPPDATA ?? process.env.XDG_CACHE_HOME ?? join(homedir(), ".cache"), + "fixmap", + "scans" + )); +} + +function architectureCachePath(repoRoot: string, commit: string, applyPolicy: boolean): string | undefined { + const cacheRoot = architectureCacheRoot(); + const fold = (value: string) => process.platform === "win32" ? value.toLowerCase() : value; + const distance = relative(fold(repoRoot), fold(cacheRoot)); + // Never write into the repository being read, matching the scan cache. + if (distance === "" || (distance !== ".." && !distance.startsWith(`..${sep}`) && !isAbsolute(distance))) return undefined; + return join(cacheRoot, `architecture-v${ARCHITECTURE_CACHE_VERSION}-${commit}-${applyPolicy ? "policy" : "no-policy"}.json`); +} + +async function readArchitectureCache(path: string, commit: string, applyPolicy: boolean): Promise { + try { + const parsed = JSON.parse(await readFile(path, "utf8")) as Record; + if (parsed.architectureHistoryCacheVersion !== ARCHITECTURE_CACHE_VERSION || parsed.commit !== commit || + parsed.applyPolicy !== applyPolicy || typeof parsed.checksum !== "string") return undefined; + if (parsed.checksum !== checksum(JSON.stringify(parsed.entry))) return undefined; + return isArchitectureEntry(parsed.entry) ? parsed.entry : undefined; + } catch { + // Missing, unreadable, or corrupt entries are rebuilt from Git objects. + return undefined; + } +} + +async function writeArchitectureCache(path: string, commit: string, applyPolicy: boolean, entry: ArchitectureEntry): Promise { + const temporaryPath = `${path}.${process.pid}-${randomUUID()}.tmp`; + try { + await mkdir(dirname(path), { recursive: true }); + await pruneArchitectureCache(dirname(path)); + const record = { + architectureHistoryCacheVersion: ARCHITECTURE_CACHE_VERSION, + commit, + applyPolicy, + checksum: checksum(JSON.stringify(entry)), + entry + }; + await writeFile(temporaryPath, `${JSON.stringify(record)}\n`, { encoding: "utf8", flag: "wx" }); + await rename(temporaryPath, path); + } catch { + // Caching is an optimization; a read-only cache directory must not fail a history run. + try { + await unlink(temporaryPath); + } catch { /* The rename may already have consumed it. */ } + } +} + +async function pruneArchitectureCache(directory: string): Promise { + try { + const now = Date.now(); + await Promise.all((await readdir(directory, { withFileTypes: true })) + .filter((entry) => entry.isFile() && (ARCHITECTURE_CACHE_FILE.test(entry.name) || ARCHITECTURE_CACHE_TEMP_FILE.test(entry.name))) + .map(async (entry) => { + const path = join(directory, entry.name); + try { + if (now - (await stat(path)).mtimeMs > ARCHITECTURE_CACHE_MAX_AGE_MS) await unlink(path); + } catch { /* Best effort. */ } + })); + } catch { /* A missing or read-only directory is harmless. */ } +} + +function isArchitectureEntry(value: unknown): value is ArchitectureEntry { + if (!isRecord(value) || !isRecord(value.snapshot) || !Array.isArray(value.decisionRules) || !Array.isArray(value.decisionDiagnostics)) return false; + const snapshot = value.snapshot; + const edge = (entry: unknown) => isRecord(entry) && typeof entry.from === "string" && typeof entry.to === "string"; + return snapshot.architectureSnapshotVersion === 1 && typeof snapshot.fingerprint === "string" && + typeof snapshot.sourceFingerprint === "string" && Array.isArray(snapshot.edges) && snapshot.edges.every(edge) && + Array.isArray(snapshot.cycles) && snapshot.cycles.every((cycle) => Array.isArray(cycle) && cycle.every((path) => typeof path === "string")) && + Array.isArray(snapshot.coupling) && Array.isArray(snapshot.boundaryViolations) && isRecord(snapshot.truncated) && + value.decisionRules.every((rule) => isRecord(rule) && + ["decisionId", "decisionPath", "decisionTitle", "from", "deny"].every((key) => typeof rule[key] === "string")); +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function checksum(value: string): string { + return createHash("sha256").update(value).digest("hex"); +} + +function historicalPackageScripts(files: readonly RepoFile[], diagnostics: ScanDiagnostic[]): PackageScript[] { + return files.filter((file) => file.path === "package.json" || file.path.endsWith("/package.json")).flatMap((manifest) => { + if (manifest.textSampleComplete !== true) return []; + try { + const parsed = JSON.parse(manifest.textSample.replace(/^/, "")) as { name?: unknown; scripts?: unknown }; + const packageDir = manifest.path.includes("/") ? manifest.path.slice(0, manifest.path.lastIndexOf("/")) : ""; + const packageName = typeof parsed.name === "string" && parsed.name.trim() ? parsed.name.trim() : undefined; + const scripts = isRecord(parsed.scripts) ? parsed.scripts : {}; + return Object.entries(scripts).flatMap(([name, command]) => typeof command === "string" + ? [{ name, command, packageDir, ...(packageName ? { packageName } : {}) }] + : []); + } catch { + diagnostics.push({ + code: "package-json-invalid", + severity: "warning", + message: `Could not parse ${manifest.path} at this commit; scripts from that package were skipped.` + }); + return []; + } + }); +} + function validateRef(value: string): string { const ref = value.trim(); if (!ref || ref.length > MAX_REF_LENGTH || /[\0\r\n]/.test(ref)) throw new Error("Git ref must be a bounded single-line value."); diff --git a/packages/core/src/browser.ts b/packages/core/src/browser.ts index d524cae4..b4033d66 100644 --- a/packages/core/src/browser.ts +++ b/packages/core/src/browser.ts @@ -140,6 +140,7 @@ export type { } from "./architecture.js"; export { parseDecisionRecord, selectDecisionRecords } from "./decisions.js"; export type { + DecisionDependencyRule, DecisionDiagnostic, DecisionInventory, DecisionRecord, diff --git a/packages/core/src/decisions.ts b/packages/core/src/decisions.ts index ce047a5e..e72aa980 100644 --- a/packages/core/src/decisions.ts +++ b/packages/core/src/decisions.ts @@ -19,11 +19,18 @@ export type DecisionRecord = { consequences?: string; targets: DecisionTarget[]; supersedes: string[]; + /** + * Import rules the record states explicitly in `fixmap-deny-imports` frontmatter, one + * ` -> ` per item. Prose is never read for rules. + */ + dependencyRules?: DecisionDependencyRule[]; sourceFingerprint: string; /** Repository-authored attribution, not proof of remote contents or authorship. */ source?: { kind: "pull-request"; url: string; verification: "unverified-local-attribution" }; }; +export type DecisionDependencyRule = { from: string; deny: string }; + export type DecisionDiagnostic = { code: "decision-source-incomplete" | "decision-parse-failed" | "decision-target-missing"; severity: "info" | "warning"; @@ -163,6 +170,7 @@ export function parseDecisionRecord(input: { const heading = documentHeadings(body).find((entry) => entry.level === 1); const titleDate = heading ? /^\s*Date:[ \t]*(\d{4}-\d{2}-\d{2})[ \t]*(?:\r?\n|$)/i.exec(body.slice(heading.end))?.[1] : undefined; const date = normalizeDate(frontmatter.date ?? section(sections, ["date"]) ?? titleDate); + const dependencyRules = parseDependencyRules(frontmatter["fixmap-deny-imports"]); const sourceUrl = frontmatter["fixmap-source-pr"]; if (sourceUrl !== undefined && !isDecisionPullRequestUrl(sourceUrl)) throw new Error("Invalid decision pull-request source."); return { @@ -178,6 +186,7 @@ export function parseDecisionRecord(input: { ...(consequences ? { consequences: normalizeProse(consequences, 8_000) } : {}), targets, supersedes: parseReferences(supersedesText), + ...(dependencyRules.length > 0 ? { dependencyRules } : {}), sourceFingerprint: input.fingerprint, ...(sourceUrl ? { source: { kind: "pull-request" as const, url: sourceUrl, verification: "unverified-local-attribution" as const } } : {}) } @@ -301,6 +310,30 @@ function targetKey(target: DecisionTarget): string { return `${target.kind}:${target.name}`; } +const MAX_DEPENDENCY_RULES = 100; + +/** A malformed rule rejects the whole record rather than silently dropping an authored constraint. */ +function parseDependencyRules(text: string | undefined): DecisionDependencyRule[] { + if (text === undefined || !text.trim()) return []; + const rules = text.split("\n").map((line) => line.trim()).filter(Boolean).map((line): DecisionDependencyRule => { + const match = /^(.+?)\s*->\s*(.+)$/.exec(unquote(line.replace(/^`|`$/g, ""))); + if (!match) throw new Error(`Invalid fixmap-deny-imports rule: ${line}`); + return { from: dependencyPattern(match[1]!), deny: dependencyPattern(match[2]!) }; + }); + if (rules.length > MAX_DEPENDENCY_RULES) throw new Error(`fixmap-deny-imports exceeds the ${MAX_DEPENDENCY_RULES}-rule bound.`); + const unique = new Map(rules.map((rule) => [`${rule.from}\0${rule.deny}`, rule])); + return [...unique.values()].sort((a, b) => a.from.localeCompare(b.from) || a.deny.localeCompare(b.deny)); +} + +function dependencyPattern(value: string): string { + const pattern = value.trim().replace(/^`|`$/g, "").replace(/\\/g, "/"); + if (!pattern || pattern.length > 500 || pattern.startsWith("!") || pattern.includes("\0") || pattern.includes("->") || + /^(?:\/|[A-Za-z]:)/.test(pattern) || pattern.split("/").includes("..")) { + throw new Error(`Invalid fixmap-deny-imports pattern: ${value}`); + } + return pattern; +} + function parseReferences(text: string): string[] { return [...new Set(text.split(/[\n,]/).map((value) => value.replace(/^\s*[-*]\s+/, "").trim()).filter(Boolean))].sort(); } diff --git a/packages/core/src/feature-catalog.ts b/packages/core/src/feature-catalog.ts index afdea7f1..c74e8593 100644 --- a/packages/core/src/feature-catalog.ts +++ b/packages/core/src/feature-catalog.ts @@ -21,7 +21,8 @@ export const FIXMAP_FEATURES: readonly FixMapFeature[] = [ { 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: "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." }, + { 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." }, { name: "Supply-chain evidence", preview: true, command: "fixmap supply-chain --input ", detail: "Validate normalized external scanner or SBOM evidence with exact tool, database, document, advisory, version, and license provenance." }, { name: "Runtime evidence", preview: true, command: "fixmap runtime --input ", detail: "Map redaction-reviewed OpenTelemetry, APM, Speedscope, or pprof observations only through exact repository paths and file fingerprints." }, { name: "Evidence import", preview: true, command: "fixmap plan --evidence ", detail: "Attach findings from other tools (scanners, CI, runtime monitors) to the files in a plan from a version-1 data-only bundle; claims are shown as supplied and never executed." }, diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index a7cd0cd8..0b76e017 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -224,9 +224,16 @@ export type { ArchitectureSnapshot } from "./architecture.js"; export { buildArchitectureSnapshotAtRef, compareArchitectureRefs, scanRepoAtRef } from "./architecture-history.js"; -export type { HistoricalArchitectureSnapshot, HistoricalRepoMap } from "./architecture-history.js"; +export type { + ArchitectureRefComparison, + DecisionDisagreement, + HistoricalArchitectureSnapshot, + HistoricalDecisionRule, + HistoricalRepoMap +} from "./architecture-history.js"; export { inventoryDecisionRecords, parseDecisionRecord, selectDecisionRecords } from "./decisions.js"; export type { + DecisionDependencyRule, DecisionDiagnostic, DecisionInventory, DecisionRecord, diff --git a/packages/core/src/plan.ts b/packages/core/src/plan.ts index 9195d7da..25e88493 100644 --- a/packages/core/src/plan.ts +++ b/packages/core/src/plan.ts @@ -5,6 +5,7 @@ import { markdownCode } from "./markdown.js"; import type { PathExcluder } from "./exclude.js"; import { buildHybridReportFromRepo, buildReportFromRepo } from "./report.js"; import { scanRepo } from "./repo-scan.js"; +import { scanRepoAtRef, type HistoricalRepoMap } from "./architecture-history.js"; import type { LanguageRegistry } from "./language-registry.js"; import { createCustomLanguageContext } from "./custom-language-context.js"; import type { EmbeddingProvider } from "./semantic.js"; @@ -25,6 +26,8 @@ export async function buildFixMapReport( languageRegistry?: LanguageRegistry; /** Explicit evidence providers, typically imported bundles; collected without network or code execution. */ evidenceSources?: readonly ReportEvidenceSource[]; + /** Preview: rank against this committed ref, read from Git objects without checkout. */ + atRef?: string | undefined; } ): Promise { return (await buildFixMapAnalysis(input)).report; @@ -47,9 +50,12 @@ export async function buildFixMapAnalysis( languageRegistry?: LanguageRegistry; /** Explicit evidence providers, typically imported bundles; collected without network or code execution. */ evidenceSources?: readonly ReportEvidenceSource[]; + /** Preview: rank against this committed ref, read from Git objects without checkout. */ + atRef?: string | undefined; } ): Promise<{ report: FixMapReport; repo: Awaited>; exclusions: PathExcluder }> { - const scannedRepo = await scanRepo({ ...input, includeHistory: input.includeHistory !== false }); + const historical = input.atRef === undefined ? undefined : await scanHistoricalRepo(input.repoRoot, input.atRef, input); + const scannedRepo = historical?.repo ?? await scanRepo({ ...input, includeHistory: input.includeHistory !== false }); const generatedArtifacts = scannedRepo.files.filter(isFixMapArtifact); const generatedPaths = new Set(generatedArtifacts.map((file) => file.path)); const repo = generatedArtifacts.length === 0 @@ -62,7 +68,10 @@ export async function buildFixMapAnalysis( ? { trackedFiles: scannedRepo.trackedFiles.filter((path) => !generatedPaths.has(path)) } : {}) }; - const requestedExclude = await resolveExclusions(input.repoRoot, input.exclude ?? []); + // A historical plan honors the .fixmapignore committed at that ref, not today's worktree copy. + const requestedExclude = historical + ? excluderFor(input.repoRoot, [...parseIgnoreFile(historical.ignoreFile ?? ""), ...(input.exclude ?? [])]) + : await resolveExclusions(input.repoRoot, input.exclude ?? []); const internalExclude = buildPathExcluder( (input.internalExclude ?? []).map((pattern) => normalizeAbsolutePattern(input.repoRoot, pattern)) ); @@ -172,11 +181,33 @@ function combineExclusions(primary: PathExcluder, internal: PathExcluder): PathE * refinement of that, not a replacement for it. */ export async function resolveExclusions(repoRoot: string, patterns: string[]): Promise { - const combined = [...await readIgnoreFile(repoRoot), ...patterns] - .map((pattern) => normalizeAbsolutePattern(repoRoot, pattern)); + return excluderFor(repoRoot, [...await readIgnoreFile(repoRoot), ...patterns]); +} + +function excluderFor(repoRoot: string, patterns: string[]): PathExcluder { + const combined = patterns.map((pattern) => normalizeAbsolutePattern(repoRoot, pattern)); return combined.length > 0 ? buildPathExcluder(combined) : NO_EXCLUSIONS; } +async function scanHistoricalRepo( + repoRoot: string, + ref: string, + input: Pick +): Promise { + if (input.diffSpec !== undefined || input.baseRef !== undefined || input.headRef !== undefined || input.workingTree || input.includeUntracked) { + throw new Error("A historical plan ranks one committed state, so it cannot be combined with a diff or the working tree."); + } + const historical = await scanRepoAtRef({ repoRoot, ref }); + historical.repo.diagnostics.unshift({ + code: "historical-plan", + severity: "info", + message: + `Preview: ranked against ${markdownCode(historical.requestedRef)} at commit ${markdownCode(historical.commit)}, ` + + "read from committed Git objects without checking out or changing the worktree. Co-change history and uncommitted files were not used." + }); + return historical; +} + /** * A leading slash normally anchors a pattern to the repository root. If a user instead * pastes the repository's full absolute path, strip that known prefix so the intent remains diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index 3ddbd9af..04597d8d 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -61,6 +61,7 @@ export type ScanDiagnostic = { | "remote-pull-fetched" | "remote-repo-fetched" | "remote-checkout-cleanup-failed" + | "historical-plan" | "no-task-terms" | "no-context-match" | "unresolved-identifier" diff --git a/packages/core/src/validate.ts b/packages/core/src/validate.ts index 5277b261..d2821b85 100644 --- a/packages/core/src/validate.ts +++ b/packages/core/src/validate.ts @@ -245,7 +245,10 @@ export function validateFixMapReport(candidate: unknown, label: string): Validat (decision.date !== undefined && (typeof decision.date !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(decision.date))) || (decision.context !== undefined && typeof decision.context !== "string") || (decision.authoredStatus !== undefined && (typeof decision.authoredStatus !== "string" || !decision.authoredStatus.trim() || decision.authoredStatus.length > 500 || decision.authoredStatus.includes("\0"))) || - (decision.consequences !== undefined && typeof decision.consequences !== "string")) return true; + (decision.consequences !== undefined && typeof decision.consequences !== "string") || + (decision.dependencyRules !== undefined && (!Array.isArray(decision.dependencyRules) || + !decision.dependencyRules.every((rule) => isRecord(rule) && typeof rule.from === "string" && rule.from.trim() && + typeof rule.deny === "string" && rule.deny.trim())))) return true; if (decision.source !== undefined && (!isRecord(decision.source) || decision.source.kind !== "pull-request" || decision.source.verification !== "unverified-local-attribution" || !isDecisionPullRequestUrl(decision.source.url))) return true; return decision.targets.some((target) => { diff --git a/packages/core/test/architecture-drift.test.ts b/packages/core/test/architecture-drift.test.ts new file mode 100644 index 00000000..1ef65d9c --- /dev/null +++ b/packages/core/test/architecture-drift.test.ts @@ -0,0 +1,214 @@ +import { execFile } from "node:child_process"; +import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { promisify } from "node:util"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { compareArchitectureRefs } from "../src/architecture-history.js"; +import { parseDecisionRecord } from "../src/decisions.js"; +import { buildFixMapReport } from "../src/plan.js"; + +const exec = promisify(execFile); +const TIMEOUT = process.platform === "win32" ? 60_000 : 30_000; +const ODD = "odd dir/ünï cöde/a/b/c/d/e"; +const roots: string[] = []; +let previousCacheDir: string | undefined; +let cacheDir: string; + +beforeEach(async () => { + previousCacheDir = process.env.FIXMAP_CACHE_DIR; + cacheDir = await mkdtemp(join(tmpdir(), "fixmap-arch-cache-")); + roots.push(cacheDir); + process.env.FIXMAP_CACHE_DIR = cacheDir; +}); + +afterEach(async () => { + if (previousCacheDir === undefined) delete process.env.FIXMAP_CACHE_DIR; + else process.env.FIXMAP_CACHE_DIR = previousCacheDir; + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }))); +}); + +async function put(root: string, path: string, content: string): Promise { + await mkdir(dirname(join(root, path)), { recursive: true }); + await writeFile(join(root, path), content, "utf8"); +} + +async function commit(root: string, message: string): Promise { + await exec("git", ["add", "-A"], { cwd: root }); + await exec("git", ["commit", "--quiet", "-m", message], { cwd: root }); + return (await exec("git", ["rev-parse", "HEAD"], { cwd: root })).stdout.trim(); +} + +function adr(status: string, rule: string, title: string): string { + return `---\nstatus: ${status}\nfixmap-deny-imports:\n - "${rule}"\n---\n# ${title}\n\n## Decision\n\nKeep the layers apart.\n`; +} + +/** Two commits: the second adds a policy violation, a cycle, an ADR disagreement, and odd-path edges. */ +async function driftFixture(): Promise<{ root: string; before: string; after: string }> { + const root = await mkdtemp(join(tmpdir(), "fixmap-drift-")); + roots.push(root); + await exec("git", ["init", "--quiet"], { cwd: root }); + await exec("git", ["config", "user.email", "fixmap@example.test"], { cwd: root }); + await exec("git", ["config", "user.name", "FixMap Test"], { cwd: root }); + await exec("git", ["config", "core.autocrlf", "false"], { cwd: root }); + await put(root, "src/ui/view.ts", "export const view = 1;\n"); + await put(root, "src/db/store.ts", "export const store = 1;\n"); + await put(root, "src/core/a.ts", "import { b } from './b';\nexport const a = b;\n"); + await put(root, "src/core/b.ts", "export const b = 1;\n"); + await put(root, `${ODD}/sibling.ts`, "export const sibling = 1;\n"); + await put(root, `${ODD}/leaf.ts`, "import { sibling } from './sibling';\nexport const leaf = sibling;\n"); + await put(root, ".fixmap/policy.json", JSON.stringify({ + architecturePolicyVersion: 1, + boundaries: [{ id: "ui-no-db", from: ["src/ui/**"], deny: ["src/db/**"], reason: "UI goes through core.", severity: "error" }] + })); + await put(root, "docs/adr/0001-core-independent.md", adr("Accepted", "src/core/** -> src/ui/**", "Core does not depend on UI")); + await put(root, "docs/adr/0002-proposed.md", adr("Proposed", "src/core/** -> src/core/**", "Proposed core isolation")); + const before = await commit(root, "before"); + + await put(root, "src/ui/view.ts", "import { store } from '../db/store';\nexport const view = store;\n"); + await put(root, "src/core/b.ts", "import { a } from './a';\nexport const b = 1;\nexport const again = a;\n"); + await put(root, "src/core/a.ts", "import { b } from './b';\nimport { view } from '../ui/view';\nexport const a = b + view;\n"); + await put(root, `${ODD}/leaf.ts`, "export const leaf = 1;\n"); + await put(root, `${ODD}/new file.ts`, "import { sibling } from './sibling';\nexport const fresh = sibling;\n"); + const after = await commit(root, "after"); + return { root, before, after }; +} + +async function gitState(root: string): Promise<{ head: string; status: string }> { + return { + head: (await exec("git", ["rev-parse", "HEAD"], { cwd: root })).stdout.trim(), + status: (await exec("git", ["status", "--porcelain=v1", "--untracked-files=all"], { cwd: root })).stdout + }; +} + +async function cacheFiles(): Promise { + return (await readdir(cacheDir)).filter((name) => name.startsWith("architecture-")).sort(); +} + +describe("architecture drift over Git refs", () => { + it("reports edges, cycles, policy violations, coupling, and ADR disagreements with exact commits", async () => { + const { root, before, after } = await driftFixture(); + const state = await gitState(root); + + const result = await compareArchitectureRefs({ repoRoot: root, fromRef: before, toRef: "HEAD", couplingDelta: 1 }); + + expect(result.from.commit).toBe(before); + expect(result.to.commit).toBe(after); + expect(result.to.requestedRef).toBe("HEAD"); + expect(result.drift.addedEdges).toEqual(expect.arrayContaining([ + { from: "src/ui/view.ts", to: "src/db/store.ts" }, + { from: "src/core/b.ts", to: "src/core/a.ts" }, + { from: "src/core/a.ts", to: "src/ui/view.ts" }, + { from: `${ODD}/new file.ts`, to: `${ODD}/sibling.ts` } + ])); + expect(result.drift.removedEdges).toEqual([{ from: `${ODD}/leaf.ts`, to: `${ODD}/sibling.ts` }]); + expect(result.drift.newCycles).toEqual([["src/core/a.ts", "src/core/b.ts"]]); + expect(result.drift.newBoundaryViolations).toEqual([{ ruleId: "ui-no-db", from: "src/ui/view.ts", to: "src/db/store.ts" }]); + expect(result.drift.couplingGrowth.map((entry) => entry.path)).toEqual(expect.arrayContaining(["src/core/a.ts", "src/ui/view.ts"])); + expect(result.decisionDisagreements).toEqual([{ + decisionId: expect.stringMatching(/^decision:[a-f0-9]{16}$/), + decisionPath: "docs/adr/0001-core-independent.md", + decisionTitle: "Core does not depend on UI", + rule: { from: "src/core/**", deny: "src/ui/**" }, + edge: { from: "src/core/a.ts", to: "src/ui/view.ts" }, + introduced: true + }]); + // The proposed record's rule is violated by a.ts <-> b.ts, but it states no accepted intent. + expect(result.to.decisionRules.map((rule) => rule.decisionPath)).toEqual(["docs/adr/0001-core-independent.md"]); + expect(await gitState(root)).toEqual(state); + }, TIMEOUT); + + it("reuses per-commit cache entries and rebuilds corrupt ones", async () => { + const { root, before, after } = await driftFixture(); + const state = await gitState(root); + const first = await compareArchitectureRefs({ repoRoot: root, fromRef: before, toRef: after }); + const files = await cacheFiles(); + expect(files).toEqual([`architecture-v1-${after}-policy.json`, `architecture-v1-${before}-policy.json`].sort()); + + // A well-formed entry with a marker fingerprint proves the second run read the cache. + const afterPath = join(cacheDir, `architecture-v1-${after}-policy.json`); + const record = JSON.parse(await readFile(afterPath, "utf8")); + record.entry.snapshot.fingerprint = "architecture:cachedmarker"; + const { createHash } = await import("node:crypto"); + record.checksum = createHash("sha256").update(JSON.stringify(record.entry)).digest("hex"); + await writeFile(afterPath, JSON.stringify(record), "utf8"); + const hit = await compareArchitectureRefs({ repoRoot: root, fromRef: before, toRef: after }); + expect(hit.to.snapshot.fingerprint).toBe("architecture:cachedmarker"); + expect(hit.decisionDisagreements).toEqual(first.decisionDisagreements); + + // Edited content without a matching checksum, and plain garbage, are both ignored and rebuilt. + record.entry.snapshot.edges = []; + await writeFile(afterPath, JSON.stringify(record), "utf8"); + expect((await compareArchitectureRefs({ repoRoot: root, fromRef: before, toRef: after })).to.snapshot).toEqual(first.to.snapshot); + await writeFile(afterPath, "{not json", "utf8"); + const rebuilt = await compareArchitectureRefs({ repoRoot: root, fromRef: before, toRef: after }); + expect(rebuilt.to.snapshot).toEqual(first.to.snapshot); + expect(JSON.parse(await readFile(afterPath, "utf8")).entry.snapshot.fingerprint).toBe(first.to.snapshot.fingerprint); + expect(await gitState(root)).toEqual(state); + }, TIMEOUT); + + it("skips the cache when disabled or when the cache directory is inside the repository", async () => { + const { root, before, after } = await driftFixture(); + await compareArchitectureRefs({ repoRoot: root, fromRef: before, toRef: after, useCache: false }); + expect(await cacheFiles()).toEqual([]); + + process.env.FIXMAP_CACHE_DIR = join(root, ".cache"); + await compareArchitectureRefs({ repoRoot: root, fromRef: before, toRef: after }); + await expect(readdir(join(root, ".cache"))).rejects.toThrow(); + expect((await gitState(root)).status).toBe(""); + }, TIMEOUT); + + it("fails clearly on unknown refs without touching the worktree", async () => { + const { root, before } = await driftFixture(); + const state = await gitState(root); + await expect(compareArchitectureRefs({ repoRoot: root, fromRef: before, toRef: "no-such-ref" })).rejects.toThrow("Could not resolve Git ref"); + expect(await gitState(root)).toEqual(state); + }, TIMEOUT); +}); + +describe("historical plans", () => { + it("ranks against a committed ref without reading the worktree or moving HEAD", async () => { + const { root, before } = await driftFixture(); + await put(root, "src/core/untracked.ts", "export const untracked = 'view store';\n"); + const state = await gitState(root); + + const report = await buildFixMapReport({ repoRoot: root, issueText: "new file sibling fresh", atRef: before, limit: 20 }); + + const paths = report.contextFiles.map((file) => file.path); + expect(paths).not.toContain(`${ODD}/new file.ts`); + expect(paths).not.toContain("src/core/untracked.ts"); + expect(paths).toContain(`${ODD}/sibling.ts`); + expect(report.diagnostics.find((entry) => entry.code === "historical-plan")?.message).toContain(before); + expect(await gitState(root)).toEqual(state); + }, TIMEOUT); + + it("rejects diff or working-tree options and unknown refs", async () => { + const { root } = await driftFixture(); + await expect(buildFixMapReport({ repoRoot: root, issueText: "x", atRef: "HEAD", workingTree: true })).rejects.toThrow("cannot be combined"); + await expect(buildFixMapReport({ repoRoot: root, issueText: "x", atRef: "missing-ref" })).rejects.toThrow("Could not resolve Git ref"); + }, TIMEOUT); +}); + +describe("decision dependency rules", () => { + it("parses explicit fixmap-deny-imports rules and rejects malformed ones", () => { + const parsed = parseDecisionRecord({ + path: "docs/adr/0001.md", + fingerprint: "git:0000000000000000000000000000000000000000", + content: adr("Accepted", "src\\core/** -> src/ui/**", "Rule") + }); + expect(parsed.record?.dependencyRules).toEqual([{ from: "src/core/**", deny: "src/ui/**" }]); + for (const bad of ["src/core/**", "../outside/** -> src/**", "src/** -> /abs/**", "!src/** -> src/ui/**"]) { + expect(() => parseDecisionRecord({ + path: "docs/adr/0002.md", + fingerprint: "git:0000000000000000000000000000000000000000", + content: adr("Accepted", bad, "Bad") + })).toThrow(); + } + const prose = parseDecisionRecord({ + path: "docs/adr/0003.md", + fingerprint: "git:0000000000000000000000000000000000000000", + content: "# Prose\n\n## Decision\n\nsrc/core must never import src/ui -> src/core.\n" + }); + expect(prose.record?.dependencyRules).toBeUndefined(); + }); +}); From f4c57913ccbc8eb509d43664653b42abefc6b578 Mon Sep 17 00:00:00 2001 From: Aryam Goyal Date: Sun, 22 Nov 2026 20:06:36 +0530 Subject: [PATCH 2/9] feat: reviewer suggestions on the CLI and MCP (preview) Add `fixmap reviewers (--report plan.json | --diff | --working-tree)` and the read-only MCP tool `fixmap_reviewers`. Both print suggested reviewers per changed path with the reason and source line, from the highest-precedence CODEOWNERS file (last matching rule wins), active annotation owners, architecture-policy reviewers, and bounded commit authors. - `--no-history-authors` / `noHistoryAuthors` drops commit-author suggestions and skips reading history. - Commit authors are read with git's `%aN`, which applies `.mailmap`; a real-repository test now proves aliases are merged before counting. - Output strips `@` from handles so nothing notifies anyone; e-mail addresses stay. Core exports `renderReviewRoutingMarkdown`, `reviewRoutingWithoutMentions` and `withoutMentions` for Action parity. - Evidence now records `changedPath`; shallow and truncated history are diagnosed. - Feature catalog entry `Reviewer suggestions` with `preview: true`. Co-Authored-By: Claude Opus 5.5 --- README.md | 19 ++- packages/cli/README.md | 2 + packages/cli/src/cli-runner.ts | 11 ++ packages/cli/src/mcp.ts | 52 ++++++- packages/cli/src/reviewers-command.ts | 164 ++++++++++++++++++++ packages/cli/test/cli-runner.test.ts | 4 +- packages/cli/test/mcp.test.ts | 31 +++- packages/cli/test/reviewers-command.test.ts | 150 ++++++++++++++++++ packages/core/src/browser.ts | 4 +- packages/core/src/feature-catalog.ts | 3 +- packages/core/src/index.ts | 4 +- packages/core/src/ownership.ts | 103 +++++++++++- packages/core/test/ownership.test.ts | 34 +++- 13 files changed, 562 insertions(+), 19 deletions(-) create mode 100644 packages/cli/src/reviewers-command.ts create mode 100644 packages/cli/test/reviewers-command.test.ts diff --git a/README.md b/README.md index e82439a5..9c3f8305 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/cli/README.md b/packages/cli/README.md index e2047251..027fc157 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 66feda9a..b86c0cf9 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 70326eb1..918f8d45 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 00000000..6eda141a --- /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 7920fb22..450dfcec 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 8c444a51..89c8465e 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 00000000..9f1af237 --- /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 d524cae4..460bbaec 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 afdea7f1..f56c3881 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 a7cd0cd8..68c58a52 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 f2c6113f..2ced1539 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 d00db6c3..1c6edad1 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"); + }); }); From 26da08a35446ce8c017a44fed70c468b3b599c91 Mon Sep 17 00:00:00 2001 From: Aryam Goyal Date: Sun, 22 Nov 2026 20:06:17 +0530 Subject: [PATCH 3/9] feat: save outcomes and change dossiers locally (preview) Core: record-store.ts persists outcome records under .fixmap/outcomes/ and change dossiers under .fixmap/dossiers/, one validated JSON file per record. Writes use temp file + rename; links, junctions, hardlinks and traversal ids are refused; a bounded lock is never taken over; malformed files are reported as problems instead of failing a listing. CLI (preview): fixmap outcome record|list|show|remove|calibrate|prune and fixmap dossier create|list|show|remove, with --redact (free text stored as SHA-256). Calibration stays report-only (automaticWeightChanges: false). MCP (preview, read-only): fixmap_outcomes and fixmap_dossier. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + docs/outcomes-and-dossiers.md | 81 +++++ packages/cli/src/cli-runner.ts | 9 + packages/cli/src/mcp.ts | 5 +- packages/cli/src/outcome-command.ts | 411 ++++++++++++++++++++++ packages/cli/src/record-tools.ts | 71 ++++ packages/cli/test/cli-runner.test.ts | 2 +- packages/cli/test/mcp.test.ts | 6 +- packages/cli/test/outcome-command.test.ts | 276 +++++++++++++++ packages/core/src/feature-catalog.ts | 4 +- packages/core/src/index.ts | 5 + packages/core/src/record-store.ts | 276 +++++++++++++++ packages/core/test/record-store.test.ts | 188 ++++++++++ 13 files changed, 1329 insertions(+), 6 deletions(-) create mode 100644 docs/outcomes-and-dossiers.md create mode 100644 packages/cli/src/outcome-command.ts create mode 100644 packages/cli/src/record-tools.ts create mode 100644 packages/cli/test/outcome-command.test.ts create mode 100644 packages/core/src/record-store.ts create mode 100644 packages/core/test/record-store.test.ts diff --git a/README.md b/README.md index e82439a5..83626618 100644 --- a/README.md +++ b/README.md @@ -376,6 +376,7 @@ Architecture rules live in a reviewed `.fixmap/policy.json` file. Every rule has - Its public API also exposes Explain, Compare, and Verify builders and result types, so another tool can compose the same workflow without shelling out to the CLI. - `fixmap annotate` writes a versioned `.fixmap/annotations.json` with stable content identities, file/symbol/service/contract scopes, optional owner and expiry, and rename/missing-target checks. Relevant notes retain the store fingerprint in Markdown, JSON, and compact agent reports. See the [candidate annotation guide](docs/annotations.md) for workflows, ownership boundaries, and interrupted-lock recovery. - The candidate MCP tool `fixmap_annotate` shares that store and its locking/validation. It requires an explicit `action`: `add` accepts `target`/`symbol` or `service`/`contract`, `note`, optional `owner`/`expires`, and local `repo`; `list` accepts `repo` and `format`; `remove` requires the exact annotation `id` and optional `repo`. Only add/remove writes files. The tool advertises mutation/destructive hints; those hints are not authorization, and agents must obtain the user's request before changing notes. Invalid or action-inapplicable fields fail before mutation. This candidate tool is not a claim that the published npm release already supports it. +- Preview: `fixmap outcome record|list|show|remove|calibrate|prune` and `fixmap dossier create|list|show|remove` save predicted-versus-edited outcomes and fingerprinted change dossiers under `.fixmap/outcomes/` and `.fixmap/dossiers/` with atomic writes, link refusal, `--redact` (free text stored as SHA-256), and age-based pruning. Calibration is report-only (`automaticWeightChanges: false`). The read-only MCP tools `fixmap_outcomes` and `fixmap_dossier` list and show them. See [outcomes and change dossiers](docs/outcomes-and-dossiers.md). - `.fixmap/policy.json` defines bounded, repository-owned dependency boundaries, required test changes, reviewer routing, and breaking-contract rules. Plan and Verify use the same evaluator and retain the exact policy fingerprint; Core can also compare deterministic architecture snapshots for new edges, cyclic components, boundary violations, and coupling growth. - Historical Core APIs resolve refs to immutable commits and compare exact Git-blob architecture snapshots without checking out a branch, moving `HEAD`, or writing into the worktree. - The opt-in local sensitive-data evidence provider emits provenance-marked credential/token/PII/payment indicators and structural proximity to logging/network/storage/analytics sinks. It never copies detected values or snippets and explicitly labels every result as low-confidence, incomplete evidence rather than a taint or security proof. diff --git a/docs/outcomes-and-dossiers.md b/docs/outcomes-and-dossiers.md new file mode 100644 index 00000000..5be24e2a --- /dev/null +++ b/docs/outcomes-and-dossiers.md @@ -0,0 +1,81 @@ +# Outcomes and change dossiers (preview) + +Preview: these commands may change before v0.10.0. + +FixMap can save two kinds of local record after a change is done. Both live inside the +repository, one JSON file per record, and nothing leaves the machine. + +| Record | Directory | Command | MCP (read-only) | +| --- | --- | --- | --- | +| Outcome | `.fixmap/outcomes/` | `fixmap outcome record\|list\|show\|remove\|calibrate\|prune` | `fixmap_outcomes` (list, show, calibrate) | +| Change dossier | `.fixmap/dossiers/` | `fixmap dossier create\|list\|show\|remove` | `fixmap_dossier` (list, show) | + +## Outcomes + +An outcome record keeps what a saved plan predicted (`contextFiles`) next to the paths that were +actually edited, the commands that ran, and who judged the task. + +```sh +fixmap plan --issue "Fix login redirect" --format json --output plan.json +# ... make the change ... +fixmap outcome record --report plan.json --working-tree \ + --command-result test-result.json --assessment agent --status succeeded +fixmap outcome calibrate +``` + +- `--diff ` or `--working-tree [--include-untracked]` is required: it is where the edited paths come from. +- `--command-result ` (repeatable) takes one object or an array. Each entry is either a + `fixmap sandbox` result or `{ "command", "status", "evidence"?, "relatedPaths"? }` with status + `passed`, `failed`, `timeout`, `crashed`, or `unavailable`. +- `--assessment human|agent|external|unassessed` and `--status succeeded|failed|partial|unknown` + record who judged the task. A passing command is never treated as task success. + +`fixmap outcome calibrate` reports precision (predicted paths that were edited), recall (edited +paths that were predicted), misses, false positives, and command and assessment counts across every +stored record. It is a report. Ranking weights never change automatically, and the output always +says `automaticWeightChanges: false`. + +## Change dossiers + +```sh +fixmap dossier create --report plan.json --task "Fix login redirect" \ + --diff main...HEAD --pr https://github.com/owner/repo/pull/12 --commit +``` + +A dossier links the request text and its SHA-256, the report and Impact Graph fingerprints, the +report's ADR references, the diff's changed paths, command results, and commit/PR identifiers. +The record carries a content fingerprint; a hand-edited file fails validation and is reported. + +## Privacy: `--redact` + +`--redact` stores `sha256:` in place of free text: + +- `outcome record`: the assessment reason and each command's evidence. +- `dossier create`: the task text (`request.summary`). + +Paths, commands, and fingerprints are kept, since calibration needs them. Outcome records never +store task text; the task id defaults to `plan-` unless you +pass `--task-id`. + +## Retention: `prune` + +```sh +fixmap outcome prune --older-than 90 +``` + +deletes outcome records recorded more than 90 days ago. Malformed files are listed, never deleted. +`fixmap outcome remove ` and `fixmap dossier remove ` delete a single record. + +## Safety and recovery + +- Writes go to a temp file and are renamed into place, so a reader never sees half a record. +- `.fixmap`, `.fixmap/outcomes`, and `.fixmap/dossiers` must be real directories: links and + junctions are refused. Record files and locks must be regular files with one link. +- Record ids are letters, digits, `.`, `_`, and `-` only, so an id cannot name a path outside the store. +- Writers take `.fixmap/outcomes.lock` or `.fixmap/dossiers.lock`. A second writer waits about a + second, then stops. FixMap never takes over a lock, however old: if a writer was interrupted, + confirm no FixMap process is running, then delete the lock file by hand. +- `list` and `calibrate` report unreadable or invalid files under "Unreadable stored files" (or + `problems` in JSON) and keep going. +- Decide whether to commit these directories. They are plain JSON and reviewable; add them to + `.gitignore` if they should stay on one machine. diff --git a/packages/cli/src/cli-runner.ts b/packages/cli/src/cli-runner.ts index 66feda9a..de31e410 100644 --- a/packages/cli/src/cli-runner.ts +++ b/packages/cli/src/cli-runner.ts @@ -118,6 +118,8 @@ Usage: fixmap sandbox --request sandbox.json --execute-declared-command fixmap watch --report plan.json --repo . fixmap annotate src/auth/token.ts --note "Do not refactor; external contract" + fixmap outcome record --report plan.json --working-tree --assessment agent --status succeeded + fixmap dossier create --report plan.json --task "Fix login" --diff main...HEAD --pr fixmap features fixmap setup [--agent claude|cursor|copilot|agents|all] [--repo ] fixmap mcp [--repo ] @@ -143,6 +145,8 @@ Commands: runtime Preview: Map redaction-reviewed runtime evidence to exact files sandbox Preview: Run one explicitly consented command in an isolated container watch Recheck working-tree drift and impact whenever edits change + outcome Preview: Save predicted-versus-edited outcomes locally and calibrate them + dossier Preview: Save a fingerprinted change dossier for a finished change annotate Attach reviewable tribal knowledge to files, symbols, services, or contracts features List every FixMap capability and its command setup Preview workflows, or explicitly install /fixmap for coding agents @@ -238,6 +242,11 @@ export async function runCli(args: string[], dependencies: CliDependencies = {}) return 0; } + if (args[0] === "outcome" || args[0] === "dossier") { + const module = await import("./outcome-command.js"); + return (args[0] === "outcome" ? module.runOutcomeCommand : module.runDossierCommand)(args.slice(1), { stdout, stderr }); + } + if (args[0] === "annotate") { const module = await import("./annotation-command.js"); return module.runAnnotateCommand(args.slice(1), { stdout, stderr }); diff --git a/packages/cli/src/mcp.ts b/packages/cli/src/mcp.ts index 70326eb1..de5f53f5 100644 --- a/packages/cli/src/mcp.ts +++ b/packages/cli/src/mcp.ts @@ -1,5 +1,6 @@ import { readFileSync } from "node:fs"; import { ANNOTATION_TOOL, runAnnotationTool } from "./annotation-tool.js"; +import { DOSSIER_TOOL, OUTCOMES_TOOL, runDossierTool, runOutcomesTool } from "./record-tools.js"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { Server } from "@modelcontextprotocol/sdk/server/index.js"; @@ -516,11 +517,13 @@ 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, 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, OUTCOMES_TOOL, DOSSIER_TOOL] })); server.setRequestHandler(CallToolRequestSchema, async (request) => { if (request.params.name === ANNOTATION_TOOL.name) return runAnnotationTool(request.params.arguments, defaultRepo); + if (request.params.name === OUTCOMES_TOOL.name) return runOutcomesTool(request.params.arguments, defaultRepo); + if (request.params.name === DOSSIER_TOOL.name) return runDossierTool(request.params.arguments, defaultRepo); if (request.params.name === CONTEXT_TOOL.name || request.params.name === GRAPH_TOOL.name) { const kind = request.params.name === CONTEXT_TOOL.name ? "context" : "graph"; const parsed = parseAnalysisToolArguments(request.params.arguments ?? {}, kind); diff --git a/packages/cli/src/outcome-command.ts b/packages/cli/src/outcome-command.ts new file mode 100644 index 00000000..e04c2b77 --- /dev/null +++ b/packages/cli/src/outcome-command.ts @@ -0,0 +1,411 @@ +import { createHash, randomBytes } from "node:crypto"; +import { realpath } from "node:fs/promises"; +import { basename, isAbsolute, relative, resolve } from "node:path"; +import { + buildChangeDossier, + createGraphIdentity, + createOutcomeRecord, + deleteStoredDossier, + deleteStoredOutcome, + pruneStoredOutcomes, + readStoredDossier, + readStoredDossiers, + readStoredOutcome, + readStoredOutcomes, + saveStoredDossier, + saveStoredOutcome, + scanRepo, + summarizeOutcomeCalibration, + validateFixMapReport, + type ChangeDossier, + type ChangeDossierInput, + type FixMapReport, + type OutcomeCalibration, + type OutcomeRecord, + type StoredRecordProblem, + type TestOutcomeStatus +} from "@aryam/fixmap-core"; +import { describeInputReadError, readDecodedTextFile } from "./decode-input.js"; + +export const OUTCOME_USAGE = `Usage: + fixmap outcome record --report (--diff | --working-tree [--include-untracked]) + [--command-result ...] [--assessment human|agent|external|unassessed] + [--status succeeded|failed|partial|unknown] [--reason ] [--task-id ] [--redact] + fixmap outcome list [--format markdown|json] + fixmap outcome show [--format markdown|json] + fixmap outcome remove + fixmap outcome calibrate [--format markdown|json] + fixmap outcome prune --older-than + +Saves what a plan predicted next to what was actually edited, one file per record under +.fixmap/outcomes/. Calibration is a visible report only: it never changes ranking weights. +--redact stores the SHA-256 of the assessment reason and command evidence instead of their text. +Every command also accepts --repo (default current directory). +`; + +export const DOSSIER_USAGE = `Usage: + fixmap dossier create --report --task [--diff | --working-tree [--include-untracked]] + [--command-result ...] [--pr ] [--commit ] [--redact] + fixmap dossier list [--format markdown|json] + fixmap dossier show [--format markdown|json] + fixmap dossier remove + +Saves a fingerprinted change dossier (request, plan and graph references, ADRs, diff, command +results, commit/PR identifiers) under .fixmap/dossiers/. --redact stores the task text as its SHA-256. +Every command also accepts --repo (default current directory). +`; + +/** --command-result accepts one object or an array: a FixMap sandbox result, or {command, status, evidence?, relatedPaths?}. */ +type CommandResult = { command: string; status: TestOutcomeStatus; evidence: string; relatedPaths: string[] }; + +export type RecordCommandIo = { + stdout: (text: string) => void; + stderr: (text: string) => void; + now?: () => Date; + /** Test seam: resolve changed paths without scanning. */ + changedFiles?: (repoRoot: string, change: ChangeSource) => Promise; +}; + +type ChangeSource = { diffSpec?: string; workingTree?: boolean; includeUntracked?: boolean }; +type Parsed = { action: string; positional: string[]; values: Map; flags: Set }; + +const VALUE_FLAGS = new Set(["--repo", "--report", "--diff", "--command-result", "--assessment", "--status", "--reason", + "--task-id", "--task", "--pr", "--commit", "--format", "--older-than"]); +const BOOLEAN_FLAGS = new Set(["--working-tree", "--include-untracked", "--redact"]); +const REPEATABLE = new Set(["--command-result"]); +const ACTION_OPTIONS: Record = { + "outcome record": ["--repo", "--report", "--diff", "--working-tree", "--include-untracked", "--command-result", "--assessment", "--status", "--reason", "--task-id", "--redact"], + "outcome list": ["--repo", "--format"], + "outcome show": ["--repo", "--format"], + "outcome remove": ["--repo"], + "outcome calibrate": ["--repo", "--format"], + "outcome prune": ["--repo", "--older-than"], + "dossier create": ["--repo", "--report", "--task", "--diff", "--working-tree", "--include-untracked", "--command-result", "--pr", "--commit", "--redact"], + "dossier list": ["--repo", "--format"], + "dossier show": ["--repo", "--format"], + "dossier remove": ["--repo"] +}; +const ASSESSMENT_SOURCE = { human: "human", agent: "agent", external: "external-system", unassessed: "unassessed" } as const; +const STATUSES = ["passed", "failed", "timeout", "crashed", "unavailable"] as const; + +export function runOutcomeCommand(args: string[], io: RecordCommandIo): Promise { return run("outcome", OUTCOME_USAGE, args, io); } +export function runDossierCommand(args: string[], io: RecordCommandIo): Promise { return run("dossier", DOSSIER_USAGE, args, io); } + +async function run(group: "outcome" | "dossier", usage: string, args: string[], io: RecordCommandIo): Promise { + if (args.length === 0 || args[0] === "--help" || args[0] === "-h" || args.includes("--help") || args.includes("-h")) { + io.stdout(usage); + return args.length === 0 ? 1 : 0; + } + const fail = (message: string) => { io.stderr(`${message}\n\n${usage}`); return 1; }; + const parsed = parseArgs(args); + if (typeof parsed === "string") return fail(parsed); + const allowed = ACTION_OPTIONS[`${group} ${parsed.action}`]; + if (!allowed) return fail(`Unknown ${group} action: ${parsed.action}`); + for (const flag of [...parsed.values.keys(), ...parsed.flags]) { + if (!allowed.includes(flag)) return fail(`${flag} does not apply to ${group} ${parsed.action}.`); + } + const takesId = parsed.action === "show" || parsed.action === "remove"; + if (takesId ? parsed.positional.length !== 1 : parsed.positional.length > 0) { + return fail(takesId ? `${group} ${parsed.action} needs exactly one record id.` : `Unexpected argument: ${parsed.positional[0]}`); + } + const format = one(parsed, "--format") ?? "markdown"; + if (format !== "markdown" && format !== "json") return fail("--format must be markdown or json."); + try { + const repoRoot = await realpath(resolve(one(parsed, "--repo") ?? process.cwd())); + const id = parsed.positional[0]!; + if (group === "outcome") { + switch (parsed.action) { + case "record": return await recordOutcome(repoRoot, parsed, io, fail); + case "list": return print(io, format, await readStoredOutcomes(repoRoot), renderOutcomeList); + case "show": return show(io, format, await readStoredOutcome(repoRoot, id), renderOutcome); + case "remove": await deleteStoredOutcome(repoRoot, id); io.stdout(`Removed .fixmap/outcomes/${id}.json.\n`); return 0; + case "calibrate": return calibrate(io, format, await readStoredOutcomes(repoRoot)); + default: return await prune(repoRoot, parsed, io, fail); + } + } + switch (parsed.action) { + case "create": return await createDossier(repoRoot, parsed, io, fail); + case "list": return print(io, format, await readStoredDossiers(repoRoot), renderDossierList); + case "show": return show(io, format, await readStoredDossier(repoRoot, id), renderDossier); + default: await deleteStoredDossier(repoRoot, id); io.stdout(`Removed .fixmap/dossiers/${id}.json.\n`); return 0; + } + } catch (error) { + io.stderr(`${error instanceof Error ? error.message : String(error)}\n`); + return 1; + } +} + +async function recordOutcome(repoRoot: string, parsed: Parsed, io: RecordCommandIo, fail: (message: string) => number): Promise { + const assessmentName = one(parsed, "--assessment") ?? "unassessed"; + if (!(assessmentName in ASSESSMENT_SOURCE)) return fail("--assessment must be human, agent, external, or unassessed."); + const source = ASSESSMENT_SOURCE[assessmentName as keyof typeof ASSESSMENT_SOURCE]; + const status = one(parsed, "--status") ?? (source === "unassessed" ? "unknown" : undefined); + if (!status) return fail("--status succeeded|failed|partial|unknown is required with an assessment source."); + if (!["succeeded", "failed", "partial", "unknown"].includes(status)) return fail("--status must be succeeded, failed, partial, or unknown."); + if (source === "unassessed" && status !== "unknown") return fail("An unassessed outcome can only have --status unknown."); + const change = changeSource(parsed, true); + if (typeof change === "string") return fail(change); + const plan = loadReport(one(parsed, "--report")); + if (typeof plan === "string") return fail(plan); + const redact = parsed.flags.has("--redact"); + const commands = loadCommandResults(parsed.values.get("--command-result") ?? []); + const now = io.now?.() ?? new Date(); + const reason = one(parsed, "--reason") ?? (source === "unassessed" ? "Not assessed." : `Assessed by ${assessmentName}.`); + const record = createOutcomeRecord({ + id: newId("outcome", now), + taskId: one(parsed, "--task-id") ?? `plan-${plan.hash.slice(0, 16)}`, + repositoryIdentity: repositoryIdentity(repoRoot), + planFingerprint: `sha256:${plan.hash}`, + recordedAt: now.toISOString(), + predictedPaths: plan.report.contextFiles.map((file) => file.path), + editedPaths: await resolveChangedFiles(repoRoot, change!, io), + testOutcomes: commands.map((entry) => ({ + command: entry.command, + status: entry.status, + relatedPaths: entry.relatedPaths, + evidence: redact ? sha256Text(entry.evidence) : entry.evidence + })), + taskAssessment: { status: status as OutcomeRecord["taskAssessment"]["status"], source, reason: redact ? sha256Text(reason) : reason } + }); + await saveStoredOutcome(repoRoot, record); + const calibration = summarizeOutcomeCalibration({ outcomeStoreVersion: 1, records: [record] }).perRecord[0]!; + io.stdout(`Saved .fixmap/outcomes/${record.id}.json: ${calibration.correctlyPredicted.length} of ${record.editedPaths.length} edited ` + + `path(s) were predicted; ${calibration.predictedButUnedited.length} predicted path(s) were not edited.${redact ? " Free text was redacted to SHA-256." : ""}\n`); + return 0; +} + +async function createDossier(repoRoot: string, parsed: Parsed, io: RecordCommandIo, fail: (message: string) => number): Promise { + const task = one(parsed, "--task"); + if (!task) return fail("dossier create requires --task describing the request."); + const change = changeSource(parsed, false); + if (typeof change === "string") return fail(change); + const reportPath = one(parsed, "--report"); + const plan = loadReport(reportPath); + if (typeof plan === "string") return fail(plan); + const redact = parsed.flags.has("--redact"); + const commands = loadCommandResults(parsed.values.get("--command-result") ?? []); + const now = (io.now?.() ?? new Date()).toISOString(); + const commit = one(parsed, "--commit"); + const pullRequest = one(parsed, "--pr"); + let diff: ChangeDossierInput["diff"] = null; + if (change) { + const changedFiles = await resolveChangedFiles(repoRoot, change, io); + diff = { + sourceFingerprint: `sha256:${sha256(JSON.stringify({ change, changedFiles }))}`, + changedFiles, + ...(change.diffSpec ? { base: change.diffSpec } : { base: "HEAD", head: "working-tree" }) + }; + } + const artifact = relative(repoRoot, resolve(reportPath!)).replace(/\\/g, "/"); + const dossier = buildChangeDossier({ + id: newId("dossier", new Date(now)), + repositoryIdentity: repositoryIdentity(repoRoot), + createdAt: now, + updatedAt: now, + request: { summary: redact ? sha256Text(task) : task, sourceFingerprint: `sha256:${sha256(task)}` }, + assumptions: [], + plan: { + reportFingerprint: `sha256:${plan.hash}`, + graphFingerprint: `sha256:${sha256(JSON.stringify(plan.report.impact ?? null))}`, + ...(artifact && !artifact.startsWith("..") && !isAbsolute(artifact) ? { artifactPath: artifact } : {}) + }, + decisions: (plan.report.decisions ?? []).map((decision) => ({ id: decision.id, path: decision.path, sourceFingerprint: decision.sourceFingerprint })), + diff, + tests: commands.map((entry) => ({ command: entry.command, status: entry.status, evidenceFingerprint: `sha256:${sha256(entry.evidence)}`, relatedPaths: entry.relatedPaths })), + runtimeEvidence: [], + reviews: [], + releaseIdentifiers: { + ...(commit ? { commit } : {}), + ...(pullRequest ? { pullRequest } : {}) + } + }); + await saveStoredDossier(repoRoot, dossier); + io.stdout(`Saved .fixmap/dossiers/${dossier.id}.json (${dossier.fingerprint}).${redact ? " Task text was redacted to SHA-256." : ""}\n`); + return 0; +} + +async function prune(repoRoot: string, parsed: Parsed, io: RecordCommandIo, fail: (message: string) => number): Promise { + const raw = one(parsed, "--older-than"); + if (!raw || !/^\d{1,5}$/.test(raw)) return fail("outcome prune requires --older-than (a whole number of days, 0-99999)."); + const cutoff = new Date((io.now?.() ?? new Date()).getTime() - Number(raw) * 86_400_000); + const result = await pruneStoredOutcomes(repoRoot, cutoff); + io.stdout(`Removed ${result.removed.length} outcome record(s) recorded before ${cutoff.toISOString()}; kept ${result.kept}.\n` + + result.removed.map((id) => `- ${id}\n`).join("") + renderProblems(result.problems)); + return 0; +} + +function calibrate(io: RecordCommandIo, format: string, stored: { records: OutcomeRecord[]; problems: StoredRecordProblem[] }): number { + const calibration = summarizeOutcomeCalibration({ outcomeStoreVersion: 1, records: stored.records }); + if (format === "json") io.stdout(`${JSON.stringify({ ...calibration, problems: stored.problems }, null, 2)}\n`); + else io.stdout(renderCalibration(calibration) + renderProblems(stored.problems)); + return 0; +} + +function print(io: RecordCommandIo, format: string, stored: { records: T[]; problems: StoredRecordProblem[] }, render: (records: T[]) => string): number { + io.stdout(format === "json" ? `${JSON.stringify(stored, null, 2)}\n` : render(stored.records) + renderProblems(stored.problems)); + return 0; +} + +function show(io: RecordCommandIo, format: string, record: T, render: (record: T) => string): number { + io.stdout(format === "json" ? `${JSON.stringify(record, null, 2)}\n` : render(record)); + return 0; +} + +function parseArgs(args: string[]): Parsed | string { + const [action, ...rest] = args; + if (!action || action.startsWith("-")) return "Name an action first."; + const values = new Map(); + const flags = new Set(); + const positional: string[] = []; + for (let index = 0; index < rest.length; index += 1) { + const raw = rest[index]!; + if (!raw.startsWith("--")) { positional.push(raw); continue; } + const separator = raw.indexOf("="); + const flag = separator === -1 ? raw : raw.slice(0, separator); + if (BOOLEAN_FLAGS.has(flag)) { + if (separator !== -1) return `${flag} does not take a value.`; + if (flags.has(flag)) return `Pass ${flag} only once.`; + flags.add(flag); + continue; + } + if (!VALUE_FLAGS.has(flag)) return `Unknown option: ${raw}`; + if (values.has(flag) && !REPEATABLE.has(flag)) return `Pass ${flag} only once.`; + const inline = separator === -1 ? undefined : raw.slice(separator + 1); + const following = rest[index + 1]; + const value = inline ?? (following !== undefined && !following.startsWith("--") ? following : undefined); + if (inline === undefined && value !== undefined) index += 1; + if (!value?.trim()) return `${flag} requires a non-blank value.`; + values.set(flag, [...(values.get(flag) ?? []), value.trim()]); + } + return { action, positional, values, flags }; +} + +function changeSource(parsed: Parsed, required: boolean): ChangeSource | undefined | string { + const diffSpec = one(parsed, "--diff"); + const workingTree = parsed.flags.has("--working-tree"); + if (diffSpec && workingTree) return "Use either --diff or --working-tree, not both."; + if (parsed.flags.has("--include-untracked") && !workingTree) return "--include-untracked only applies with --working-tree."; + if (!diffSpec && !workingTree) return required ? "Provide --diff or --working-tree so FixMap can see what was actually edited." : undefined; + return diffSpec ? { diffSpec } : { workingTree: true, includeUntracked: parsed.flags.has("--include-untracked") }; +} + +function loadReport(path: string | undefined): { report: FixMapReport; hash: string } | string { + if (!path) return "Provide --report with the JSON report the change was planned from."; + let text: string; + try { + text = readDecodedTextFile(path); + } catch (error) { + return `Could not read "${path}": ${describeInputReadError(path, error)}`; + } + let candidate: unknown; + try { + candidate = JSON.parse(text); + } catch { + return `"${path}" is not a JSON FixMap report. Save one with: fixmap plan --issue "..." --format json --output plan.json`; + } + const loaded = validateFixMapReport(candidate, `"${path}"`); + if (!loaded.success) return loaded.message; + return { report: loaded.report, hash: sha256(text) }; +} + +function loadCommandResults(paths: string[]): CommandResult[] { + return paths.flatMap((path) => { + let candidate: unknown; + try { + candidate = JSON.parse(readDecodedTextFile(path)); + } catch (error) { + throw new Error(`Could not read command result "${path}": ${error instanceof SyntaxError ? "not valid JSON" : describeInputReadError(path, error)}`); + } + return (Array.isArray(candidate) ? candidate : [candidate]).map((entry, index) => commandResult(entry, `${path}[${index}]`)); + }); +} + +function commandResult(value: unknown, label: string): CommandResult { + const entry = value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; + if (typeof entry.command !== "string" || !entry.command.trim() || !STATUSES.includes(entry.status as TestOutcomeStatus)) { + throw new Error(`Command result ${label} needs a command and a status of ${STATUSES.join(", ")}.`); + } + const evidence = typeof entry.evidence === "string" && entry.evidence.trim() + ? entry.evidence + : entry.sandboxResultVersion === 1 + ? `sandbox ${String(entry.executionId)} exit ${String(entry.exitCode)} image ${String(entry.image)}` + : `${String(entry.status)} (from ${label})`; + const relatedPaths = Array.isArray(entry.relatedPaths) ? entry.relatedPaths : []; + if (!relatedPaths.every((path) => typeof path === "string")) throw new Error(`Command result ${label} relatedPaths must be strings.`); + return { command: entry.command, status: entry.status as TestOutcomeStatus, evidence: evidence.slice(0, 2_000), relatedPaths: relatedPaths as string[] }; +} + +async function resolveChangedFiles(repoRoot: string, change: ChangeSource, io: RecordCommandIo): Promise { + if (io.changedFiles) return io.changedFiles(repoRoot, change); + const repo = await scanRepo({ repoRoot, ...change, useCache: true }); + const unresolved = repo.diagnostics.find((diagnostic) => diagnostic.code === "diff-unavailable"); + if (unresolved) throw new Error(`${unresolved.message}\nFixMap needs a resolvable diff to record what was edited.`); + return repo.changedFiles; +} + +function repositoryIdentity(repoRoot: string): string { + const name = basename(repoRoot).replace(/[^A-Za-z0-9._-]/g, "-").replace(/^[^A-Za-z0-9]+/, "") || "repository"; + return createGraphIdentity({ workspace: "local", kind: "repository", key: name.slice(0, 100) }); +} + +function newId(prefix: string, now: Date): string { + return `${prefix}-${now.toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z")}-${randomBytes(4).toString("hex")}`; +} +function sha256(text: string): string { return createHash("sha256").update(text, "utf8").digest("hex"); } +function sha256Text(text: string): string { return `sha256:${sha256(text)}`; } +function one(parsed: Parsed, flag: string): string | undefined { return parsed.values.get(flag)?.[0]; } +function percent(value: number | null): string { return value === null ? "n/a" : `${(value * 100).toFixed(1)}%`; } + +function renderProblems(problems: StoredRecordProblem[]): string { + if (problems.length === 0) return ""; + return `\n## Unreadable stored files (${problems.length})\n\n${problems.map((problem) => `- ${problem.file}: ${problem.message}`).join("\n")}\n`; +} + +function renderOutcomeList(records: OutcomeRecord[]): string { + if (records.length === 0) return "# FixMap Outcomes\n\nNo outcome records found.\n"; + return `# FixMap Outcomes\n\n${records.map((record) => + `- ${record.id} (${record.recordedAt}): ${record.predictedPaths.length} predicted, ${record.editedPaths.length} edited, ` + + `task ${record.taskAssessment.status} (${record.taskAssessment.source})`).join("\n")}\n`; +} + +function renderOutcome(record: OutcomeRecord): string { + const list = (paths: string[]) => paths.length ? paths.map((path) => `- ${path}`).join("\n") : "- none"; + return [`# Outcome ${record.id}`, "", `Recorded: ${record.recordedAt}`, `Task: ${record.taskId}`, `Plan: ${record.planFingerprint}`, + `Assessment: ${record.taskAssessment.status} (${record.taskAssessment.source}): ${record.taskAssessment.reason}`, "", + "## Predicted paths", list(record.predictedPaths), "", "## Edited paths", list(record.editedPaths), "", "## Commands", + record.testOutcomes.length ? record.testOutcomes.map((test) => `- ${test.status}: ${test.command}`).join("\n") : "- none", ""].join("\n"); +} + +function renderCalibration(calibration: OutcomeCalibration): string { + const { totals } = calibration; + return [ + "# FixMap Outcome Calibration", "", + `Records: ${calibration.records}`, + `Precision: ${percent(calibration.precision)} (${totals.correctlyPredictedEdits} of ${totals.predictedPaths} predicted paths were edited)`, + `Recall: ${percent(calibration.recall)} (${totals.correctlyPredictedEdits} of ${totals.editedPaths} edited paths were predicted)`, + `Predicted but not edited: ${totals.predictedButUnedited}`, + `Edited but not predicted: ${totals.editedButUnpredicted}`, + `Commands: ${Object.entries(calibration.testOutcomes).map(([status, count]) => `${status} ${count}`).join(", ")}`, + `Task assessments: ${Object.entries(calibration.taskAssessments).map(([status, count]) => `${status} ${count}`).join(", ")}`, + "", + "Report only: ranking weights are never changed automatically (automaticWeightChanges: false).", "" + ].join("\n"); +} + +function renderDossierList(records: ChangeDossier[]): string { + if (records.length === 0) return "# FixMap Change Dossiers\n\nNo change dossiers found.\n"; + return `# FixMap Change Dossiers\n\n${records.map((record) => + `- ${record.id} (${record.createdAt}): ${record.request.summary.slice(0, 120)}`).join("\n")}\n`; +} + +function renderDossier(dossier: ChangeDossier): string { + const release = Object.entries(dossier.releaseIdentifiers).map(([key, value]) => `- ${key}: ${value}`); + return [`# Change dossier ${dossier.id}`, "", `Fingerprint: ${dossier.fingerprint}`, `Created: ${dossier.createdAt}`, + `Request: ${dossier.request.summary}`, `Plan report: ${dossier.plan.reportFingerprint}${dossier.plan.artifactPath ? ` (${dossier.plan.artifactPath})` : ""}`, + `Graph: ${dossier.plan.graphFingerprint}`, "", + "## Decisions", dossier.decisions.length ? dossier.decisions.map((entry) => `- ${entry.id}: ${entry.path}`).join("\n") : "- none", "", + "## Diff", dossier.diff ? `${dossier.diff.changedFiles.length} changed path(s)${dossier.diff.base ? ` against ${dossier.diff.base}` : ""}\n` + + dossier.diff.changedFiles.map((path) => `- ${path}`).join("\n") : "- not recorded", "", + "## Commands", dossier.tests.length ? dossier.tests.map((test) => `- ${test.status}: ${test.command}`).join("\n") : "- none", "", + "## Release identifiers", release.length ? release.join("\n") : "- none", ""].join("\n"); +} diff --git a/packages/cli/src/record-tools.ts b/packages/cli/src/record-tools.ts new file mode 100644 index 00000000..6a6cadd1 --- /dev/null +++ b/packages/cli/src/record-tools.ts @@ -0,0 +1,71 @@ +import { runDossierCommand, runOutcomeCommand } from "./outcome-command.js"; + +const PREVIEW = "Preview (may change before v0.10.0): "; + +export const OUTCOMES_TOOL = { + name: "fixmap_outcomes", + title: "FixMap outcomes", + description: `${PREVIEW}Read saved outcome records from .fixmap/outcomes/: list them, show one, or calibrate predicted versus edited paths across all of them. ` + + "Read-only; calibration never changes ranking weights. Record new outcomes with the fixmap outcome CLI.", + annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, + inputSchema: { + type: "object" as const, + properties: { + action: { type: "string", enum: ["list", "show", "calibrate"] }, + repo: { type: "string", description: "Local repository directory" }, + id: { type: "string", description: "Outcome record id (show only)" }, + format: { type: "string", enum: ["markdown", "json"] } + }, + required: ["action"], additionalProperties: false + } +}; + +export const DOSSIER_TOOL = { + name: "fixmap_dossier", + title: "FixMap change dossiers", + description: `${PREVIEW}Read saved change dossiers from .fixmap/dossiers/: list them or show one with its request, plan and graph fingerprints, ADRs, diff, commands, and commit/PR identifiers. ` + + "Read-only; create dossiers with the fixmap dossier CLI.", + annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, + inputSchema: { + type: "object" as const, + properties: { + action: { type: "string", enum: ["list", "show"] }, + repo: { type: "string", description: "Local repository directory" }, + id: { type: "string", description: "Change dossier id (show only)" }, + format: { type: "string", enum: ["markdown", "json"] } + }, + required: ["action"], additionalProperties: false + } +}; + +export function runOutcomesTool(value: unknown, defaultRepo: string) { + return runReadTool(value, defaultRepo, ["list", "show", "calibrate"], runOutcomeCommand); +} + +export function runDossierTool(value: unknown, defaultRepo: string) { + return runReadTool(value, defaultRepo, ["list", "show"], runDossierCommand); +} + +async function runReadTool( + value: unknown, + defaultRepo: string, + actions: string[], + command: typeof runOutcomeCommand +) { + const failure = (message: string) => ({ isError: true, content: [{ type: "text" as const, text: `Invalid arguments: ${message}` }] }); + if (!value || typeof value !== "object" || Array.isArray(value)) return failure("expected an object."); + const args = value as Record; + if (!actions.includes(String(args.action))) return failure(`action must be ${actions.join(", ")}.`); + for (const [key, entry] of Object.entries(args)) { + if (!["action", "repo", "id", "format"].includes(key)) return failure(`field ${key} is not allowed.`); + if (typeof entry !== "string" || !entry.trim() || entry.length > 4_096) return failure(`${key} must be a bounded non-empty string.`); + } + if ((args.action === "show") !== (args.id !== undefined)) return failure(args.action === "show" ? "id is required for show." : "id only applies to show."); + if (typeof args.id === "string" && args.id.startsWith("-")) return failure("id cannot begin with '-'."); + if (args.repo && /^[a-z][a-z0-9+.-]*:\/\//i.test(String(args.repo))) return failure("repo must be a local directory."); + const cliArgs = [String(args.action), ...(args.id ? [String(args.id)] : []), `--repo=${args.repo ?? defaultRepo}`, `--format=${args.format ?? "json"}`]; + const output: string[] = []; + const errors: string[] = []; + const code = await command(cliArgs, { stdout: (text) => { output.push(text); }, stderr: (text) => { errors.push(text); } }); + return { ...(code ? { isError: true } : {}), content: [{ type: "text" as const, text: (code ? errors : output).join("") }] }; +} diff --git a/packages/cli/test/cli-runner.test.ts b/packages/cli/test/cli-runner.test.ts index 7920fb22..55c32771 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", "Product capabilities", "Cross-repository workspace", "Repository Q&A", "Migration planning", - "Reverse documentation", "Architecture history", "Supply-chain evidence", "Runtime evidence", "Evidence import", "Execution sandbox", + "Reverse documentation", "Architecture history", "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(); diff --git a/packages/cli/test/mcp.test.ts b/packages/cli/test/mcp.test.ts index 8c444a51..426b0976 100644 --- a/packages/cli/test/mcp.test.ts +++ b/packages/cli/test/mcp.test.ts @@ -195,8 +195,8 @@ 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_history", "fixmap_migrate", - "fixmap_reverse_docs", "fixmap_runtime", "fixmap_supply_chain", "fixmap_workspace" + "fixmap_ask", "fixmap_capability", "fixmap_change_scope", "fixmap_dossier", "fixmap_history", "fixmap_migrate", + "fixmap_outcomes", "fixmap_reverse_docs", "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 +393,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_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_outcomes", "fixmap_dossier" ]); 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/outcome-command.test.ts b/packages/cli/test/outcome-command.test.ts new file mode 100644 index 00000000..f206aaed --- /dev/null +++ b/packages/cli/test/outcome-command.test.ts @@ -0,0 +1,276 @@ +import { execFile } from "node:child_process"; +import { createHash } from "node:crypto"; +import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { promisify } from "node:util"; +import { afterEach, describe, expect, it } from "vitest"; +import type { FixMapReport, OutcomeRecord } from "@aryam/fixmap-core"; +import { runCli } from "../src/cli-runner.js"; +import { runDossierCommand, runOutcomeCommand, type RecordCommandIo } from "../src/outcome-command.js"; +import { runDossierTool, runOutcomesTool } from "../src/record-tools.js"; + +const exec = promisify(execFile); +const roots: string[] = []; +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 }))); +}); + +const report: FixMapReport = { + reportVersion: 1, + summary: "Ranked.", + contextFiles: [ + { rank: 1, path: "src/a.ts", score: 9, confidence: "high", reasons: ["named"] }, + { rank: 2, path: "src/b.ts", score: 5, confidence: "medium", reasons: ["imports"] } + ], + testRoutes: [], + risks: [], + changedFiles: [], + diagnostics: [] +}; + +async function setup() { + const root = await mkdtemp(join(tmpdir(), "fixmap-outcome-cli-")); + roots.push(root); + const reportPath = join(root, "plan.json"); + await writeFile(reportPath, JSON.stringify(report)); + return { root, reportPath }; +} + +function io(edited: string[] = [], now = "2026-11-20T10:00:00.000Z") { + const stdout: string[] = []; + const stderr: string[] = []; + const value: RecordCommandIo = { + stdout: (text) => { stdout.push(text); }, + stderr: (text) => { stderr.push(text); }, + now: () => new Date(now), + changedFiles: async () => edited + }; + return { stdout, stderr, io: value, out: () => stdout.join(""), err: () => stderr.join("") }; +} + +async function storedOutcomes(root: string) { + const result = io(); + expect(await runOutcomeCommand(["list", `--repo=${root}`, "--format=json"], result.io)).toBe(0); + return JSON.parse(result.out()) as { records: OutcomeRecord[]; problems: unknown[] }; +} + +const sha = (text: string) => `sha256:${createHash("sha256").update(text).digest("hex")}`; + +describe("fixmap outcome", () => { + it("records predicted versus edited paths and command results, then shows and removes the record", async () => { + const { root, reportPath } = await setup(); + const commandPath = join(root, "tests.json"); + await writeFile(commandPath, JSON.stringify([ + { command: "npm test", status: "passed", evidence: "exit 0", relatedPaths: ["test/a.test.ts"] }, + { sandboxResultVersion: 1, executionId: "run-1", image: "node@sha256:abc", command: "npm run lint", status: "failed", exitCode: 1 } + ])); + const recorded = io(["src/a.ts", "src/c.ts"]); + expect(await runOutcomeCommand(["record", "--repo", root, "--report", reportPath, "--working-tree", "--command-result", commandPath, + "--assessment", "agent", "--status", "succeeded", "--reason", "Tests pass"], recorded.io)).toBe(0); + expect(recorded.out()).toContain("1 of 2 edited path(s) were predicted; 1 predicted path(s) were not edited."); + const [record] = (await storedOutcomes(root)).records; + expect(record).toMatchObject({ + predictedPaths: ["src/a.ts", "src/b.ts"], + editedPaths: ["src/a.ts", "src/c.ts"], + recordedAt: "2026-11-20T10:00:00.000Z", + planFingerprint: sha(JSON.stringify(report)), + repositoryIdentity: expect.stringMatching(/^fixmap:\/\/workspace\/local\/repository\//), + taskAssessment: { status: "succeeded", source: "agent", reason: "Tests pass" } + }); + expect(record!.id).toMatch(/^outcome-20261120T100000Z-[a-f0-9]{8}$/); + expect(record!.testOutcomes).toEqual([ + { command: "npm run lint", status: "failed", relatedPaths: [], evidence: "sandbox run-1 exit 1 image node@sha256:abc" }, + { command: "npm test", status: "passed", relatedPaths: ["test/a.test.ts"], evidence: "exit 0" } + ]); + + const shown = io(); + expect(await runOutcomeCommand(["show", record!.id, `--repo=${root}`], shown.io)).toBe(0); + expect(shown.out()).toContain("## Edited paths\n- src/a.ts\n- src/c.ts"); + const removed = io(); + expect(await runOutcomeCommand(["remove", record!.id, `--repo=${root}`], removed.io)).toBe(0); + expect((await storedOutcomes(root)).records).toEqual([]); + }); + + it("redacts the assessment reason and command evidence to SHA-256", async () => { + const { root, reportPath } = await setup(); + const commandPath = join(root, "tests.json"); + await writeFile(commandPath, JSON.stringify({ command: "npm test", status: "passed", evidence: "token=secret in log" })); + const result = io(["src/a.ts"]); + expect(await runOutcomeCommand(["record", `--repo=${root}`, `--report=${reportPath}`, "--diff=main...HEAD", `--command-result=${commandPath}`, + "--assessment=human", "--status=partial", "--reason=Customer ACME complained", "--redact"], result.io)).toBe(0); + const stored = await readFile(join(root, ".fixmap", "outcomes", (await readdir(join(root, ".fixmap", "outcomes")))[0]!), "utf8"); + expect(stored).not.toContain("ACME"); + expect(stored).not.toContain("secret"); + const [record] = (await storedOutcomes(root)).records; + expect(record!.taskAssessment.reason).toBe(sha("Customer ACME complained")); + expect(record!.testOutcomes[0]!.evidence).toBe(sha("token=secret in log")); + }); + + it("calibrates across stored records without changing ranking weights", async () => { + const { root, reportPath } = await setup(); + // Record 1: predicted a,b; edited a,c → 1 correct, 1 false positive, 1 miss. + expect(await runOutcomeCommand(["record", `--repo=${root}`, `--report=${reportPath}`, "--working-tree"], io(["src/a.ts", "src/c.ts"]).io)).toBe(0); + // Record 2: predicted a,b; edited a,b → 2 correct. + expect(await runOutcomeCommand(["record", `--repo=${root}`, `--report=${reportPath}`, "--working-tree", "--assessment=human", "--status=failed"], + io(["src/a.ts", "src/b.ts"], "2026-11-21T10:00:00.000Z").io)).toBe(0); + const json = io(); + expect(await runOutcomeCommand(["calibrate", `--repo=${root}`, "--format", "json"], json.io)).toBe(0); + const calibration = JSON.parse(json.out()); + expect(calibration).toMatchObject({ + records: 2, + totals: { predictedPaths: 4, editedPaths: 4, correctlyPredictedEdits: 3, predictedButUnedited: 1, editedButUnpredicted: 1 }, + precision: 0.75, + recall: 0.75, + taskAssessments: { failed: 1, unknown: 1, succeeded: 0, partial: 0 }, + automaticWeightChanges: false, + problems: [] + }); + const markdown = io(); + expect(await runOutcomeCommand(["calibrate", `--repo=${root}`], markdown.io)).toBe(0); + expect(markdown.out()).toContain("Precision: 75.0% (3 of 4 predicted paths were edited)"); + expect(markdown.out()).toContain("automaticWeightChanges: false"); + const empty = io(); + expect(await runOutcomeCommand(["calibrate", `--repo=${(await setup()).root}`], empty.io)).toBe(0); + expect(empty.out()).toContain("Precision: n/a"); + }); + + it("prunes records older than a number of days", async () => { + const { root, reportPath } = await setup(); + await runOutcomeCommand(["record", `--repo=${root}`, `--report=${reportPath}`, "--working-tree"], io([], "2026-01-01T00:00:00.000Z").io); + await runOutcomeCommand(["record", `--repo=${root}`, `--report=${reportPath}`, "--working-tree"], io([], "2026-11-19T00:00:00.000Z").io); + const pruned = io([], "2026-11-20T00:00:00.000Z"); + expect(await runOutcomeCommand(["prune", `--repo=${root}`, "--older-than", "30"], pruned.io)).toBe(0); + expect(pruned.out()).toContain("Removed 1 outcome record(s)"); + expect((await storedOutcomes(root)).records.map((record) => record.recordedAt)).toEqual(["2026-11-19T00:00:00.000Z"]); + expect(await runOutcomeCommand(["prune", `--repo=${root}`, "--older-than", "-1"], io().io)).toBe(1); + }); + + it("lists malformed stored files as problems instead of failing", async () => { + const { root, reportPath } = await setup(); + await runOutcomeCommand(["record", `--repo=${root}`, `--report=${reportPath}`, "--working-tree"], io(["src/a.ts"]).io); + await writeFile(join(root, ".fixmap", "outcomes", "broken.json"), "{"); + const listed = io(); + expect(await runOutcomeCommand(["list", `--repo=${root}`], listed.io)).toBe(0); + expect(listed.out()).toContain("## Unreadable stored files (1)\n\n- .fixmap/outcomes/broken.json: Not valid JSON"); + const calibrated = io(); + expect(await runOutcomeCommand(["calibrate", `--repo=${root}`, "--format=json"], calibrated.io)).toBe(0); + expect(JSON.parse(calibrated.out())).toMatchObject({ records: 1, problems: [{ file: ".fixmap/outcomes/broken.json" }] }); + }); + + it("rejects invalid arguments with a clear message", async () => { + const { root, reportPath } = await setup(); + const cases: Array<[string[], string]> = [ + [["record", `--report=${reportPath}`], "Provide --diff or --working-tree"], + [["record", `--report=${reportPath}`, "--working-tree", "--diff=a..b"], "not both"], + [["record", `--report=${reportPath}`, "--working-tree", "--assessment=human"], "--status succeeded|failed|partial|unknown is required"], + [["record", `--report=${reportPath}`, "--working-tree", "--status=succeeded"], "An unassessed outcome can only have --status unknown"], + [["record", `--report=${join(root, "missing.json")}`, "--working-tree"], "does not exist"], + [["list", "--older-than=3"], "--older-than does not apply to outcome list"], + [["show"], "needs exactly one record id"], + [["show", "../../etc/passwd"], "Invalid outcome record id"], + [["explode"], "Unknown outcome action: explode"], + [["list", "--format=xml"], "--format must be markdown or json"] + ]; + for (const [args, message] of cases) { + const result = io(["src/a.ts"]); + expect(await runOutcomeCommand([...args, `--repo=${root}`], result.io), args.join(" ")).toBe(1); + expect(result.err(), args.join(" ")).toContain(message); + } + const markdown = join(root, "plan.md"); + await writeFile(markdown, "# FixMap report"); + const result = io(); + expect(await runOutcomeCommand(["record", `--repo=${root}`, `--report=${markdown}`, "--working-tree"], result.io)).toBe(1); + expect(result.err()).toContain("is not a JSON FixMap report"); + expect(await readdir(root)).not.toContain(".fixmap"); + }); + + it("reads edited paths from a real Git working tree through the CLI", async () => { + const { root, reportPath } = await setup(); + await mkdir(join(root, "src")); + await writeFile(join(root, "src", "a.ts"), "export const a = 1;\n"); + await writeFile(join(root, "src", "b.ts"), "export const b = 1;\n"); + await exec("git", ["init", "--quiet"], { cwd: root }); + await exec("git", ["config", "user.email", "fixmap@example.test"], { cwd: root }); + await exec("git", ["config", "user.name", "FixMap Test"], { cwd: root }); + await exec("git", ["add", "src"], { cwd: root }); + await exec("git", ["commit", "--quiet", "-m", "init"], { cwd: root }); + await writeFile(join(root, "src", "a.ts"), "export const a = 2;\n"); + const stdout: string[] = []; + const stderr: string[] = []; + expect(await runCli(["outcome", "record", "--repo", root, "--report", reportPath, "--working-tree"], { + stdout: (text) => { stdout.push(text); }, stderr: (text) => { stderr.push(text); } + }), stderr.join("")).toBe(0); + expect((await storedOutcomes(root)).records[0]).toMatchObject({ editedPaths: ["src/a.ts"] }); + }); +}); + +describe("fixmap dossier", () => { + it("creates, lists, shows, and removes a fingerprinted dossier with diff and release identifiers", async () => { + const { root, reportPath } = await setup(); + const created = io(["src/a.ts"]); + expect(await runDossierCommand(["create", `--repo=${root}`, `--report=${reportPath}`, "--task", "Fix login redirect", + "--diff=main...HEAD", "--pr=https://github.com/o/r/pull/9", "--commit=abc123"], created.io)).toBe(0); + expect(created.out()).toMatch(/Saved \.fixmap\/dossiers\/dossier-20261120T100000Z-[a-f0-9]{8}\.json \(dossier:[a-f0-9]{16}\)/); + const listed = io(); + expect(await runDossierCommand(["list", `--repo=${root}`, "--format=json"], listed.io)).toBe(0); + const [dossier] = JSON.parse(listed.out()).records; + expect(dossier).toMatchObject({ + request: { summary: "Fix login redirect", sourceFingerprint: sha("Fix login redirect") }, + plan: { reportFingerprint: sha(JSON.stringify(report)), artifactPath: "plan.json" }, + diff: { changedFiles: ["src/a.ts"], base: "main...HEAD" }, + releaseIdentifiers: { pullRequest: "https://github.com/o/r/pull/9", commit: "abc123" } + }); + const shown = io(); + expect(await runDossierCommand(["show", dossier.id, `--repo=${root}`], shown.io)).toBe(0); + expect(shown.out()).toContain("- pullRequest: https://github.com/o/r/pull/9"); + expect(await runDossierCommand(["remove", dossier.id, `--repo=${root}`], io().io)).toBe(0); + expect(await readdir(join(root, ".fixmap", "dossiers"))).toEqual([]); + }); + + it("redacts the task text and allows a dossier without a diff", async () => { + const { root, reportPath } = await setup(); + expect(await runDossierCommand(["create", `--repo=${root}`, `--report=${reportPath}`, "--task=Patient Jane Doe data leak", "--redact"], io().io)).toBe(0); + const directory = join(root, ".fixmap", "dossiers"); + const text = await readFile(join(directory, (await readdir(directory))[0]!), "utf8"); + expect(text).not.toContain("Jane"); + expect(JSON.parse(text)).toMatchObject({ request: { summary: sha("Patient Jane Doe data leak") }, diff: null }); + const missingTask = io(); + expect(await runDossierCommand(["create", `--repo=${root}`, `--report=${reportPath}`], missingTask.io)).toBe(1); + expect(missingTask.err()).toContain("requires --task"); + }); +}); + +describe("read-only MCP record tools", () => { + it("lists, shows, and calibrates outcomes and dossiers without writing", async () => { + const { root, reportPath } = await setup(); + await runOutcomeCommand(["record", `--repo=${root}`, `--report=${reportPath}`, "--working-tree"], io(["src/a.ts"]).io); + await runDossierCommand(["create", `--repo=${root}`, `--report=${reportPath}`, "--task=Fix"], io().io); + const listed = await runOutcomesTool({ action: "list", repo: root }, root); + const id = JSON.parse(listed.content[0]!.text).records[0].id as string; + const shown = await runOutcomesTool({ action: "show", id }, root); + expect(JSON.parse(shown.content[0]!.text).id).toBe(id); + const calibration = JSON.parse((await runOutcomesTool({ action: "calibrate", repo: root }, root)).content[0]!.text); + expect(calibration).toMatchObject({ records: 1, precision: 0.5, recall: 1, automaticWeightChanges: false }); + const dossiers = JSON.parse((await runDossierTool({ action: "list" }, root)).content[0]!.text); + expect(dossiers.records).toHaveLength(1); + + for (const [tool, args, message] of [ + [runOutcomesTool, { action: "record" }, "action must be"], + [runOutcomesTool, { action: "remove", id }, "action must be"], + [runDossierTool, { action: "calibrate" }, "action must be"], + [runDossierTool, { action: "show" }, "id is required"], + [runOutcomesTool, { action: "list", id }, "id only applies"], + [runOutcomesTool, { action: "list", olderThan: "3" }, "not allowed"], + [runOutcomesTool, { action: "show", id: "--repo=/" }, "cannot begin"], + [runDossierTool, { action: "list", repo: "https://example.com/r" }, "local directory"] + ] as const) { + const result = await tool(args, root); + expect(result.isError).toBe(true); + expect(result.content[0]!.text).toContain(message); + } + const missing = await runOutcomesTool({ action: "show", id: "outcome-missing" }, root); + expect(missing.isError).toBe(true); + expect(missing.content[0]!.text).toContain("No outcome record found"); + }); +}); diff --git a/packages/core/src/feature-catalog.ts b/packages/core/src/feature-catalog.ts index afdea7f1..36ec3993 100644 --- a/packages/core/src/feature-catalog.ts +++ b/packages/core/src/feature-catalog.ts @@ -25,13 +25,15 @@ export const FIXMAP_FEATURES: readonly FixMapFeature[] = [ { name: "Supply-chain evidence", preview: true, command: "fixmap supply-chain --input ", detail: "Validate normalized external scanner or SBOM evidence with exact tool, database, document, advisory, version, and license provenance." }, { name: "Runtime evidence", preview: true, command: "fixmap runtime --input ", detail: "Map redaction-reviewed OpenTelemetry, APM, Speedscope, or pprof observations only through exact repository paths and file fingerprints." }, { name: "Evidence import", preview: true, command: "fixmap plan --evidence ", detail: "Attach findings from other tools (scanners, CI, runtime monitors) to the files in a plan from a version-1 data-only bundle; claims are shown as supplied and never executed." }, + { name: "Outcome feedback loop", preview: true, command: "fixmap outcome record --report --working-tree", detail: "Save what a plan predicted next to what was edited and which commands passed, one atomic file per record in .fixmap/outcomes/, then calibrate precision and recall; ranking weights never change automatically." }, + { name: "Change dossier", preview: true, command: "fixmap dossier create --report --task ", detail: "Save a fingerprinted record linking the request, plan and graph fingerprints, ADRs, diff, command results, and commit/PR identifiers in .fixmap/dossiers/, with optional SHA-256 redaction of the task text." }, { name: "Execution sandbox", preview: true, command: "fixmap sandbox --request --execute-declared-command", detail: "Run exactly one reviewed command in an already-present digest-pinned Docker image with network off and source/root read-only by default." }, { name: "Explain", command: "fixmap plan --explain ", detail: "Show whether a path ranked, tied below the limit, was excluded, or was never scanned." }, { name: "Compare", command: "fixmap plan --compare ", detail: "Compare a refined task and current plan with an earlier JSON report." }, { 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, Capability maps, Workspace, Ask, Migrate, Reverse Docs, History, 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." }, diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index a7cd0cd8..88553763 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -50,6 +50,11 @@ 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 { + deleteStoredDossier, deleteStoredOutcome, isStoredRecordId, pruneStoredOutcomes, readStoredDossier, readStoredDossiers, + readStoredOutcome, readStoredOutcomes, saveStoredDossier, saveStoredOutcome +} from "./record-store.js"; +export type { StoredRecordProblem, StoredRecords } from "./record-store.js"; export { routeReviewers } from "./ownership.js"; export type { ReviewEvidence, ReviewRoutingResult, ReviewSuggestion } from "./ownership.js"; export { buildSandboxInvocation, runSandbox } from "./sandbox.js"; diff --git a/packages/core/src/record-store.ts b/packages/core/src/record-store.ts new file mode 100644 index 00000000..f41d81b5 --- /dev/null +++ b/packages/core/src/record-store.ts @@ -0,0 +1,276 @@ +import { lstat, mkdir, open, readdir, readFile, realpath, rename, rm, stat } from "node:fs/promises"; +import { resolve } from "node:path"; +import { randomUUID } from "node:crypto"; +import { validateChangeDossier, type ChangeDossier } from "./dossier.js"; +import { createOutcomeRecord, type OutcomeRecord } from "./outcomes.js"; + +/** + * Repository-local persistence for outcome records (.fixmap/outcomes/) and change dossiers + * (.fixmap/dossiers/), one JSON file per record. Follows the annotation store: writes go + * through a temp file and rename, links and junctions are refused, and a lock held by + * another writer is never taken over, however old it looks. + */ + +export type StoredRecordProblem = { file: string; message: string }; +export type StoredRecords = { records: T[]; problems: StoredRecordProblem[] }; + +/** Stored IDs double as file names, so they exclude ':' (invalid on Windows) and a trailing dot. */ +const STORED_ID = /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,126}[A-Za-z0-9_-])?$/; +const LOCK_ATTEMPTS = 40; +const LOCK_RETRY_MS = 25; + +type Kind = { + directory: "outcomes" | "dossiers"; + label: string; + validate: (value: unknown) => T; + id: (record: T) => string; + date: (record: T) => string; +}; + +const OUTCOMES: Kind = { + directory: "outcomes", + label: "outcome record", + validate: (value) => { + if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid outcome record envelope."); + const { outcomeRecordVersion, ...rest } = value as OutcomeRecord; + if (outcomeRecordVersion !== 1) throw new Error("Invalid outcome record envelope."); + return createOutcomeRecord(rest); + }, + id: (record) => record.id, + date: (record) => record.recordedAt +}; + +const DOSSIERS: Kind = { + directory: "dossiers", + label: "change dossier", + validate: validateChangeDossier, + id: (record) => record.id, + date: (record) => record.createdAt +}; + +export function isStoredRecordId(id: string): boolean { return STORED_ID.test(id); } + +export const readStoredOutcomes = (repoRoot: string) => listRecords(OUTCOMES, repoRoot); +export const readStoredOutcome = (repoRoot: string, id: string) => readRecord(OUTCOMES, repoRoot, id); +export const saveStoredOutcome = (repoRoot: string, record: OutcomeRecord) => saveRecord(OUTCOMES, repoRoot, record); +export const deleteStoredOutcome = (repoRoot: string, id: string) => deleteRecord(OUTCOMES, repoRoot, id); +/** Delete outcome records recorded strictly before `cutoff`. Malformed files are reported, never deleted. */ +export const pruneStoredOutcomes = (repoRoot: string, cutoff: Date) => pruneRecords(OUTCOMES, repoRoot, cutoff); + +export const readStoredDossiers = (repoRoot: string) => listRecords(DOSSIERS, repoRoot); +export const readStoredDossier = (repoRoot: string, id: string) => readRecord(DOSSIERS, repoRoot, id); +export const saveStoredDossier = (repoRoot: string, record: ChangeDossier) => saveRecord(DOSSIERS, repoRoot, record); +export const deleteStoredDossier = (repoRoot: string, id: string) => deleteRecord(DOSSIERS, repoRoot, id); + +async function listRecords(kind: Kind, repoRoot: string): Promise> { + const root = await repositoryRoot(repoRoot); + const directory = await existingKindDirectory(kind, root); + if (!directory) return { records: [], problems: [] }; + const records: T[] = []; + const problems: StoredRecordProblem[] = []; + for (const name of (await readdir(directory)).sort()) { + if (name.startsWith(".")) continue; // in-flight or abandoned temp files + const file = `.fixmap/${kind.directory}/${name}`; + const id = name.endsWith(".json") ? name.slice(0, -".json".length) : ""; + if (!isStoredRecordId(id)) { problems.push({ file, message: "Not a record file (expected .json)." }); continue; } + try { + records.push(await readRecordFile(kind, directory, id)); + } catch (error) { + problems.push({ file, message: errorMessage(error) }); + } + } + records.sort((a, b) => kind.date(a).localeCompare(kind.date(b)) || kind.id(a).localeCompare(kind.id(b))); + return { records, problems }; +} + +async function readRecord(kind: Kind, repoRoot: string, id: string): Promise { + assertId(kind, id); + const root = await repositoryRoot(repoRoot); + const directory = await existingKindDirectory(kind, root); + if (!directory) throw new Error(`No ${kind.label} found: ${id}`); + try { + return await readRecordFile(kind, directory, id); + } catch (error) { + if (isNodeError(error, "ENOENT")) throw new Error(`No ${kind.label} found: ${id}`); + throw error; + } +} + +async function saveRecord(kind: Kind, repoRoot: string, record: T): Promise { + const validated = kind.validate(record); + const id = kind.id(validated); + assertId(kind, id); + const root = await repositoryRoot(repoRoot); + return withLock(kind, root, async (directory) => { + const target = recordPath(directory, id); + if (await fileInfo(target)) throw new Error(`A ${kind.label} with id ${id} already exists.`); + const temporary = resolve(directory, `.${id}.${process.pid}.${randomUUID()}.tmp`); + const handle = await open(temporary, "wx", 0o600); + try { + await handle.writeFile(`${JSON.stringify(validated, null, 2)}\n`, "utf8"); + await handle.sync(); + } finally { + await handle.close(); + } + try { + await rename(temporary, target); + } catch (error) { + await rm(temporary, { force: true }); + throw error; + } + return validated; + }); +} + +async function deleteRecord(kind: Kind, repoRoot: string, id: string): Promise { + assertId(kind, id); + const root = await repositoryRoot(repoRoot); + await withLock(kind, root, async (directory) => { + const target = recordPath(directory, id); + const info = await fileInfo(target); + if (!info) throw new Error(`No ${kind.label} found: ${id}`); + assertRegularFile(kind, info); + await rm(target); + }); +} + +async function pruneRecords(kind: Kind, repoRoot: string, cutoff: Date): Promise<{ removed: string[]; kept: number; problems: StoredRecordProblem[] }> { + if (!Number.isFinite(cutoff.getTime())) throw new Error("Prune cutoff must be a valid date."); + const root = await repositoryRoot(repoRoot); + if (!(await existingKindDirectory(kind, root))) return { removed: [], kept: 0, problems: [] }; + return withLock(kind, root, async (directory) => { + const { records, problems } = await listRecords(kind, root); + const removed: string[] = []; + for (const record of records) { + if (Date.parse(kind.date(record)) >= cutoff.getTime()) continue; + const target = recordPath(directory, kind.id(record)); + const info = await fileInfo(target); + if (!info) continue; + assertRegularFile(kind, info); + await rm(target); + removed.push(kind.id(record)); + } + return { removed, kept: records.length - removed.length, problems }; + }); +} + +async function readRecordFile(kind: Kind, directory: string, id: string): Promise { + const path = recordPath(directory, id); + const info = await lstat(path); + assertRegularFile(kind, info); + let parsed: unknown; + try { + parsed = JSON.parse(await readFile(path, "utf8")) as unknown; + } catch (error) { + if (error instanceof SyntaxError) throw new Error(`Not valid JSON: ${error.message}`); + throw error; + } + const record = kind.validate(parsed); + if (kind.id(record) !== id) throw new Error(`File name does not match its ${kind.label} id ${kind.id(record)}.`); + return record; +} + +async function withLock(kind: Kind, root: string, operation: (directory: string) => Promise): Promise { + const directory = await createKindDirectory(kind, root); + const lockPath = resolve(root, ".fixmap", `${kind.directory}.lock`); + let handle; + for (let attempt = 1; !handle; attempt += 1) { + const existing = await fileInfo(lockPath); + if (existing) assertRegularFile(kind, existing); + try { + handle = await open(lockPath, "wx", 0o600); + } catch (error) { + if (!isNodeError(error, "EEXIST")) throw error; + // Age cannot prove that a writer has stopped (it may be suspended), so the lock is never + // taken over. Wait a bounded time for a live writer, then refuse. + if (attempt >= LOCK_ATTEMPTS) { + throw new Error(`Another FixMap ${kind.label} update is in progress or left a lock. Retry after it finishes; if interrupted, confirm no FixMap writer is running before manually removing .fixmap/${kind.directory}.lock.`); + } + await new Promise((done) => setTimeout(done, LOCK_RETRY_MS)); + } + } + try { + await handle.writeFile(`${JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString() })}\n`, "utf8"); + await handle.sync(); + await assertDirectory(kind, root, directory); + return await operation(directory); + } finally { + try { + await handle.close(); + } finally { + await rm(lockPath, { force: true }); + } + } +} + +async function repositoryRoot(path: string): Promise { + const root = await realpath(path); + if (!(await stat(root)).isDirectory()) throw new Error("FixMap repository must be a directory."); + return root; +} + +async function existingKindDirectory(kind: Kind, root: string): Promise { + const fixmap = resolve(root, ".fixmap"); + if (!(await fileInfo(fixmap))) return undefined; + await assertDirectory(kind, root, fixmap); + const directory = resolve(fixmap, kind.directory); + if (!(await fileInfo(directory))) return undefined; + await assertDirectory(kind, root, directory); + return directory; +} + +async function createKindDirectory(kind: Kind, root: string): Promise { + const fixmap = resolve(root, ".fixmap"); + if (await fileInfo(fixmap)) await assertDirectory(kind, root, fixmap); + else await makeDirectory(fixmap); + await assertDirectory(kind, root, fixmap); + const directory = resolve(fixmap, kind.directory); + if (!(await fileInfo(directory))) await makeDirectory(directory); + await assertDirectory(kind, root, directory); + return directory; +} + +/** A concurrent writer may create the directory first; the link check that follows still applies. */ +async function makeDirectory(path: string): Promise { + await mkdir(path).catch((error: unknown) => { + if (!isNodeError(error, "EEXIST")) throw error; + }); +} + +/** Refuse a link, junction, or anything that resolves somewhere other than its lexical path. */ +async function assertDirectory(kind: Kind, root: string, directory: string): Promise { + const info = await lstat(directory); + if (!info.isDirectory() || info.isSymbolicLink() || await realpath(directory) !== directory || !directory.startsWith(root)) { + throw new Error(`The ${kind.label} store must be a real repository-local directory (.fixmap/${kind.directory}), not a link or junction.`); + } +} + +function assertRegularFile(kind: Kind, info: Awaited>): void { + if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1) { + throw new Error(`Stored ${kind.label} files and locks must be regular, unlinked repository-local files.`); + } +} + +function recordPath(directory: string, id: string): string { + const path = resolve(directory, `${id}.json`); + if (resolve(path, "..") !== directory) throw new Error("Record path escapes its store directory."); + return path; +} + +function assertId(kind: Kind, id: string): void { + if (typeof id !== "string" || !isStoredRecordId(id)) { + throw new Error(`Invalid ${kind.label} id: use letters, digits, '.', '_' or '-' (at most 128 characters, no path separators).`); + } +} + +async function fileInfo(path: string) { + return lstat(path).catch((error: unknown) => { + if (isNodeError(error, "ENOENT")) return undefined; + throw error; + }); +} + +function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error); } +function isNodeError(error: unknown, code: string): error is NodeJS.ErrnoException { + return error instanceof Error && "code" in error && (error as NodeJS.ErrnoException).code === code; +} diff --git a/packages/core/test/record-store.test.ts b/packages/core/test/record-store.test.ts new file mode 100644 index 00000000..8fc0e458 --- /dev/null +++ b/packages/core/test/record-store.test.ts @@ -0,0 +1,188 @@ +import { link, mkdir, mkdtemp, readdir, readFile, rm, symlink, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import { afterEach, describe, expect, it } from "vitest"; +import { buildChangeDossier } from "../src/dossier.js"; +import { createOutcomeRecord, type OutcomeRecord } from "../src/outcomes.js"; +import { + deleteStoredDossier, + deleteStoredOutcome, + pruneStoredOutcomes, + readStoredDossier, + readStoredDossiers, + readStoredOutcome, + readStoredOutcomes, + saveStoredDossier, + saveStoredOutcome +} from "../src/record-store.js"; + +const roots: string[] = []; +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 }))); +}); + +async function repo(): Promise { + const root = await mkdtemp(join(tmpdir(), "fixmap-record-store-")); + roots.push(root); + return root; +} + +function outcome(id: string, recordedAt = "2026-11-01T00:00:00Z", overrides: Partial = {}): OutcomeRecord { + return createOutcomeRecord({ + id, + taskId: "task-1", + repositoryIdentity: "fixmap://workspace/local/repository/api", + planFingerprint: "sha256:0123456789abcdef", + recordedAt, + predictedPaths: ["src/a.ts", "src/b.ts"], + editedPaths: ["src/a.ts", "src/c.ts"], + testOutcomes: [], + taskAssessment: { status: "unknown", source: "unassessed", reason: "Not assessed." }, + ...overrides + }); +} + +function dossier(id: string) { + return buildChangeDossier({ + id, + repositoryIdentity: "fixmap://workspace/local/repository/api", + createdAt: "2026-11-01T00:00:00Z", + updatedAt: "2026-11-01T00:00:00Z", + request: { summary: "Fix login", sourceFingerprint: "sha256:abcdef012345" }, + assumptions: [], + plan: { reportFingerprint: "sha256:111111111111", graphFingerprint: "sha256:222222222222" }, + decisions: [], + diff: null, + tests: [], + runtimeEvidence: [], + reviews: [], + releaseIdentifiers: { pullRequest: "https://github.com/o/r/pull/1" } + }); +} + +describe("outcome and dossier store", () => { + it("reads nothing and creates nothing in a repository without a store", async () => { + const root = await repo(); + expect(await readStoredOutcomes(root)).toEqual({ records: [], problems: [] }); + expect(await readStoredDossiers(root)).toEqual({ records: [], problems: [] }); + await expect(readStoredOutcome(root, "missing")).rejects.toThrow("No outcome record found: missing"); + expect(await readdir(root)).toEqual([]); + }); + + it("writes one file per record atomically, leaves no temp file, and releases the lock", async () => { + const root = await repo(); + const saved = await saveStoredOutcome(root, outcome("outcome-1")); + expect(await readdir(join(root, ".fixmap"))).toEqual(["outcomes"]); + expect(await readdir(join(root, ".fixmap", "outcomes"))).toEqual(["outcome-1.json"]); + expect(JSON.parse(await readFile(join(root, ".fixmap", "outcomes", "outcome-1.json"), "utf8"))).toEqual(saved); + expect(await readStoredOutcome(root, "outcome-1")).toEqual(saved); + await expect(saveStoredOutcome(root, outcome("outcome-1"))).rejects.toThrow("already exists"); + await saveStoredDossier(root, dossier("dossier-1")); + expect(await readStoredDossier(root, "dossier-1")).toEqual(dossier("dossier-1")); + expect((await readdir(join(root, ".fixmap"))).sort()).toEqual(["dossiers", "outcomes"]); + }); + + it("serializes concurrent writers without corrupting or losing a saved record", async () => { + const root = await repo(); + const ids = Array.from({ length: 12 }, (_, index) => `outcome-${index}`); + const results = await Promise.allSettled(ids.map((id) => saveStoredOutcome(root, outcome(id)))); + for (const result of results) { + if (result.status === "rejected") expect(String(result.reason)).toContain("in progress or left a lock"); + } + const saved = ids.filter((_, index) => results[index]!.status === "fulfilled"); + expect(saved.length).toBeGreaterThan(0); + const stored = await readStoredOutcomes(root); + expect(stored.problems).toEqual([]); + expect(stored.records.map((record) => record.id).sort()).toEqual(saved.sort()); + expect(await readdir(join(root, ".fixmap", "outcomes"))).toHaveLength(saved.length); + expect(await readdir(join(root, ".fixmap"))).not.toContain("outcomes.lock"); + }); + + it("refuses to take over a lock another writer holds, however old", async () => { + const root = await repo(); + await mkdir(join(root, ".fixmap")); + const lock = join(root, ".fixmap", "outcomes.lock"); + await writeFile(lock, '{"pid":1}\n'); + await expect(saveStoredOutcome(root, outcome("outcome-1"))).rejects.toThrow("in progress or left a lock"); + await expect(deleteStoredOutcome(root, "outcome-1")).rejects.toThrow("in progress or left a lock"); + expect(await readFile(lock, "utf8")).toBe('{"pid":1}\n'); + expect(await readdir(join(root, ".fixmap", "outcomes"))).toEqual([]); + }); + + it("rejects ids that could traverse out of the store", async () => { + const root = await repo(); + for (const id of ["../escape", "..", "a/b", "a\\b", "C:evil", "name.", ".hidden", ""]) { + await expect(readStoredOutcome(root, id)).rejects.toThrow("Invalid outcome record id"); + await expect(deleteStoredDossier(root, id)).rejects.toThrow("Invalid change dossier id"); + } + await expect(saveStoredOutcome(root, outcome("x:y"))).rejects.toThrow("Invalid outcome record id"); + }); + + it("refuses a linked .fixmap directory, a linked store directory, and hardlinked records", async () => { + const outside = await repo(); + const root = await repo(); + await symlink(outside, join(root, ".fixmap"), process.platform === "win32" ? "junction" : "dir"); + await expect(saveStoredOutcome(root, outcome("outcome-1"))).rejects.toThrow("not a link or junction"); + await expect(readStoredOutcomes(root)).rejects.toThrow("not a link or junction"); + expect(await readdir(outside)).toEqual([]); + + const second = await repo(); + await mkdir(join(second, ".fixmap")); + await symlink(outside, join(second, ".fixmap", "dossiers"), process.platform === "win32" ? "junction" : "dir"); + await expect(saveStoredDossier(second, dossier("dossier-1"))).rejects.toThrow("not a link or junction"); + expect(await readdir(outside)).toEqual([]); + + const third = await repo(); + await saveStoredOutcome(third, outcome("outcome-1")); + await link(join(third, ".fixmap", "outcomes", "outcome-1.json"), join(outside, "copy.json")); + await expect(readStoredOutcome(third, "outcome-1")).rejects.toThrow("regular, unlinked"); + await expect(deleteStoredOutcome(third, "outcome-1")).rejects.toThrow("regular, unlinked"); + expect((await readStoredOutcomes(third)).problems).toEqual([ + { file: ".fixmap/outcomes/outcome-1.json", message: expect.stringContaining("regular, unlinked") } + ]); + }); + + it("reports malformed stored files without crashing or hiding valid records", async () => { + const root = await repo(); + await saveStoredOutcome(root, outcome("good")); + const directory = join(root, ".fixmap", "outcomes"); + await writeFile(join(directory, "broken.json"), "{not json"); + await writeFile(join(directory, "invalid.json"), JSON.stringify({ outcomeRecordVersion: 1, id: "invalid" })); + await writeFile(join(directory, "renamed.json"), JSON.stringify(outcome("other"))); + await writeFile(join(directory, "notes.txt"), "hello"); + await writeFile(join(directory, ".good.123.tmp"), "partial"); + const stored = await readStoredOutcomes(root); + expect(stored.records.map((record) => record.id)).toEqual(["good"]); + expect(stored.problems).toEqual([ + { file: ".fixmap/outcomes/broken.json", message: expect.stringContaining("Not valid JSON") }, + { file: ".fixmap/outcomes/invalid.json", message: "Invalid outcome record envelope." }, + { file: ".fixmap/outcomes/notes.txt", message: "Not a record file (expected .json)." }, + { file: ".fixmap/outcomes/renamed.json", message: expect.stringContaining("does not match") } + ]); + const tampered = { ...dossier("dossier-1"), request: { summary: "edited", sourceFingerprint: "sha256:abcdef012345" } }; + await mkdir(join(root, ".fixmap", "dossiers")); + await writeFile(join(root, ".fixmap", "dossiers", "dossier-1.json"), JSON.stringify(tampered)); + expect((await readStoredDossiers(root)).problems[0]?.message).toContain("fingerprint does not match"); + }); + + it("prunes only records older than the cutoff and never deletes malformed files", async () => { + const root = await repo(); + await saveStoredOutcome(root, outcome("old", "2026-01-01T00:00:00Z")); + await saveStoredOutcome(root, outcome("edge", "2026-06-01T00:00:00Z")); + await saveStoredOutcome(root, outcome("new", "2026-11-01T00:00:00Z")); + await writeFile(join(root, ".fixmap", "outcomes", "broken.json"), "{"); + const result = await pruneStoredOutcomes(root, new Date("2026-06-01T00:00:00Z")); + expect(result).toMatchObject({ removed: ["old"], kept: 2 }); + expect(result.problems).toHaveLength(1); + expect((await readdir(join(root, ".fixmap", "outcomes"))).sort()).toEqual(["broken.json", "edge.json", "new.json"]); + expect(await pruneStoredOutcomes(await repo(), new Date())).toEqual({ removed: [], kept: 0, problems: [] }); + }); + + it("removes a record and reports a missing one", async () => { + const root = await repo(); + await saveStoredDossier(root, dossier("dossier-1")); + await deleteStoredDossier(root, "dossier-1"); + expect((await readStoredDossiers(root)).records).toEqual([]); + await expect(deleteStoredDossier(root, "dossier-1")).rejects.toThrow("No change dossier found: dossier-1"); + }); +}); From 237758e4fe437f08b80429c962e9be50b251b12a Mon Sep 17 00:00:00 2001 From: Aryam Goyal Date: Sun, 22 Nov 2026 20:11:14 +0530 Subject: [PATCH 4/9] fix(cli): keep the dossier artifact path when paths differ only by realpath The repository root is resolved with realpath (macOS /var -> /private/var, Windows 8.3 short names on CI runners), but the report path was only resolved lexically, so relative() began with ".." and the plan artifact path was dropped. Compare against the report's realpath, and add a regression that reaches the repository and report through a symlink/junction alias. Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/outcome-command.ts | 3 ++- packages/cli/test/outcome-command.test.ts | 19 ++++++++++++++++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/packages/cli/src/outcome-command.ts b/packages/cli/src/outcome-command.ts index e04c2b77..448b10d9 100644 --- a/packages/cli/src/outcome-command.ts +++ b/packages/cli/src/outcome-command.ts @@ -196,7 +196,8 @@ async function createDossier(repoRoot: string, parsed: Parsed, io: RecordCommand ...(change.diffSpec ? { base: change.diffSpec } : { base: "HEAD", head: "working-tree" }) }; } - const artifact = relative(repoRoot, resolve(reportPath!)).replace(/\\/g, "/"); + // repoRoot is a realpath (macOS /private/var, Windows 8.3 names), so compare against the report's realpath too. + const artifact = relative(repoRoot, await realpath(resolve(reportPath!))).replace(/\\/g, "/"); const dossier = buildChangeDossier({ id: newId("dossier", new Date(now)), repositoryIdentity: repositoryIdentity(repoRoot), diff --git a/packages/cli/test/outcome-command.test.ts b/packages/cli/test/outcome-command.test.ts index f206aaed..b24d2149 100644 --- a/packages/cli/test/outcome-command.test.ts +++ b/packages/cli/test/outcome-command.test.ts @@ -1,6 +1,6 @@ import { execFile } from "node:child_process"; import { createHash } from "node:crypto"; -import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, readdir, readFile, rm, symlink, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { promisify } from "node:util"; @@ -228,6 +228,23 @@ describe("fixmap dossier", () => { expect(await readdir(join(root, ".fixmap", "dossiers"))).toEqual([]); }); + it("keeps the plan artifact path when the repository or report is reached through a link", async () => { + // Regression: the repository root is a realpath (macOS /var -> /private/var, Windows 8.3 + // names), and a lexically resolved report path made the artifact look outside the repository. + const { root, reportPath } = await setup(); + const aliasParent = await mkdtemp(join(tmpdir(), "fixmap-dossier-alias-")); + roots.push(aliasParent); + const alias = join(aliasParent, "repo"); + await symlink(root, alias, process.platform === "win32" ? "junction" : "dir"); + for (const [repo, plan] of [[alias, reportPath], [root, join(alias, "plan.json")]]) { + expect(await runDossierCommand(["create", `--repo=${repo}`, `--report=${plan}`, "--task=Fix"], io().io)).toBe(0); + } + const listed = io(); + expect(await runDossierCommand(["list", `--repo=${root}`, "--format=json"], listed.io)).toBe(0); + const records = JSON.parse(listed.out()).records as Array<{ plan: { artifactPath?: string } }>; + expect(records.map((record) => record.plan.artifactPath)).toEqual(["plan.json", "plan.json"]); + }); + it("redacts the task text and allows a dossier without a diff", async () => { const { root, reportPath } = await setup(); expect(await runDossierCommand(["create", `--repo=${root}`, `--report=${reportPath}`, "--task=Patient Jane Doe data leak", "--redact"], io().io)).toBe(0); From a7bd28e960e26c89faea35d55621ac9bcfc73f80 Mon Sep 17 00:00:00 2001 From: Aryam Goyal Date: Sun, 22 Nov 2026 20:12:47 +0530 Subject: [PATCH 5/9] feat: Contract Guardian on the CLI and MCP (preview) - fixmap contracts lists OpenAPI, AsyncAPI, GraphQL, Protobuf, JSON Schema and SQL migration surfaces in the working tree with kind, declared version and exact fingerprint. - fixmap contracts diff .. compares two exact Git refs through Git objects (no checkout, no worktree change) and prints breaking / unknown / compatible changes with before/after fingerprints. - Read-only MCP tool fixmap_contracts (action list|diff, readOnlyHint). - YAML OpenAPI/AsyncAPI now go through a bounded YAML-subset reader and the same decoder as JSON, so both spellings yield identical deltas. Anchors, aliases, tags, merge keys, duplicate keys and multi-document files are reported as contract-parse-failed instead of guessed. - A contract readable on one side and unparseable on the other is now an explicit "contract-unavailable" change with unknown compatibility. - GraphQL/Protobuf/SQL files the scanner does not sample are read in full for contracts, and contractSourcesFromRepo reports them as incomplete rather than parsing an empty sample. - Feature catalog entry (preview), artifact detection for contracts output, rebuilt action bundle. Co-Authored-By: Claude Opus 5.5 --- packages/action/dist/index.mjs | 13 + packages/cli/src/cli-runner.ts | 11 + packages/cli/src/contracts-command.ts | 234 +++++++++++ packages/cli/src/mcp.ts | 55 ++- packages/cli/test/cli-runner.test.ts | 4 +- packages/cli/test/contracts-command.test.ts | 332 +++++++++++++++ packages/cli/test/mcp.test.ts | 71 +++- packages/core/src/architecture-history.ts | 10 +- packages/core/src/artifacts.ts | 8 + packages/core/src/contracts-repository.ts | 137 +++++++ packages/core/src/contracts.ts | 130 +++--- packages/core/src/feature-catalog.ts | 3 +- packages/core/src/index.ts | 2 + packages/core/src/yaml-subset.ts | 381 ++++++++++++++++++ .../core/test/contracts-repository.test.ts | 108 +++++ packages/core/test/contracts.test.ts | 141 ++++++- 16 files changed, 1567 insertions(+), 73 deletions(-) create mode 100644 packages/cli/src/contracts-command.ts create mode 100644 packages/cli/test/contracts-command.test.ts create mode 100644 packages/core/src/contracts-repository.ts create mode 100644 packages/core/src/yaml-subset.ts create mode 100644 packages/core/test/contracts-repository.test.ts diff --git a/packages/action/dist/index.mjs b/packages/action/dist/index.mjs index fc2ef17d..fa3c41c5 100644 --- a/packages/action/dist/index.mjs +++ b/packages/action/dist/index.mjs @@ -3075,6 +3075,11 @@ function fixMapArtifactKind(file) { } if (candidate.capabilityListVersion === 1 && Array.isArray(candidate.capabilities)) return "capability-list-json"; + if (candidate.contractListVersion === 1 && isRecord2(candidate.inventory)) + return "contract-list-json"; + if (candidate.contractDiffVersion === 1 && isRecord2(candidate.from) && isRecord2(candidate.to) && isRecord2(candidate.comparison)) { + return "contract-diff-json"; + } if ((candidate.reportVersion === void 0 || candidate.reportVersion === 1) && typeof candidate.summary === "string" && Array.isArray(candidate.contextFiles) && Array.isArray(candidate.testRoutes) && Array.isArray(candidate.risks) && Array.isArray(candidate.changedFiles) && Array.isArray(candidate.diagnostics)) return "report-json"; if (candidate.contextVersion === 1 && typeof candidate.task === "string" && typeof candidate.budgetTokens === "number" && candidate.tokenEstimate === "utf8-bytes-divided-by-4" && Array.isArray(candidate.snippets) && Array.isArray(candidate.omitted)) @@ -9469,6 +9474,14 @@ function canonicalize2(value) { return JSON.stringify(value); } +// packages/core/dist/contracts-repository.js +import { execFile as execFile4 } from "node:child_process"; +import { promisify as promisify4 } from "node:util"; +var exec4 = promisify4(execFile4); +var MAX_CONTRACT_BYTES = 2 * 1024 * 1024; +var MAX_TREE_BYTES2 = 32 * 1024 * 1024; +var MAX_TOTAL_BYTES = 64 * 1024 * 1024; + // packages/action/src/annotations.ts async function runAnnotationAction(input, repoRoot, allowWrite) { if (Buffer.byteLength(input, "utf8") > 32768) throw new Error("annotation-request exceeds 32 KiB."); diff --git a/packages/cli/src/cli-runner.ts b/packages/cli/src/cli-runner.ts index 66feda9a..19d9cfb6 100644 --- a/packages/cli/src/cli-runner.ts +++ b/packages/cli/src/cli-runner.ts @@ -113,6 +113,7 @@ Usage: fixmap migrate --input migration.json --format markdown 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 fixmap supply-chain --input supply-chain.json fixmap runtime --input runtime.json fixmap sandbox --request sandbox.json --execute-declared-command @@ -139,6 +140,7 @@ Commands: migrate Preview: Build a dependency-ordered, review-only migration plan 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 supply-chain Preview: Import normalized external scanner and SBOM evidence runtime Preview: Map redaction-reviewed runtime evidence to exact files sandbox Preview: Run one explicitly consented command in an isolated container @@ -548,6 +550,15 @@ export async function runCli(args: string[], dependencies: CliDependencies = {}) }); } + if (args[0] === "contracts") { + const { runContractsCommand } = await import("./contracts-command.js"); + return runContractsCommand(args.slice(1), { + stdout, + stderr, + ...(dependencies.writeReport ? { writeOutput: dependencies.writeReport } : {}) + }); + } + if (args[0] === "supply-chain") { const { runSupplyChainCommand } = await import("./supply-chain-command.js"); return runSupplyChainCommand(args.slice(1), { diff --git a/packages/cli/src/contracts-command.ts b/packages/cli/src/contracts-command.ts new file mode 100644 index 00000000..194e78a5 --- /dev/null +++ b/packages/cli/src/contracts-command.ts @@ -0,0 +1,234 @@ +import { lstat, readFile, realpath, stat, writeFile } from "node:fs/promises"; +import { homedir } from "node:os"; +import { isAbsolute, relative, resolve, sep } from "node:path"; +import { + compareContractRefs, + inventoryWorkingTreeContracts, + isFixMapArtifact, + scanRepo, + type ContractChange, + type ContractDiagnostic, + type ContractInventory, + type ContractRefComparison +} from "@aryam/fixmap-core"; + +export const CONTRACTS_USAGE = `Usage: + fixmap contracts [--repo ] [--format markdown|json] [--output ] [--no-cache] + fixmap contracts diff .. [--repo ] [--format markdown|json] [--output ] + +Lists OpenAPI, AsyncAPI, GraphQL, Protobuf, JSON Schema, and SQL migration contracts in the +working tree, or compares them at two exact Git refs through Git objects without checking out +either ref or changing the worktree. Changes are classified as breaking, unknown, or compatible +with before/after fingerprints. Unreadable or unparseable contracts are reported, never skipped. +`; + +type Format = "markdown" | "json"; +type CommandIO = { + stdout?: (text: string) => void; + stderr?: (text: string) => void; + writeOutput?: (path: string, contents: string) => Promise; +}; + +export type ContractList = { contractListVersion: 1; inventory: ContractInventory }; + +export async function runContractsCommand(args: string[], io: CommandIO = {}): 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(CONTRACTS_USAGE); + return 0; + } + const isDiff = args[0] === "diff"; + let options: Options; + try { + options = parseOptions(isDiff ? args.slice(1) : args, isDiff); + } catch (error) { + stderr(`${message(error)}\n\n${CONTRACTS_USAGE}`); + return 1; + } + try { + const repoRoot = await repositoryRoot(options.repo); + if (options.output) await assertOutputSafe(repoRoot, options.output); + let rendered: string; + if (options.range) { + const result = await compareContractRefs({ repoRoot, fromRef: options.range.from, toRef: options.range.to }); + rendered = options.format === "json" ? `${JSON.stringify(result, null, 2)}\n` : renderContractDiffMarkdown(result); + } else { + const repo = await scanRepo({ repoRoot, useCache: !options.noCache }); + const scanError = repo.diagnostics.find((diagnostic) => diagnostic.severity === "error"); + if (scanError) throw new Error(scanError.message); + const list: ContractList = { contractListVersion: 1, inventory: await inventoryWorkingTreeContracts(repo) }; + rendered = options.format === "json" ? `${JSON.stringify(list, null, 2)}\n` : renderContractListMarkdown(list); + } + if (options.output) await (io.writeOutput ?? ((path, contents) => writeFile(path, contents, "utf8")))(options.output, rendered); + else stdout(rendered); + return 0; + } catch (error) { + stderr(`${contractsError(options.repo, error)}\n`); + return 1; + } +} + +export function renderContractListMarkdown(list: ContractList): string { + const { surfaces, diagnostics } = list.inventory; + const lines = [ + "# FixMap Contracts", + "", + surfaces.length === 0 + ? "No supported contract surfaces were found in the working tree." + : `${surfaces.length} contract surface${surfaces.length === 1 ? "" : "s"} in the working tree.`, + "", + "## Surfaces", + "" + ]; + if (surfaces.length === 0) lines.push("- None found."); + else { + lines.push("| Path | Kind | Name | Version | Entries | Fingerprint |", "| --- | --- | --- | --- | --- | --- |"); + for (const surface of surfaces) { + lines.push(`| ${cell(surface.path)} | ${surface.kind} | ${cell(surface.name)} | ${surface.version ? cell(surface.version) : "-"} | ${surface.entries.length} | ${cell(surface.sourceFingerprint)} |`); + } + } + lines.push("", ...diagnosticLines(diagnostics)); + lines.push("> Read-only inventory. FixMap parsed contract text locally and did not execute repository code."); + return `${lines.join("\n")}\n`; +} + +export function renderContractDiffMarkdown(result: ContractRefComparison): string { + const { comparison } = result; + const lines = [ + "# FixMap Contract Diff", + "", + `From: \`${result.from.requestedRef}\` at \`${result.from.commit}\``, + `To: \`${result.to.requestedRef}\` at \`${result.to.commit}\``, + "", + comparison.summary, + "" + ]; + for (const compatibility of ["breaking", "unknown", "compatible"] as const) { + const changes = comparison.changes.filter((change) => change.compatibility === compatibility); + lines.push(`## ${compatibility[0]!.toUpperCase()}${compatibility.slice(1)}`, ""); + if (changes.length === 0) lines.push("- None."); + for (const change of changes) lines.push(changeLine(change)); + lines.push(""); + } + lines.push(...diagnosticLines(comparison.diagnostics)); + lines.push("> Read-only historical comparison. FixMap read committed Git objects and did not checkout a ref or change the worktree."); + return `${lines.join("\n")}\n`; +} + +function changeLine(change: ContractChange): string { + const before = change.evidence.beforeFingerprint ? `\`${change.evidence.beforeFingerprint}\`` : "absent"; + const after = change.evidence.afterFingerprint ? `\`${change.evidence.afterFingerprint}\`` : "absent"; + return `- \`${change.path}\` (${change.contractKind}): ${change.reason} Fingerprints: ${before} -> ${after}.`; +} + +function diagnosticLines(diagnostics: readonly ContractDiagnostic[]): string[] { + if (diagnostics.length === 0) return []; + return ["## Diagnostics", "", ...diagnostics.map((diagnostic) => `- \`${diagnostic.path}\` (${diagnostic.code}): ${diagnostic.message}`), ""]; +} + +function cell(value: string): string { + return `\`${value.replace(/[|`\r\n]/g, " ")}\``; +} + +type Options = { + repo: string; + format: Format; + noCache: boolean; + output?: string; + range?: { from: string; to: string }; +}; + +function parseOptions(args: string[], isDiff: boolean): Options { + const rest = [...args]; + let rangeText: string | undefined; + if (isDiff) { + if (!rest[0] || rest[0].startsWith("--")) throw new Error("contracts diff requires ..."); + rangeText = rest.shift(); + } + const values = new Map(); + let noCache = false; + for (let index = 0; index < rest.length; index += 1) { + const raw = rest[index]!; + if (raw === "--no-cache") { + if (isDiff) throw new Error("--no-cache does not apply to immutable Git-ref contract diffs."); + if (noCache) throw new Error("Pass --no-cache only once."); + noCache = true; + continue; + } + const equals = /^(--[a-z-]+)=(.*)$/s.exec(raw); + const flag = equals?.[1] ?? raw; + if (!["--repo", "--format", "--output"].includes(flag)) throw new Error(`Unknown contracts option: ${raw}`); + if (values.has(flag)) throw new Error(`Pass ${flag} only once.`); + const value = equals?.[2] ?? rest[++index]; + if (typeof value !== "string" || !value.trim() || (!equals && value.startsWith("--"))) throw new Error(`${flag} requires a value.`); + if (/[\0\r\n]/.test(value)) throw new Error(`${flag} must be a single-line value.`); + values.set(flag, value.trim()); + } + const format = (values.get("--format") ?? "markdown").toLowerCase(); + if (format !== "markdown" && format !== "json") throw new Error("--format must be markdown or json."); + const repo = expandHome(values.get("--repo") ?? process.cwd()); + if (/^[a-z][a-z0-9+.-]*:\/\//i.test(repo)) throw new Error("contracts requires a local checkout, not a remote URL."); + const output = values.get("--output"); + return { + repo, + format, + noCache, + ...(output ? { output: expandHome(output) } : {}), + ...(rangeText !== undefined ? { range: parseRange(rangeText) } : {}) + }; +} + +function parseRange(value: string): { from: string; to: string } { + const index = value.indexOf(".."); + if (value.includes("...")) throw new Error("contracts diff compares two exact refs; use .., not a three-dot merge-base range."); + if (index <= 0 || index + 2 >= value.length || value.indexOf("..", index + 2) !== -1) throw new Error("contracts diff range must be ..."); + const from = value.slice(0, index).trim(); + const to = value.slice(index + 2).trim(); + if (!from || !to || from.length > 500 || to.length > 500 || /[\0\r\n]/.test(value)) { + throw new Error("contracts diff refs must be bounded single-line values."); + } + if (from.startsWith("-") || to.startsWith("-")) throw new Error("contracts diff refs cannot start with '-'."); + return { from, to }; +} + +async function repositoryRoot(input: string): Promise { + const root = resolve(input); + const info = await stat(root).catch(() => undefined); + if (!info?.isDirectory()) throw new Error("not-directory"); + return realpath(root); +} + +/** Refuses to overwrite a repository file unless it is a prior FixMap artifact. */ +async function assertOutputSafe(repoRoot: string, output: string): Promise { + const absolute = resolve(output); + const outputRelative = relative(repoRoot, absolute); + if (!outputRelative || outputRelative === ".." || outputRelative.startsWith(`..${sep}`) || isAbsolute(outputRelative)) return; + const info = await lstat(absolute).catch(() => undefined); + if (!info) return; + const path = outputRelative.replace(/\\/g, "/"); + if (!info.isFile() || info.isSymbolicLink() || info.nlink > 1 || info.size > 4 * 1024 * 1024 || + !isFixMapArtifact({ path, textSample: await readFile(absolute, "utf8"), textSampleComplete: true })) { + throw new Error(`--output refuses to overwrite repository file ${path}; choose a new path or a prior FixMap contracts artifact.`); + } +} + +function contractsError(repo: string, error: unknown): string { + const text = message(error); + if (text === "not-directory") return `Contracts repository "${repo}" does not exist or is not a directory.`; + if (text.includes("Could not resolve Git ref")) { + return `Could not resolve one of the requested Git refs in "${repo}". Confirm both refs exist and the path is a Git checkout.`; + } + if (text.startsWith("--output refuses")) return text; + return `Could not read contracts in "${repo}": ${text.replace(/Command failed:[\s\S]*/i, "Git could not read the requested committed state.")}`; +} + +function message(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +function expandHome(value: string): string { + if (value === "~") return homedir(); + if (value.startsWith("~/") || value.startsWith("~\\")) return resolve(homedir(), value.slice(2)); + return value; +} diff --git a/packages/cli/src/mcp.ts b/packages/cli/src/mcp.ts index 70326eb1..8f4b235e 100644 --- a/packages/cli/src/mcp.ts +++ b/packages/cli/src/mcp.ts @@ -49,6 +49,7 @@ import { parseRuntimeInput, renderRuntimeMarkdown } from "./runtime-command.js"; import { runWorkspaceCommand } from "./workspace-command.js"; import { runChangeScopeCommand } from "./change-scope-command.js"; import { runCapabilitiesCommand, runCapabilityCommand } from "./capability-command.js"; +import { runContractsCommand } from "./contracts-command.js"; import { buildReportForRepository, isSafeGitRefName, @@ -407,6 +408,27 @@ const HISTORY_TOOL = { } }; +const CONTRACTS_TOOL = { + name: "fixmap_contracts", + title: "FixMap contracts", + description: + "Preview (may change before v0.10.0): List OpenAPI, AsyncAPI, GraphQL, Protobuf, JSON Schema, and SQL migration contracts in the working tree (action list), " + + "or compare them at two exact Git refs through Git objects without checking out either ref or changing the worktree (action diff). " + + "Each change is breaking, unknown, or compatible with before/after fingerprints; unparseable contracts are reported as diagnostics.", + annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }, + inputSchema: { + type: "object" as const, + properties: { + action: { type: "string", enum: ["list", "diff"], description: "list (default) inventories the working tree; diff compares from..to" }, + from: { type: "string", description: "Earlier exact Git ref; required for diff" }, + to: { type: "string", description: "Later exact Git ref; required for diff" }, + repo: { type: "string", description: "Local checkout path (defaults to the MCP server repository)" }, + format: { type: "string", description: "Output format: markdown (default) or json, case-insensitive" } + }, + additionalProperties: false + } +}; + const SUPPLY_CHAIN_TOOL = { name: "fixmap_supply_chain", title: "FixMap supply chain", @@ -516,7 +538,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, 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] })); server.setRequestHandler(CallToolRequestSchema, async (request) => { @@ -785,6 +807,37 @@ export function createFixMapMcpServer( : `Could not compare historical architecture in "${repoRoot}".` }] }; } } + if (request.params.name === CONTRACTS_TOOL.name) { + const record = (request.params.arguments ?? {}) as Record; + const invalid = (text: string) => ({ isError: true, content: [{ type: "text", text: `Invalid arguments: ${text}` }] }); + const unknown = Object.keys(record).filter((key) => !["action", "from", "to", "repo", "format"].includes(key)); + if (unknown.length > 0) return invalid(`unknown argument${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}.`); + if (record.action !== undefined && record.action !== "list" && record.action !== "diff") return invalid('"action" must be "list" or "diff".'); + const action = record.action ?? "list"; + for (const key of ["from", "to"] as const) { + const value = record[key]; + if (value !== undefined && (typeof value !== "string" || !value.trim() || value.length > 500 || /[\0\r\n]/.test(value) || value.includes("..") || value.trim().startsWith("-"))) { + return invalid(`"${key}" must be a bounded single-line Git ref.`); + } + } + if (action === "diff" && (record.from === undefined || record.to === undefined)) return invalid('action "diff" requires both "from" and "to".'); + if (action === "list" && (record.from !== undefined || record.to !== undefined)) return invalid('"from" and "to" apply only to action "diff".'); + if (record.repo !== undefined && (typeof record.repo !== "string" || !record.repo.trim() || /[\0\r\n]/.test(record.repo))) { + return invalid('"repo" must be a non-empty local path.'); + } + if (typeof record.repo === "string" && /^[a-z][a-z0-9+.-]*:\/\//i.test(record.repo.trim())) return invalid('"repo" must be a local checkout.'); + const format = normalizeFormat(record.format); + if (!format.success) return invalid(format.message); + const commandArgs = [ + ...(action === "diff" ? ["diff", `${String(record.from).trim()}..${String(record.to).trim()}`] : []), + "--repo", typeof record.repo === "string" ? record.repo.trim() : defaultRepo, + "--format", format.value ?? "markdown" + ]; + const stdout: string[] = []; + const stderr: string[] = []; + const exitCode = await runContractsCommand(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("").trim() }] }; + } if (request.params.name === SUPPLY_CHAIN_TOOL.name) { const record = request.params.arguments as Record | undefined; const unknown = Object.keys(record ?? {}).filter((key) => !["input", "format"].includes(key)); diff --git a/packages/cli/test/cli-runner.test.ts b/packages/cli/test/cli-runner.test.ts index 7920fb22..9a959b6a 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", "Product capabilities", "Cross-repository workspace", "Repository Q&A", "Migration planning", - "Reverse documentation", "Architecture history", "Supply-chain evidence", "Runtime evidence", "Evidence import", "Execution sandbox", + "Reverse documentation", "Architecture history", "Contract Guardian", "Supply-chain evidence", "Runtime evidence", "Evidence import", "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", "editor", "capability", "capabilities", "workspace", "ask", "migrate", "reverse-docs", "history", "supply-chain", "runtime", "sandbox"]) { + for (const command of ["change-scope", "editor", "capability", "capabilities", "workspace", "ask", "migrate", "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/contracts-command.test.ts b/packages/cli/test/contracts-command.test.ts new file mode 100644 index 00000000..f3172055 --- /dev/null +++ b/packages/cli/test/contracts-command.test.ts @@ -0,0 +1,332 @@ +import { execFile } from "node:child_process"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { promisify } from "node:util"; +import { afterEach, describe, expect, it } from "vitest"; +import { runCli } from "../src/cli-runner.js"; + +const exec = promisify(execFile); +const GIT_TEST_TIMEOUT = process.platform === "win32" ? 60_000 : 20_000; +const roots: string[] = []; + +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }))); +}); + +async function git(root: string, ...args: string[]): Promise { + return (await exec("git", args, { cwd: root })).stdout; +} + +async function write(root: string, files: Record): Promise { + for (const [path, content] of Object.entries(files)) { + await mkdir(dirname(join(root, path)), { recursive: true }); + await writeFile(join(root, path), content, "utf8"); + } +} + +async function repository(): Promise { + const root = await mkdtemp(join(tmpdir(), "fixmap-contracts-cli-")); + roots.push(root); + await git(root, "init", "--quiet"); + await git(root, "config", "user.email", "fixmap@example.test"); + await git(root, "config", "user.name", "FixMap Test"); + await git(root, "config", "core.autocrlf", "false"); + return root; +} + +async function commit(root: string, files: Record, message: string, remove: string[] = []): Promise { + await write(root, files); + for (const path of remove) await git(root, "rm", "--quiet", path); + await git(root, "add", "-A"); + await git(root, "commit", "--quiet", "--allow-empty", "-m", message); + return (await git(root, "rev-parse", "HEAD")).trim(); +} + +function capture() { + const stdout: string[] = []; + const stderr: string[] = []; + return { + stdout, + stderr, + dependencies: { stdout: (text: string) => stdout.push(text), stderr: (text: string) => stderr.push(text) } + }; +} + +async function contractsJson(args: string[]) { + const io = capture(); + const exitCode = await runCli(["contracts", ...args, "--format", "json"], io.dependencies); + expect(io.stderr.join("")).toBe(""); + expect(exitCode).toBe(0); + return JSON.parse(io.stdout.join("")); +} + +const OPENAPI_V1 = { + openapi: "3.1.0", + info: { title: "Users" }, + paths: { "/users": { get: {}, post: { parameters: [{ name: "trace", in: "header", required: false, schema: { type: "string" } }] } } }, + components: { schemas: { User: { type: "object", properties: { id: { type: "string" } } } } } +}; +const OPENAPI_YAML_V1 = `openapi: 3.1.0 +info: + title: Users +paths: + /users: + get: {} + post: + parameters: + - name: trace + in: header + required: false + schema: + type: string +components: + schemas: + User: + type: object + properties: + id: { type: string } +`; +const OPENAPI_V2 = { + openapi: "3.1.0", + info: { title: "Users" }, + paths: { "/users": { post: { parameters: [ + { name: "trace", in: "header", required: false, schema: { type: "string" } }, + { name: "tenant", in: "header", required: true, schema: { type: "string" } } + ] } } }, + components: { schemas: { User: { type: "object", properties: { id: { type: "string" }, nickname: { type: "string" } } } } } +}; +const OPENAPI_YAML_V2 = `openapi: 3.1.0 +info: + title: Users +paths: + /users: + post: + parameters: + - name: trace + in: header + required: false + schema: + type: string + - name: tenant + in: header + required: true + schema: { type: string } +components: + schemas: + User: + type: object + properties: + id: { type: string } + nickname: + type: string +`; + +describe("contracts command", () => { + it("lists every supported working-tree contract with kind, version, and exact fingerprint", async () => { + const root = await repository(); + await commit(root, { + "api/openapi.yaml": OPENAPI_YAML_V1, + "events/asyncapi.json": JSON.stringify({ asyncapi: "2.6.0", info: { title: "Events" }, channels: { "user.created": { publish: {} } } }), + "schema/schema.graphql": "type Query { user(id: ID!): User }\ntype User { id: ID! }\n", + "proto/user.proto": "syntax = \"proto3\";\nmessage User { string id = 1; }\n", + "schemas/user.schema.json": JSON.stringify({ $schema: "https://json-schema.org/draft/2020-12/schema", title: "User", properties: { id: { type: "string" } } }), + "db/migrations/001_users.sql": "CREATE TABLE users (id text);\n", + "src/index.ts": "export const ok = true;\n" + }, "contracts"); + + const list = await contractsJson(["--repo", root, "--no-cache"]); + expect(list.contractListVersion).toBe(1); + expect(list.inventory.diagnostics).toEqual([]); + expect(list.inventory.surfaces.map((surface: { kind: string; path: string; version?: string }) => [surface.kind, surface.path, surface.version])).toEqual([ + ["asyncapi", "events/asyncapi.json", "2.6.0"], + ["graphql", "schema/schema.graphql", undefined], + ["json-schema", "schemas/user.schema.json", "https://json-schema.org/draft/2020-12/schema"], + ["migration", "db/migrations/001_users.sql", undefined], + ["openapi", "api/openapi.yaml", "3.1.0"], + ["protobuf", "proto/user.proto", "proto3"] + ]); + for (const surface of list.inventory.surfaces) { + expect(surface.sourceFingerprint).toMatch(/^worktree:[a-f0-9]{64}$/); + // GraphQL, Protobuf, and SQL are read in full rather than reported as empty surfaces. + expect(surface.entries.length).toBeGreaterThan(0); + } + + const markdown = capture(); + expect(await runCli(["contracts", "--repo", root], markdown.dependencies)).toBe(0); + const text = markdown.stdout.join(""); + expect(text).toMatch(/^# FixMap Contracts\n/); + expect(text).toContain("6 contract surfaces in the working tree."); + expect(text).toContain("| `api/openapi.yaml` | openapi | `Users` | `3.1.0` |"); + }, GIT_TEST_TIMEOUT); + + it("reports a repository with no contracts without failing", async () => { + const root = await repository(); + await commit(root, { "src/index.ts": "export const ok = true;\n", "package.json": "{\"name\":\"plain\"}\n" }, "plain"); + const list = await contractsJson(["--repo", root]); + expect(list.inventory).toEqual({ inventoryVersion: 1, surfaces: [], diagnostics: [] }); + const io = capture(); + expect(await runCli(["contracts", "--repo", root], io.dependencies)).toBe(0); + expect(io.stdout.join("")).toContain("No supported contract surfaces were found in the working tree."); + }, GIT_TEST_TIMEOUT); + + it("reports malformed specs as diagnostics instead of skipping them", async () => { + const root = await repository(); + await commit(root, { + "openapi.yaml": "openapi: 3.1.0\npaths:\n /a: &shared\n get: {}\n /b: *shared\n", + "api/openapi.json": "{ \"openapi\": \"3.1.0\", ", + "schema.graphql": "this is not GraphQL SDL\n" + }, "broken"); + const list = await contractsJson(["--repo", root]); + expect(list.inventory.surfaces).toEqual([]); + expect(list.inventory.diagnostics.map((diagnostic: { path: string; code: string }) => [diagnostic.path, diagnostic.code])).toEqual([ + ["api/openapi.json", "contract-parse-failed"], + ["openapi.yaml", "contract-parse-failed"], + ["schema.graphql", "contract-parse-failed"] + ]); + expect(list.inventory.diagnostics[1].message).toContain("anchors, aliases, and tags are not supported"); + }, GIT_TEST_TIMEOUT); + + it("diffs exact refs into breaking, unknown, and compatible changes without changing HEAD or git status", async () => { + const root = await repository(); + const before = await commit(root, { + "api/openapi.json": JSON.stringify(OPENAPI_V1, null, 2), + "schema.graphql": "type Query { ok: Boolean }\n", + "db/migrations/001.sql": "CREATE TABLE users (id text);\n" + }, "before"); + const after = await commit(root, { + "api/openapi.json": JSON.stringify(OPENAPI_V2, null, 2), + "schema.graphql": "this is not GraphQL SDL\n", + "db/migrations/001.sql": "CREATE TABLE users (id text, nickname text);\n", + "proto/new.proto": "message Added { string id = 1; }\n" + }, "after"); + // Uncommitted edits must survive and must not leak into the committed comparison. + await writeFile(join(root, "api/openapi.json"), "{ \"dirty\": true }", "utf8"); + const headBefore = await git(root, "rev-parse", "HEAD"); + const statusBefore = await git(root, "status", "--porcelain=v1"); + + const diff = await contractsJson(["diff", `${before}..${after}`, "--repo", root]); + expect(diff.contractDiffVersion).toBe(1); + expect(diff.from).toEqual({ requestedRef: before, commit: before }); + expect(diff.to).toEqual({ requestedRef: after, commit: after }); + const changes = diff.comparison.changes as Array & { evidence: Record }>; + expect(changes).toEqual(expect.arrayContaining([ + expect.objectContaining({ path: "api/openapi.json", entry: "operation:GET /users", compatibility: "breaking" }), + expect.objectContaining({ path: "api/openapi.json", entry: "argument:POST /users:header:tenant", compatibility: "breaking" }), + expect.objectContaining({ path: "api/openapi.json", entry: "field:User.nickname", compatibility: "compatible" }), + expect.objectContaining({ path: "schema.graphql", change: "contract-unavailable", compatibility: "unknown" }), + expect.objectContaining({ path: "db/migrations/001.sql", change: "entry-removed", compatibility: "unknown" }), + expect.objectContaining({ path: "proto/new.proto", change: "contract-added", compatibility: "compatible" }) + ])); + const severity = { breaking: 0, unknown: 1, compatible: 2 } as Record; + expect(changes.map((change) => severity[change.compatibility as string])).toEqual( + [...changes.map((change) => severity[change.compatibility as string])].sort((a, b) => a! - b!) + ); + const tenant = changes.find((change) => change.entry === "argument:POST /users:header:tenant")!; + expect(tenant.evidence.beforeFingerprint).toMatch(/^git:[a-f0-9]{40}$/); + expect(tenant.evidence.afterFingerprint).toMatch(/^git:[a-f0-9]{40}$/); + expect(tenant.evidence.beforeFingerprint).not.toBe(tenant.evidence.afterFingerprint); + expect(diff.comparison.diagnostics).toContainEqual(expect.objectContaining({ path: "schema.graphql", code: "contract-parse-failed" })); + + const markdown = capture(); + expect(await runCli(["contracts", "diff", `${before}..${after}`, "--repo", root], markdown.dependencies)).toBe(0); + const text = markdown.stdout.join(""); + expect(text).toContain(`From: \`${before}\` at \`${before}\``); + expect(text).toMatch(/## Breaking\n\n- `api\/openapi\.json` \(openapi\): .* Fingerprints: `git:[a-f0-9]{40}` -> `git:[a-f0-9]{40}`\./); + expect(text).toContain("## Unknown"); + expect(text).toContain("## Compatible"); + expect(text).toContain("did not checkout a ref or change the worktree"); + + expect(await git(root, "rev-parse", "HEAD")).toBe(headBefore); + expect(await git(root, "status", "--porcelain=v1")).toBe(statusBefore); + expect(await readFile(join(root, "api/openapi.json"), "utf8")).toBe("{ \"dirty\": true }"); + }, GIT_TEST_TIMEOUT); + + it("produces the same deltas for YAML and JSON spellings of one OpenAPI change", async () => { + const root = await repository(); + const before = await commit(root, { "json/openapi.json": JSON.stringify(OPENAPI_V1), "yaml/openapi.yaml": OPENAPI_YAML_V1 }, "before"); + const after = await commit(root, { "json/openapi.json": JSON.stringify(OPENAPI_V2), "yaml/openapi.yaml": OPENAPI_YAML_V2 }, "after"); + const diff = await contractsJson(["diff", `${before}..${after}`, "--repo", root]); + const shape = (prefix: string) => (diff.comparison.changes as Array>) + .filter((change) => String(change.path).startsWith(prefix)) + .map(({ change, compatibility, entry, before: was, after: now, reason }) => ({ change, compatibility, entry, was, now, reason })); + expect(shape("json/").map((change) => [change.entry, change.compatibility])).toEqual([ + ["argument:POST /users:header:tenant", "breaking"], + ["operation:GET /users", "breaking"], + ["field:User.nickname", "compatible"] + ]); + expect(shape("yaml/")).toEqual(shape("json/")); + expect(diff.comparison.diagnostics).toEqual([]); + }, GIT_TEST_TIMEOUT); + + it("reports a contract removed between refs as breaking and an identical range as unchanged", async () => { + const root = await repository(); + const before = await commit(root, { "schema.graphql": "type Query { ok: Boolean }\n", "README.md": "x\n" }, "before"); + const after = await commit(root, {}, "after", ["schema.graphql"]); + const removed = await contractsJson(["diff", `${before}..${after}`, "--repo", root]); + expect(removed.comparison.changes).toEqual([expect.objectContaining({ change: "contract-removed", compatibility: "breaking" })]); + const same = await contractsJson(["diff", `${after}..HEAD`, "--repo", root]); + expect(same.comparison).toMatchObject({ summary: "No supported contract surface changed.", changes: [] }); + }, GIT_TEST_TIMEOUT); + + it("fails clearly on refs that do not exist and on non-Git directories", async () => { + const root = await repository(); + await commit(root, { "schema.graphql": "type Query { ok: Boolean }\n" }, "only"); + const missing = capture(); + expect(await runCli(["contracts", "diff", "HEAD..does-not-exist", "--repo", root], missing.dependencies)).toBe(1); + expect(missing.stderr.join("")).toContain("Could not resolve one of the requested Git refs"); + expect(missing.stdout).toEqual([]); + + const plain = await mkdtemp(join(tmpdir(), "fixmap-contracts-plain-")); + roots.push(plain); + const notGit = capture(); + expect(await runCli(["contracts", "diff", "HEAD~1..HEAD", "--repo", plain], notGit.dependencies)).toBe(1); + expect(notGit.stderr.join("")).toContain("Could not resolve one of the requested Git refs"); + + const absent = capture(); + expect(await runCli(["contracts", "--repo", join(plain, "missing")], absent.dependencies)).toBe(1); + expect(absent.stderr.join("")).toContain("does not exist or is not a directory"); + }, GIT_TEST_TIMEOUT); + + it("validates arguments strictly", async () => { + const cases: Array<[string[], string]> = [ + [["diff"], "contracts diff requires ..."], + [["diff", "main"], "contracts diff range must be ..."], + [["diff", "main...HEAD"], "not a three-dot merge-base range"], + [["diff", "..HEAD"], "contracts diff range must be ..."], + [["diff", "a..b..c"], "contracts diff range must be ..."], + [["diff", "--upload-pack=x..HEAD"], "contracts diff requires ..."], + [["diff", "-x..HEAD"], "cannot start with '-'"], + [["diff", "a..b", "--no-cache"], "--no-cache does not apply"], + [["--format", "xml"], "--format must be markdown or json."], + [["--bogus"], "Unknown contracts option: --bogus"], + [["--repo", "https://example.com/repo.git"], "local checkout"], + [["--repo", "a", "--repo", "b"], "Pass --repo only once."], + [["--output"], "--output requires a value."] + ]; + for (const [args, expected] of cases) { + const io = capture(); + expect(await runCli(["contracts", ...args], io.dependencies)).toBe(1); + expect(io.stderr.join("")).toContain(expected); + } + const help = capture(); + expect(await runCli(["contracts", "--help"], help.dependencies)).toBe(0); + expect(help.stdout.join("")).toContain("fixmap contracts diff .."); + }); + + it("refuses to overwrite a repository file but replaces its own prior artifact", async () => { + const root = await repository(); + await commit(root, { "schema.graphql": "type Query { ok: Boolean }\n", "notes.md": "keep me\n" }, "only"); + const refused = capture(); + expect(await runCli(["contracts", "--repo", root, "--output", join(root, "notes.md")], refused.dependencies)).toBe(1); + expect(refused.stderr.join("")).toContain("--output refuses to overwrite repository file notes.md"); + expect(await readFile(join(root, "notes.md"), "utf8")).toBe("keep me\n"); + + const target = join(root, "contracts.json"); + for (let run = 0; run < 2; run += 1) { + const io = capture(); + expect(await runCli(["contracts", "--repo", root, "--format", "json", "--output", target], io.dependencies)).toBe(0); + } + expect(JSON.parse(await readFile(target, "utf8")).contractListVersion).toBe(1); + }, GIT_TEST_TIMEOUT); +}); diff --git a/packages/cli/test/mcp.test.ts b/packages/cli/test/mcp.test.ts index 8c444a51..74199cd2 100644 --- a/packages/cli/test/mcp.test.ts +++ b/packages/cli/test/mcp.test.ts @@ -195,7 +195,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_history", "fixmap_migrate", + "fixmap_ask", "fixmap_capability", "fixmap_change_scope", "fixmap_contracts", "fixmap_history", "fixmap_migrate", "fixmap_reverse_docs", "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"]) { @@ -393,7 +393,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_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" ]); const plan = tools.tools.find((tool) => tool.name === "fixmap_plan"); const verify = tools.tools.find((tool) => tool.name === "fixmap_verify"); @@ -653,6 +653,73 @@ describe("fixmap mcp server", () => { expect(comparison.drift.addedEdges).toContainEqual({ from: "a.ts", to: "b.ts" }); }, 20_000); + it("lists and diffs contracts through a read-only MCP tool without checkout", async () => { + const root = await mkdtemp(join(tmpdir(), "fixmap-mcp-contracts-")); + const git = async (...args: string[]) => (await promisify(execFile)("git", args, { cwd: root })).stdout; + try { + await git("init", "--quiet"); + await git("config", "user.email", "fixmap@example.test"); + await git("config", "user.name", "FixMap Test"); + await writeFile(join(root, "openapi.yaml"), "openapi: 3.1.0\npaths:\n /users:\n get: {}\n post: {}\n", "utf8"); + await git("add", "-A"); + await git("commit", "--quiet", "-m", "before"); + const before = (await git("rev-parse", "HEAD")).trim(); + await writeFile(join(root, "openapi.yaml"), "openapi: 3.1.0\npaths:\n /users:\n post: {}\n /health:\n get: {}\n", "utf8"); + await git("add", "-A"); + await git("commit", "--quiet", "-m", "after"); + const after = (await git("rev-parse", "HEAD")).trim(); + const statusBefore = await git("status", "--porcelain=v1"); + + const client = await connectClient(); + const tool = (await client.listTools()).tools.find((candidate) => candidate.name === "fixmap_contracts"); + expect(tool?.annotations).toMatchObject({ readOnlyHint: true, destructiveHint: false }); + expect(Object.keys(tool?.inputSchema.properties ?? {}).sort()).toEqual(["action", "format", "from", "repo", "to"]); + expect(tool?.inputSchema.additionalProperties).toBe(false); + + const listed = await client.callTool({ name: "fixmap_contracts", arguments: { repo: root, format: "JSON" } }); + expect(listed.isError).toBeFalsy(); + const list = JSON.parse((listed.content as Array<{ text: string }>)[0]!.text); + expect(list.inventory.surfaces).toEqual([expect.objectContaining({ kind: "openapi", path: "openapi.yaml", version: "3.1.0" })]); + + const diffed = await client.callTool({ name: "fixmap_contracts", arguments: { action: "diff", repo: root, from: before, to: after, format: "json" } }); + expect(diffed.isError).toBeFalsy(); + const diff = JSON.parse((diffed.content as Array<{ text: string }>)[0]!.text); + expect(diff.from.commit).toBe(before); + expect(diff.comparison.changes).toEqual([ + expect.objectContaining({ entry: "operation:GET /users", compatibility: "breaking" }), + expect.objectContaining({ entry: "operation:GET /health", compatibility: "compatible" }) + ]); + const markdown = await client.callTool({ name: "fixmap_contracts", arguments: { action: "diff", repo: root, from: before, to: after } }); + expect((markdown.content as Array<{ text: string }>)[0]!.text).toMatch(/^# FixMap Contract Diff\n/); + expect(await git("status", "--porcelain=v1")).toBe(statusBefore); + expect((await git("rev-parse", "HEAD")).trim()).toBe(after); + + const missing = await client.callTool({ name: "fixmap_contracts", arguments: { action: "diff", repo: root, from: before, to: "no-such-ref" } }); + expect(missing.isError).toBe(true); + expect((missing.content as Array<{ text: string }>)[0]!.text).toContain("Could not resolve one of the requested Git refs"); + + const invalid: Array<[Record, string]> = [ + [{ action: "remove" }, '"action" must be "list" or "diff"'], + [{ action: "diff", from: before }, 'requires both "from" and "to"'], + [{ from: before, to: after }, 'apply only to action "diff"'], + [{ action: "diff", from: "a..b", to: after }, '"from" must be a bounded single-line Git ref'], + [{ action: "diff", from: "--output=x", to: after }, '"from" must be a bounded single-line Git ref'], + [{ action: "diff", from: before, to: 7 }, '"to" must be a bounded single-line Git ref'], + [{ repo: "https://example.com/repo.git" }, '"repo" must be a local checkout'], + [{ repo: "" }, '"repo" must be a non-empty local path'], + [{ format: "xml" }, '"format" must be either'], + [{ noCache: true }, "unknown argument: noCache"] + ]; + for (const [args, expected] of invalid) { + const result = await client.callTool({ name: "fixmap_contracts", arguments: args }); + expect(result.isError).toBe(true); + expect((result.content as Array<{ text: string }>)[0]!.text).toContain(expected); + } + } finally { + await rm(root, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }); + } + }, 30_000); + it("imports normalized supply-chain evidence through MCP", async () => { const client = await connectClient(); const result = await client.callTool({ diff --git a/packages/core/src/architecture-history.ts b/packages/core/src/architecture-history.ts index 2fa9726a..d9fbb6ef 100644 --- a/packages/core/src/architecture-history.ts +++ b/packages/core/src/architecture-history.ts @@ -15,7 +15,7 @@ const MAX_TEXT_SAMPLE_BYTES = 64_000; const MAX_BATCH_BYTES = 64 * 1024 * 1024; const MAX_BATCH_OUTPUT_BYTES = MAX_BATCH_BYTES + 2 * 1024 * 1024; -type TreeEntry = { mode: string; oid: string; size: number; path: string }; +export type TreeEntry = { mode: string; oid: string; size: number; path: string }; export type HistoricalRepoMap = { requestedRef: string; @@ -120,13 +120,13 @@ export async function compareArchitectureRefs(input: { }; } -function validateRef(value: string): string { +export function validateRef(value: string): string { const ref = value.trim(); if (!ref || ref.length > MAX_REF_LENGTH || /[\0\r\n]/.test(ref)) throw new Error("Git ref must be a bounded single-line value."); return ref; } -async function resolveCommit(repoRoot: string, ref: string): Promise { +export async function resolveCommit(repoRoot: string, ref: string): Promise { try { const { stdout } = await exec("git", ["rev-parse", "--verify", "--end-of-options", `${ref}^{commit}`], { cwd: repoRoot, @@ -141,7 +141,7 @@ async function resolveCommit(repoRoot: string, ref: string): Promise { } } -function parseTree(value: string): TreeEntry[] { +export function parseTree(value: string): TreeEntry[] { return value.split("\0").flatMap((record): TreeEntry[] => { if (!record) return []; const tab = record.indexOf("\t"); @@ -153,7 +153,7 @@ function parseTree(value: string): TreeEntry[] { }); } -async function readBlobs(repoRoot: string, entries: readonly TreeEntry[]): Promise> { +export async function readBlobs(repoRoot: string, entries: readonly TreeEntry[]): Promise> { if (entries.length === 0) return new Map(); const uniqueOids = [...new Set(entries.map((entry) => entry.oid))]; const child = spawn("git", ["cat-file", "--batch"], { cwd: repoRoot, stdio: ["pipe", "pipe", "pipe"], windowsHide: true }); diff --git a/packages/core/src/artifacts.ts b/packages/core/src/artifacts.ts index 9b20a606..1df5aec0 100644 --- a/packages/core/src/artifacts.ts +++ b/packages/core/src/artifacts.ts @@ -11,6 +11,10 @@ export type FixMapArtifactKind = | "change-scope-json" | "change-scope-markdown" | "context-json" + | "contract-diff-json" + | "contract-diff-markdown" + | "contract-list-json" + | "contract-list-markdown" | "context-markdown" | "report-json" | "report-markdown" @@ -60,6 +64,10 @@ export function fixMapArtifactKind(file: Pick { + const root = await realpath(resolve(repo.root)); + const sources: ContractSource[] = []; + const diagnostics: ContractDiagnostic[] = []; + let totalBytes = 0; + for (const file of repo.files) { + const byPath = CONTRACT_PATH.test(file.path); + if (!byPath && !(STRUCTURED_EXTENSION.test(file.path) && isContractCandidate(file.path, file.textSample))) continue; + const absolute = resolve(root, file.path); + const inside = relative(root, absolute); + if (!inside || inside.startsWith(`..${sep}`) || inside === "..") continue; + let bytes: Buffer | undefined; + try { + const info = await lstat(absolute); + if (info.isFile() && info.size <= MAX_CONTRACT_BYTES && totalBytes + info.size <= MAX_TOTAL_BYTES) { + bytes = await readFile(absolute); + totalBytes += bytes.length; + } + } catch { + bytes = undefined; + } + const decoded = bytes ? decodeUtf8(bytes) : undefined; + if (bytes === undefined || decoded === undefined || bytes.length > MAX_CONTRACT_BYTES) { + diagnostics.push(unread(file.path)); + continue; + } + if (!byPath && !isContractCandidate(file.path, decoded)) continue; + sources.push({ path: file.path, content: decoded, fingerprint: `worktree:${createHash("sha256").update(bytes).digest("hex")}` }); + } + return inventoryContracts(sources, diagnostics); +} + +/** Inventories contracts at one exact commit through Git objects, without checkout. */ +export async function inventoryContractsAtRef(input: { repoRoot: string; ref: string }): Promise { + const repoRoot = resolve(input.repoRoot); + const requestedRef = validateRef(input.ref); + const commit = await resolveCommit(repoRoot, requestedRef); + const { stdout } = await exec("git", ["ls-tree", "-r", "-z", "-l", "--full-tree", commit, "--"], { + cwd: repoRoot, + encoding: "utf8", + maxBuffer: MAX_TREE_BYTES + }); + const candidates = parseTree(stdout) + .filter((entry) => entry.mode !== "120000" && entry.mode !== "160000") + .filter((entry) => CONTRACT_PATH.test(entry.path) || STRUCTURED_EXTENSION.test(entry.path)); + const diagnostics: ContractDiagnostic[] = []; + const readable: TreeEntry[] = []; + let totalBytes = 0; + for (const entry of candidates) { + if (entry.size <= MAX_CONTRACT_BYTES && totalBytes + entry.size <= MAX_TOTAL_BYTES) { + readable.push(entry); + totalBytes += entry.size; + } else if (CONTRACT_PATH.test(entry.path)) { + diagnostics.push(unread(entry.path)); + } + } + const blobs = await readBlobs(repoRoot, readable); + const sources: ContractSource[] = []; + for (const entry of readable) { + const byPath = CONTRACT_PATH.test(entry.path); + const content = decodeUtf8(blobs.get(entry.oid)); + if (content === undefined) { + if (byPath) diagnostics.push(unread(entry.path)); + continue; + } + if (!byPath && !isContractCandidate(entry.path, content)) continue; + sources.push({ path: entry.path, content, fingerprint: `git:${entry.oid}` }); + } + return { requestedRef, commit, inventory: inventoryContracts(sources, diagnostics) }; +} + +/** Compares contract surfaces at two exact commits. Neither ref is checked out. */ +export async function compareContractRefs(input: { repoRoot: string; fromRef: string; toRef: string }): Promise { + const [from, to] = await Promise.all([ + inventoryContractsAtRef({ repoRoot: input.repoRoot, ref: input.fromRef }), + inventoryContractsAtRef({ repoRoot: input.repoRoot, ref: input.toRef }) + ]); + return { + contractDiffVersion: 1, + from: { requestedRef: from.requestedRef, commit: from.commit }, + to: { requestedRef: to.requestedRef, commit: to.commit }, + comparison: compareContractInventories(from.inventory, to.inventory) + }; +} + +function decodeUtf8(bytes: Buffer | undefined): string | undefined { + if (!bytes) return undefined; + try { + return new TextDecoder("utf-8", { fatal: true }).decode(bytes); + } catch { + return undefined; + } +} + +function unread(path: string): ContractDiagnostic { + return { + code: "contract-source-incomplete", + severity: "warning", + path, + message: `${path} looks like a contract, but it is larger than ${MAX_CONTRACT_BYTES / 1024 / 1024} MB, not UTF-8 text, or unreadable, so FixMap did not parse it.` + }; +} diff --git a/packages/core/src/contracts.ts b/packages/core/src/contracts.ts index ad35e065..91c8e7bf 100644 --- a/packages/core/src/contracts.ts +++ b/packages/core/src/contracts.ts @@ -2,6 +2,7 @@ import type { RepoMap } from "./types.js"; import { createGraphIdentity } from "./identity-graph.js"; import type { IdentityGraphNode } from "./identity-graph.js"; import { markdownCode } from "./markdown.js"; +import { parseYamlSubset, YamlSubsetError } from "./yaml-subset.js"; export type ContractKind = "openapi" | "asyncapi" | "graphql" | "protobuf" | "json-schema" | "migration"; export type ContractEntryRole = "operation" | "type" | "field" | "argument" | "required-field" | "migration"; @@ -24,6 +25,8 @@ export type ContractSurface = { kind: ContractKind; path: string; name: string; + /** Declared specification or syntax version (for example OpenAPI 3.1.0 or proto3), when the source states one. */ + version?: string; sourceFingerprint: string; entries: ContractEntry[]; }; @@ -48,7 +51,7 @@ export type ContractChange = { contractId: string; contractKind: ContractKind; path: string; - change: "contract-added" | "contract-removed" | "entry-added" | "entry-removed" | "entry-changed"; + change: "contract-added" | "contract-removed" | "contract-unavailable" | "entry-added" | "entry-removed" | "entry-changed"; compatibility: ContractCompatibility; reason: string; entry?: string; @@ -75,14 +78,16 @@ export type ContractGraphOptions = { }; const HTTP_METHODS = new Set(["get", "put", "post", "delete", "options", "head", "patch", "trace"]); -const CONTRACT_PATH = /(?:^|\/)(?:openapi|swagger|asyncapi)(?:\.[^/]+)?\.(?:json|ya?ml)$|\.(?:graphql|gql|proto)$|(?:^|\/)migrations?\/.*\.sql$|\.schema\.json$/i; +export const CONTRACT_PATH = /(?:^|\/)(?:openapi|swagger|asyncapi)(?:\.[^/]+)?\.(?:json|ya?ml)$|\.(?:graphql|gql|proto)$|(?:^|\/)migrations?\/.*\.sql$|\.schema\.json$/i; /** Converts a scanned repository into bounded contract sources without pretending omitted content was parsed. */ export function contractSourcesFromRepo(repo: RepoMap): { sources: ContractSource[]; diagnostics: ContractDiagnostic[] } { const sources: ContractSource[] = []; const diagnostics: ContractDiagnostic[] = []; for (const file of repo.files.filter((candidate) => isContractCandidate(candidate.path, candidate.textSample))) { - if (file.textSampleComplete === false || !file.contentFingerprint) { + // Files outside the scanner's text extensions (GraphQL, Protobuf, SQL) carry an empty + // sample; parsing that would report an empty surface instead of an unread one. + if (file.textSampleComplete === false || !file.contentFingerprint || !file.isSource) { diagnostics.push({ code: "contract-source-incomplete", severity: "warning", @@ -135,7 +140,11 @@ export function compareContractInventories( for (const [id, before] of beforeById) { const after = afterById.get(id); if (!after) { - if (unavailableAfter.has(before.path)) continue; + if (unavailableAfter.has(before.path)) { + changes.push(contractChange(before, undefined, "contract-unavailable", "unknown", + `${before.kind} contract ${before.name} could not be read on the later side, so its compatibility is unknown.`)); + continue; + } changes.push(contractChange(before, undefined, "contract-removed", "breaking", `Removed ${before.kind} contract ${before.name}.`)); continue; } @@ -143,7 +152,11 @@ export function compareContractInventories( } for (const [id, after] of afterById) { if (!beforeById.has(id)) { - if (unavailableBefore.has(after.path)) continue; + if (unavailableBefore.has(after.path)) { + changes.push(contractChange(undefined, after, "contract-unavailable", "unknown", + `${after.kind} contract ${after.name} could not be read on the earlier side, so its compatibility is unknown.`)); + continue; + } changes.push(contractChange(undefined, after, "contract-added", "compatible", `Added ${after.kind} contract ${after.name}.`)); } } @@ -298,17 +311,34 @@ function parseContract(source: ContractSource): { surface?: ContractSurface; dia } return parsed(source, "graphql", graphql); } - if (lower.endsWith(".proto")) return parsed(source, "protobuf", parseProtobuf(source.content)); + if (lower.endsWith(".proto")) { + const syntax = /^\s*(?:syntax|edition)\s*=\s*["']([^"']+)["']/m.exec(source.content.replace(/\/\/[^\r\n]*/g, ""))?.[1]; + return parsed(source, "protobuf", { ...parseProtobuf(source.content), ...(syntax ? { version: syntax } : {}) }); + } if (/(?:^|\/)migrations?\/.*\.sql$/i.test(source.path)) return parsed(source, "migration", parseMigration(source.content)); const json = parseJson(source.content); - if (json) { - if (typeof json.openapi === "string" || typeof json.swagger === "string") return parsed(source, "openapi", parseOpenApiJson(json)); - if (typeof json.asyncapi === "string") return parsed(source, "asyncapi", parseAsyncApiJson(json)); - if (typeof json.$schema === "string" || isRecord(json.properties)) return parsed(source, "json-schema", parseJsonSchema(json)); + if (json) return parsedStructured(source, json); + const yamlLike = /\.ya?ml$/i.test(source.path) || /^\s*(?:openapi|swagger|asyncapi)\s*:/m.test(source.content); + if (yamlLike) { + let document: unknown; + try { + document = parseYamlSubset(source.content); + } catch (error) { + if (!(error instanceof YamlSubsetError)) throw error; + return parseFailed(source, `YAML ${error.message}.`); + } + if (isRecord(document)) { + // YAML reads an unquoted "3.0" as a number; keep the version text the author wrote. + for (const key of ["openapi", "swagger", "asyncapi"]) { + if (typeof document[key] !== "number") continue; + const written = new RegExp(`^${key}\\s*:\\s*([^\\s#]+)`, "m").exec(source.content)?.[1]; + if (written) document[key] = written; + } + const structured = parsedStructured(source, document); + if (structured.surface || structured.diagnostic) return structured; + } } - if (/^\s*(?:openapi|swagger)\s*:/m.test(source.content)) return parsed(source, "openapi", parseOpenApiYaml(source.content)); - if (/^\s*asyncapi\s*:/m.test(source.content)) return parsed(source, "asyncapi", parseAsyncApiYaml(source.content)); if (CONTRACT_PATH.test(source.path)) { return { diagnostic: { @@ -322,6 +352,30 @@ function parseContract(source: ContractSource): { surface?: ContractSurface; dia return {}; } +/** JSON and YAML documents share one decoder, so both spellings produce identical surfaces. */ +function parsedStructured(source: ContractSource, document: Record): { surface?: ContractSurface; diagnostic?: ContractDiagnostic } { + const openapi = specVersion(document.openapi) ?? specVersion(document.swagger); + if (openapi) return parsed(source, "openapi", { ...parseOpenApiJson(document), version: openapi }); + const asyncapi = specVersion(document.asyncapi); + if (asyncapi) return parsed(source, "asyncapi", { ...parseAsyncApiJson(document), version: asyncapi }); + if (typeof document.$schema === "string" || isRecord(document.properties)) { + return parsed(source, "json-schema", { + ...parseJsonSchema(document), + ...(typeof document.$schema === "string" ? { version: document.$schema } : {}) + }); + } + if (CONTRACT_PATH.test(source.path)) { + return parseFailed(source, "the document has no openapi, swagger, asyncapi, $schema, or properties marker."); + } + return {}; +} + +function specVersion(value: unknown): string | undefined { + if (typeof value === "string" && value.trim()) return value.trim(); + if (typeof value === "number" && Number.isFinite(value)) return String(value); + return undefined; +} + function parseFailed(source: ContractSource, detail: string): { diagnostic: ContractDiagnostic } { return { diagnostic: { @@ -333,13 +387,14 @@ function parseFailed(source: ContractSource, detail: string): { diagnostic: Cont }; } -function parsed(source: ContractSource, kind: ContractKind, parsedSurface: { name?: string; entries: ContractEntry[] }): { surface: ContractSurface } { +function parsed(source: ContractSource, kind: ContractKind, parsedSurface: { name?: string; version?: string; entries: ContractEntry[] }): { surface: ContractSurface } { return { surface: { id: `contract:${kind}:${source.path.replace(/\\/g, "/")}`, kind, path: source.path.replace(/\\/g, "/"), name: parsedSurface.name ?? source.path.split(/[\\/]/).at(-1) ?? source.path, + ...(parsedSurface.version ? { version: parsedSurface.version } : {}), sourceFingerprint: source.fingerprint, entries: normalizeEntries(parsedSurface.entries) } @@ -480,49 +535,6 @@ function parseMigration(content: string): { entries: ContractEntry[] } { return { entries }; } -function parseOpenApiYaml(content: string): { name?: string; entries: ContractEntry[] } { - return parseChannelYaml(content, "paths", HTTP_METHODS); -} - -function parseAsyncApiYaml(content: string): { name?: string; entries: ContractEntry[] } { - return parseChannelYaml(content, "channels", new Set(["publish", "subscribe"])); -} - -function parseChannelYaml(content: string, sectionName: string, operations: Set): { name?: string; entries: ContractEntry[] } { - const entries: ContractEntry[] = []; - const lines = content.split(/\r?\n/); - let inSection = false; - let sectionIndent = -1; - let currentPath: string | undefined; - let pathIndent = -1; - for (const raw of lines) { - const withoutComment = raw.replace(/\s+#.*$/, ""); - const trimmed = withoutComment.trim(); - if (!trimmed) continue; - const indent = withoutComment.length - withoutComment.trimStart().length; - if (!inSection && trimmed === `${sectionName}:`) { - inSection = true; - sectionIndent = indent; - continue; - } - if (!inSection) continue; - if (indent <= sectionIndent) break; - const key = /^([^:]+):\s*$/.exec(trimmed)?.[1]?.trim(); - if (!key) continue; - if (indent > sectionIndent && (currentPath === undefined || indent <= pathIndent)) { - currentPath = unquote(key); - pathIndent = indent; - continue; - } - if (currentPath && indent > pathIndent && operations.has(key.toLowerCase())) { - const operation = sectionName === "paths" ? `${key.toUpperCase()} ${currentPath}` : `${key.toLowerCase()} ${currentPath}`; - entries.push(entry(`operation:${sectionName === "paths" ? operation : `${key.toLowerCase()}:${currentPath}`}`, "operation", operation)); - } - } - const title = content.match(/^\s*title\s*:\s*["']?([^\r\n"']+)/m)?.[1]?.trim(); - return { ...(title ? { name: title } : {}), entries }; -} - function entry(key: string, role: ContractEntryRole, signature: string, required = false): ContractEntry { return { key, role, signature: signature.trim(), required }; } @@ -572,7 +584,7 @@ function validateContractSource(source: ContractSource): void { } } -function isContractCandidate(path: string, content: string): boolean { +export function isContractCandidate(path: string, content: string): boolean { return CONTRACT_PATH.test(path.replace(/\\/g, "/")) || /^\s*(?:openapi|swagger|asyncapi)\s*:/m.test(content) || /^\s*\{[\s\S]*?"(?:openapi|swagger|asyncapi|\$schema)"\s*:/m.test(content); @@ -608,10 +620,6 @@ function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } -function unquote(value: string): string { - return value.replace(/^["']|["']$/g, ""); -} - function severityOrder(value: ContractCompatibility): number { return value === "breaking" ? 0 : value === "unknown" ? 1 : 2; } diff --git a/packages/core/src/feature-catalog.ts b/packages/core/src/feature-catalog.ts index afdea7f1..b4a9b87f 100644 --- a/packages/core/src/feature-catalog.ts +++ b/packages/core/src/feature-catalog.ts @@ -22,6 +22,7 @@ export const FIXMAP_FEATURES: readonly FixMapFeature[] = [ { 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: "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." }, + { name: "Contract Guardian", preview: true, command: "fixmap contracts diff ..", detail: "List OpenAPI, AsyncAPI, GraphQL, Protobuf, JSON Schema, and SQL migration contracts, or classify their changes between two exact Git refs as breaking, unknown, or compatible with before/after fingerprints, without checkout." }, { name: "Supply-chain evidence", preview: true, command: "fixmap supply-chain --input ", detail: "Validate normalized external scanner or SBOM evidence with exact tool, database, document, advisory, version, and license provenance." }, { name: "Runtime evidence", preview: true, command: "fixmap runtime --input ", detail: "Map redaction-reviewed OpenTelemetry, APM, Speedscope, or pprof observations only through exact repository paths and file fingerprints." }, { name: "Evidence import", preview: true, command: "fixmap plan --evidence ", detail: "Attach findings from other tools (scanners, CI, runtime monitors) to the files in a plan from a version-1 data-only bundle; claims are shown as supplied and never executed." }, @@ -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, Capability maps, Workspace, Ask, Migrate, Reverse Docs, History, Contracts, 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 a7cd0cd8..43fd9411 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -270,6 +270,8 @@ export type { ContractSource, ContractSurface } from "./contracts.js"; +export { compareContractRefs, inventoryContractsAtRef, inventoryWorkingTreeContracts } from "./contracts-repository.js"; +export type { ContractInventoryAtRef, ContractRefComparison } from "./contracts-repository.js"; export type { FixMapInput, FixMapReport, diff --git a/packages/core/src/yaml-subset.ts b/packages/core/src/yaml-subset.ts new file mode 100644 index 00000000..6537b259 --- /dev/null +++ b/packages/core/src/yaml-subset.ts @@ -0,0 +1,381 @@ +/** + * A bounded reader for the block-YAML subset that OpenAPI and AsyncAPI documents use: + * mappings, sequences, plain/quoted scalars, literal and folded block scalars, and simple + * flow collections. Anchors, aliases, tags, merge keys, and multiple documents are refused + * rather than guessed, so callers can report the document as unparseable instead of + * producing a surface that silently differs from the author's intent. + */ + +export type YamlValue = string | number | boolean | null | YamlValue[] | { [key: string]: YamlValue }; + +export class YamlSubsetError extends Error {} + +type Line = { number: number; indent: number; text: string; raw: string }; + +const MAX_DEPTH = 64; + +export function parseYamlSubset(content: string): YamlValue { + const lines = toLines(content); + if (lines.length === 0) return null; + const state = { lines, index: 0 }; + const value = parseNode(state, lines[0]!.indent, 0); + if (state.index < lines.length) fail(lines[state.index]!, "unexpected content after the document"); + return value; +} + +function toLines(content: string): Line[] { + const rawLines = content.replace(/^\uFEFF/, "").split(/\r?\n/); + const lines: Line[] = []; + let started = false; + for (let index = 0; index < rawLines.length; index += 1) { + const raw = rawLines[index]!; + if (/^%/.test(raw) && !started) continue; + if (/^---(?:\s|$)/.test(raw)) { + if (started || lines.length > 0) throw new YamlSubsetError(`line ${index + 1}: multiple YAML documents are not supported`); + started = true; + if (raw.slice(3).trim() && !raw.slice(3).trim().startsWith("#")) { + throw new YamlSubsetError(`line ${index + 1}: content on the document marker is not supported`); + } + continue; + } + if (/^\.\.\.(?:\s|$)/.test(raw)) { + if (rawLines.slice(index + 1).some((rest) => rest.trim() && !rest.trim().startsWith("#"))) { + throw new YamlSubsetError(`line ${index + 1}: multiple YAML documents are not supported`); + } + break; + } + const leading = /^[ \t]*/.exec(raw)![0]; + const text = stripComment(raw.slice(leading.length)).trimEnd(); + if (!text) { + lines.push({ number: index + 1, indent: -1, text: "", raw }); + continue; + } + if (leading.includes("\t")) throw new YamlSubsetError(`line ${index + 1}: tab indentation is not supported`); + lines.push({ number: index + 1, indent: leading.length, text, raw }); + } + return lines; +} + +function stripComment(text: string): string { + if (text.startsWith("#")) return ""; + let quote: string | undefined; + for (let index = 0; index < text.length; index += 1) { + const char = text[index]!; + if (quote) { + if (quote === "\"" && char === "\\") index += 1; + else if (char === quote) quote = undefined; + continue; + } + if ((char === "\"" || char === "'") && (index === 0 || /[\s:\[\]{},-]/.test(text[index - 1]!))) quote = char; + else if (char === "#" && /\s/.test(text[index - 1] ?? "")) return text.slice(0, index); + } + return text; +} + +type State = { lines: Line[]; index: number }; + +function current(state: State): Line | undefined { + while (state.index < state.lines.length && state.lines[state.index]!.indent < 0) state.index += 1; + return state.lines[state.index]; +} + +function parseNode(state: State, indent: number, depth: number): YamlValue { + if (depth > MAX_DEPTH) throw new YamlSubsetError("YAML nesting is deeper than FixMap reads"); + const line = current(state); + if (!line || line.indent < indent) return null; + if (isSequenceItem(line.text)) return parseSequence(state, line.indent, depth); + if (splitKey(line.text)) return parseMapping(state, line.indent, depth); + state.index += 1; + return parseInlineValue(line, line.text, state, line.indent, depth); +} + +function isSequenceItem(text: string): boolean { + return text === "-" || text.startsWith("- "); +} + +function parseSequence(state: State, indent: number, depth: number): YamlValue[] { + const values: YamlValue[] = []; + for (let line = current(state); line && line.indent === indent && isSequenceItem(line.text); line = current(state)) { + const rest = line.text.slice(1).trimStart(); + if (!rest) { + state.index += 1; + const next = current(state); + values.push(next && next.indent > indent ? parseNode(state, next.indent, depth + 1) : null); + continue; + } + // "- key: value" opens a mapping whose items align with the first key. + const column = indent + (line.text.length - rest.length); + state.lines[state.index] = { ...line, indent: column, text: rest }; + if (isSequenceItem(rest) || splitKey(rest)) values.push(parseNode(state, column, depth + 1)); + else { + state.index += 1; + values.push(parseInlineValue(line, rest, state, indent, depth)); + } + } + const after = current(state); + if (after && after.indent > indent) fail(after, "unexpected indentation in a sequence"); + return values; +} + +function parseMapping(state: State, indent: number, depth: number): { [key: string]: YamlValue } { + const result: { [key: string]: YamlValue } = {}; + for (let line = current(state); line && line.indent === indent; line = current(state)) { + const split = splitKey(line.text); + if (!split) fail(line, "expected a mapping key"); + const key = parseKey(line, split.key); + if (key === "<<") fail(line, "merge keys are not supported"); + if (Object.prototype.hasOwnProperty.call(result, key)) fail(line, `duplicate key ${JSON.stringify(key)}`); + state.index += 1; + if (!split.value) { + const next = current(state); + if (next && (next.indent > indent || (next.indent === indent && isSequenceItem(next.text)))) { + result[key] = parseNode(state, next.indent, depth + 1); + } else { + result[key] = null; + } + } else { + result[key] = parseInlineValue(line, split.value, state, indent, depth); + } + } + const after = current(state); + if (after && after.indent > indent) fail(after, "unexpected indentation in a mapping"); + return result; +} + +/** Finds the key/value separator: a colon followed by whitespace or end of line, outside quotes and flow. */ +function splitKey(text: string): { key: string; value: string } | undefined { + if (isSequenceItem(text) || text.startsWith("{") || text.startsWith("[")) return undefined; + let index = 0; + if (text.startsWith("\"") || text.startsWith("'")) { + const end = closingQuote(text, 0); + if (end === -1) return undefined; + index = end + 1; + const rest = text.slice(index); + const match = /^\s*:(?:\s|$)/.exec(rest); + if (!match) return undefined; + return { key: text.slice(0, index), value: rest.slice(match[0].length).trim() }; + } + for (; index < text.length; index += 1) { + if (text[index] === ":" && (index + 1 === text.length || /\s/.test(text[index + 1]!))) { + return { key: text.slice(0, index).trimEnd(), value: text.slice(index + 1).trim() }; + } + } + return undefined; +} + +function parseKey(line: Line, raw: string): string { + if (raw.startsWith("? ")) fail(line, "complex mapping keys are not supported"); + if (raw.startsWith("\"") || raw.startsWith("'")) return parseQuoted(line, raw); + if (/^[&*!]/.test(raw)) fail(line, "anchors, aliases, and tags are not supported"); + return raw; +} + +function parseInlineValue(line: Line, value: string, state: State, parentIndent: number, depth: number): YamlValue { + if (/^[&*!]/.test(value)) fail(line, "anchors, aliases, and tags are not supported"); + if (/^[|>]/.test(value)) return parseBlockScalar(line, value, state, parentIndent); + if (value.startsWith("{") || value.startsWith("[")) { + let text = value; + // A flow collection may wrap onto more-indented lines. + while (!flowBalanced(text)) { + const next = current(state); + if (!next || next.indent <= parentIndent) fail(line, "unterminated flow collection"); + text += ` ${next.text}`; + state.index += 1; + } + const parser = { text, index: 0, line }; + const result = parseFlowValue(parser, depth); + skipSpace(parser); + if (parser.index !== text.length) fail(line, "unexpected content after a flow collection"); + return result; + } + if (value.startsWith("\"") || value.startsWith("'")) { + let text = value; + while (closingQuote(text, 0) === -1) { + const next = current(state); + if (!next) fail(line, "unterminated quoted scalar"); + text += ` ${next.raw.trim()}`; + state.index += 1; + } + const end = closingQuote(text, 0); + if (text.slice(end + 1).trim()) fail(line, "unexpected content after a quoted scalar"); + return parseQuoted(line, text); + } + // Plain scalars may continue onto more-indented lines; YAML folds them with spaces. + let text = value; + for (let next = current(state); next && next.indent > parentIndent; next = current(state)) { + if (splitKey(next.text) || isSequenceItem(next.text)) fail(next, "a scalar value cannot also open a nested block"); + text += ` ${next.text}`; + state.index += 1; + } + return resolvePlain(text); +} + +function parseBlockScalar(line: Line, header: string, state: State, parentIndent: number): string { + const match = /^([|>])([+-]?)(\d?)([+-]?)$/.exec(header.trim()); + if (!match) fail(line, "unsupported block scalar header"); + const folded = match[1] === ">"; + const chomping = match[2] || match[4]; + const explicit = match[3] ? Number(match[3]) : undefined; + const collected: string[] = []; + let contentIndent = explicit !== undefined ? parentIndent + explicit : undefined; + while (state.index < state.lines.length) { + const next = state.lines[state.index]!; + // Block scalars keep "#" text, so read raw lines instead of comment-stripped ones. + const blank = next.raw.trim() === ""; + const leading = /^ */.exec(next.raw)![0].length; + if (!blank && leading <= parentIndent) break; + if (!blank) { + contentIndent ??= leading; + if (leading < contentIndent) fail(next, "block scalar line is less indented than its first line"); + } + collected.push(blank ? "" : next.raw.slice(contentIndent!)); + state.index += 1; + } + while (collected.length > 0 && collected.at(-1) === "" && chomping !== "+") collected.pop(); + let text = folded ? foldLines(collected) : collected.join("\n"); + if (chomping !== "-" && collected.length > 0) text += "\n"; + return text; +} + +function foldLines(lines: string[]): string { + let result = ""; + for (let index = 0; index < lines.length; index += 1) { + const line = lines[index]!; + if (index === 0) { result = line; continue; } + const previous = lines[index - 1]!; + if (line === "") result += "\n"; + else if (previous === "" || /^\s/.test(line) || /^\s/.test(previous)) result += (previous === "" ? "" : "\n") + line; + else result += ` ${line}`; + } + return result; +} + +function resolvePlain(text: string): YamlValue { + const value = text.trim(); + if (value === "" || value === "~" || /^(?:null|Null|NULL)$/.test(value)) return null; + if (/^(?:true|True|TRUE)$/.test(value)) return true; + if (/^(?:false|False|FALSE)$/.test(value)) return false; + if (/^[-+]?(?:0|[1-9][0-9]*)$/.test(value)) { + const numeric = Number(value); + return Number.isSafeInteger(numeric) ? numeric : value; + } + if (/^[-+]?(?:[0-9]+\.[0-9]*|\.[0-9]+)(?:[eE][-+]?[0-9]+)?$/.test(value) || /^[-+]?[0-9]+[eE][-+]?[0-9]+$/.test(value)) return Number(value); + return value; +} + +function closingQuote(text: string, start: number): number { + const quote = text[start]; + for (let index = start + 1; index < text.length; index += 1) { + if (quote === "\"" && text[index] === "\\") { index += 1; continue; } + if (text[index] === quote) { + if (quote === "'" && text[index + 1] === "'") { index += 1; continue; } + return index; + } + } + return -1; +} + +function parseQuoted(line: Line, text: string): string { + const end = closingQuote(text, 0); + if (end === -1) fail(line, "unterminated quoted scalar"); + const body = text.slice(1, end); + if (text[0] === "'") return body.replace(/''/g, "'"); + return body.replace(/\\(u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|.)/g, (_, escape: string) => { + if (escape.length > 1) return String.fromCharCode(parseInt(escape.slice(1), 16)); + const simple: Record = { n: "\n", t: "\t", r: "\r", "0": "\0", "\"": "\"", "\\": "\\", "/": "/", " ": " ", b: "\b", f: "\f" }; + if (!(escape in simple)) fail(line, `unsupported escape \\${escape}`); + return simple[escape]!; + }); +} + +type FlowParser = { text: string; index: number; line: Line }; + +function flowBalanced(text: string): boolean { + let depth = 0; + let quote: string | undefined; + for (let index = 0; index < text.length; index += 1) { + const char = text[index]!; + if (quote) { + if (quote === "\"" && char === "\\") index += 1; + else if (char === quote) quote = undefined; + } else if (char === "\"" || char === "'") quote = char; + else if (char === "{" || char === "[") depth += 1; + else if (char === "}" || char === "]") depth -= 1; + } + return depth <= 0 && !quote; +} + +function skipSpace(parser: FlowParser): void { + while (parser.index < parser.text.length && /\s/.test(parser.text[parser.index]!)) parser.index += 1; +} + +function parseFlowValue(parser: FlowParser, depth: number): YamlValue { + if (depth > MAX_DEPTH) throw new YamlSubsetError("YAML nesting is deeper than FixMap reads"); + skipSpace(parser); + const char = parser.text[parser.index]; + if (char === "{") return parseFlowMapping(parser, depth + 1); + if (char === "[") return parseFlowSequence(parser, depth + 1); + if (char === "\"" || char === "'") { + const end = closingQuote(parser.text, parser.index); + if (end === -1) fail(parser.line, "unterminated quoted scalar"); + const value = parseQuoted(parser.line, parser.text.slice(parser.index, end + 1)); + parser.index = end + 1; + return value; + } + if (char !== undefined && /[&*!]/.test(char)) fail(parser.line, "anchors, aliases, and tags are not supported"); + const start = parser.index; + while (parser.index < parser.text.length && !/[,\]}]/.test(parser.text[parser.index]!) && + !(parser.text[parser.index] === ":" && /[\s,\]}]/.test(parser.text[parser.index + 1] ?? " "))) parser.index += 1; + return resolvePlain(parser.text.slice(start, parser.index)); +} + +function parseFlowSequence(parser: FlowParser, depth: number): YamlValue[] { + parser.index += 1; + const values: YamlValue[] = []; + skipSpace(parser); + if (parser.text[parser.index] === "]") { parser.index += 1; return values; } + for (;;) { + values.push(parseFlowValue(parser, depth)); + skipSpace(parser); + const char = parser.text[parser.index]; + parser.index += 1; + if (char === "]") return values; + if (char !== ",") fail(parser.line, "expected , or ] in a flow sequence"); + skipSpace(parser); + if (parser.text[parser.index] === "]") { parser.index += 1; return values; } + } +} + +function parseFlowMapping(parser: FlowParser, depth: number): { [key: string]: YamlValue } { + parser.index += 1; + const result: { [key: string]: YamlValue } = {}; + skipSpace(parser); + if (parser.text[parser.index] === "}") { parser.index += 1; return result; } + for (;;) { + const keyValue = parseFlowValue(parser, depth); + if (keyValue !== null && typeof keyValue === "object") fail(parser.line, "complex mapping keys are not supported"); + const key = keyValue === null ? "" : String(keyValue); + if (key === "<<") fail(parser.line, "merge keys are not supported"); + if (Object.prototype.hasOwnProperty.call(result, key)) fail(parser.line, `duplicate key ${JSON.stringify(key)}`); + skipSpace(parser); + if (parser.text[parser.index] === ":") { + parser.index += 1; + skipSpace(parser); + const next = parser.text[parser.index]; + result[key] = next === "," || next === "}" ? null : parseFlowValue(parser, depth); + } else { + result[key] = null; + } + skipSpace(parser); + const char = parser.text[parser.index]; + parser.index += 1; + if (char === "}") return result; + if (char !== ",") fail(parser.line, "expected , or } in a flow mapping"); + skipSpace(parser); + if (parser.text[parser.index] === "}") { parser.index += 1; return result; } + } +} + +function fail(line: Line, message: string): never { + throw new YamlSubsetError(`line ${line.number}: ${message}`); +} diff --git a/packages/core/test/contracts-repository.test.ts b/packages/core/test/contracts-repository.test.ts new file mode 100644 index 00000000..9089ff21 --- /dev/null +++ b/packages/core/test/contracts-repository.test.ts @@ -0,0 +1,108 @@ +import { execFile } from "node:child_process"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { promisify } from "node:util"; +import { afterEach, describe, expect, it } from "vitest"; +import { contractSourcesFromRepo } from "../src/contracts.js"; +import { compareContractRefs, inventoryContractsAtRef, inventoryWorkingTreeContracts } from "../src/contracts-repository.js"; +import { scanRepo } from "../src/repo-scan.js"; +import { parseYamlSubset, YamlSubsetError } from "../src/yaml-subset.js"; + +const exec = promisify(execFile); +const GIT_TEST_TIMEOUT = process.platform === "win32" ? 60_000 : 20_000; +const roots: string[] = []; + +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }))); +}); + +async function repository(files: Record): Promise { + const root = await mkdtemp(join(tmpdir(), "fixmap-contracts-core-")); + roots.push(root); + await exec("git", ["init", "--quiet"], { cwd: root }); + await exec("git", ["config", "user.email", "fixmap@example.test"], { cwd: root }); + await exec("git", ["config", "user.name", "FixMap Test"], { cwd: root }); + for (const [path, content] of Object.entries(files)) { + await mkdir(dirname(join(root, path)), { recursive: true }); + await writeFile(join(root, path), content); + } + await exec("git", ["add", "-A"], { cwd: root }); + await exec("git", ["commit", "--quiet", "-m", "fixture"], { cwd: root }); + return root; +} + +describe("YAML subset reader", () => { + it("reads block, flow, quoted, and block-scalar values like JSON would", () => { + expect(parseYamlSubset([ + "---", + "a: 1", + "b: '2'", + "c: \"x\\ty\"", + "d: [1, two, {e: true}]", + "f:", + "- g: null", + " h: ~", + "- plain text", + "i: |-", + " line one", + " # kept", + "j: >", + " folded", + " text", + "k: it's fine # comment", + "l: 'it''s'", + "m: a", + " continued", + "" + ].join("\n"))).toEqual({ + a: 1, b: "2", c: "x\ty", d: [1, "two", { e: true }], + f: [{ g: null, h: null }, "plain text"], + i: "line one\n# kept", j: "folded text\n", k: "it's fine", l: "it's", m: "a continued" + }); + }); + + it("refuses constructs it cannot represent faithfully", () => { + for (const content of ["a: &x 1\nb: *x\n", "a: !!str 1\n", "<<: {a: 1}\n", "a: 1\na: 2\n", "a:\n\tb: 1\n", "a: [1, 2\n", "a: 1\n---\nb: 2\n"]) { + expect(() => parseYamlSubset(content)).toThrow(YamlSubsetError); + } + }); +}); + +describe("repository contract sources", () => { + it("reports scanner-unsampled contracts as incomplete instead of empty surfaces", async () => { + const root = await repository({ "schema.graphql": "type Query { ok: Boolean }\n", "user.proto": "message User { string id = 1; }\n" }); + const repo = await scanRepo({ repoRoot: root, useCache: false }); + const discovered = contractSourcesFromRepo(repo); + expect(discovered.sources).toEqual([]); + expect(discovered.diagnostics.map((diagnostic) => diagnostic.path)).toEqual(["schema.graphql", "user.proto"]); + + const inventory = await inventoryWorkingTreeContracts(repo); + expect(inventory.surfaces.map((surface) => [surface.path, surface.entries.length > 0])).toEqual([["schema.graphql", true], ["user.proto", true]]); + }, GIT_TEST_TIMEOUT); + + it("reports oversized or non-UTF-8 contracts as unread on both sides", async () => { + const root = await repository({ + "big.graphql": `type Query { ok: Boolean }\n${"# padding\n".repeat(260_000)}`, + "binary.proto": Buffer.from([0xff, 0xfe, 0x00, 0x01]), + "config.yaml": "name: not a contract\n" + }); + const working = await inventoryWorkingTreeContracts(await scanRepo({ repoRoot: root, useCache: false })); + const atRef = await inventoryContractsAtRef({ repoRoot: root, ref: "HEAD" }); + for (const inventory of [working, atRef.inventory]) { + expect(inventory.surfaces).toEqual([]); + expect(inventory.diagnostics.map((diagnostic) => [diagnostic.path, diagnostic.code])).toEqual([ + ["big.graphql", "contract-source-incomplete"], + ["binary.proto", "contract-source-incomplete"] + ]); + } + }, GIT_TEST_TIMEOUT); + + it("finds content-marked OpenAPI files at a ref and rejects unknown refs", async () => { + const root = await repository({ "specs/users-api.yml": "openapi: 3.0.3\npaths:\n /users:\n get: {}\n" }); + const atRef = await inventoryContractsAtRef({ repoRoot: root, ref: "HEAD" }); + expect(atRef.commit).toMatch(/^[a-f0-9]{40}$/); + expect(atRef.inventory.surfaces).toEqual([expect.objectContaining({ kind: "openapi", path: "specs/users-api.yml", version: "3.0.3" })]); + await expect(compareContractRefs({ repoRoot: root, fromRef: "HEAD", toRef: "missing-ref" })).rejects.toThrow("Could not resolve Git ref"); + }, GIT_TEST_TIMEOUT); +}); diff --git a/packages/core/test/contracts.test.ts b/packages/core/test/contracts.test.ts index 83299f4f..2793b237 100644 --- a/packages/core/test/contracts.test.ts +++ b/packages/core/test/contracts.test.ts @@ -196,10 +196,149 @@ describe("Contract Guardian", () => { const previous = inventoryContracts([source("schema.graphql", "type Query { ok: Boolean }", "before")]); const current = inventoryContracts([source("schema.graphql", "this is not GraphQL SDL", "after")]); const result = compareContractInventories(previous, current); - expect(result.changes).toEqual([]); + expect(result.changes).toEqual([expect.objectContaining({ + change: "contract-unavailable", + compatibility: "unknown", + evidence: { beforeFingerprint: "content:before0000000000" } + })]); + expect(result.changes.some((change) => change.change === "contract-removed")).toBe(false); expect(result.diagnostics).toContainEqual(expect.objectContaining({ code: "contract-parse-failed" })); }); + it("produces identical surfaces and deltas for equivalent OpenAPI JSON and YAML", () => { + const beforeJson = { + openapi: "3.1.0", + info: { title: "Users" }, + paths: { + "/users/{id}": { + get: { parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }] }, + delete: {} + } + }, + components: { schemas: { User: { type: "object", required: ["id"], properties: { id: { type: "string" }, email: { type: "string", format: "email" } } } } } + }; + const afterJson = { + openapi: "3.1.0", + info: { title: "Users" }, + paths: { + "/users/{id}": { + get: { parameters: [ + { name: "id", in: "path", required: true, schema: { type: "integer" } }, + { name: "expand", in: "query", required: false, schema: { type: "string" } } + ] } + } + }, + components: { schemas: { User: { type: "object", required: ["id", "email"], properties: { id: { type: "string" }, email: { type: "string", format: "email" } } } } } + }; + const beforeYaml = [ + "# Users API", + "openapi: 3.1.0", + "info:", + " title: Users", + " description: |", + " Multi-line text with a # that is not a comment", + " and: a colon.", + "paths:", + " '/users/{id}':", + " get:", + " parameters:", + " - name: id", + " in: path", + " required: true", + " schema: { type: string }", + " delete: {}", + "components:", + " schemas:", + " User:", + " type: object", + " required: [id]", + " properties:", + " id:", + " type: string # inline comment", + " email:", + " type: string", + " format: email", + "" + ].join("\n"); + const afterYaml = [ + "openapi: \"3.1.0\"", + "info: { title: Users }", + "paths:", + " /users/{id}:", + " get:", + " parameters:", + " - name: id", + " in: path", + " required: true", + " schema:", + " type: integer", + " - {name: expand, in: query, required: false, schema: {type: string}}", + "components:", + " schemas:", + " User:", + " type: object", + " required:", + " - id", + " - email", + " properties:", + " id: { type: string }", + " email: { type: string, format: email }", + "" + ].join("\n"); + const jsonBefore = inventoryContracts([source("api/openapi.json", JSON.stringify(beforeJson), "before")]); + const yamlBefore = inventoryContracts([source("api/openapi.json", beforeYaml, "before")].map((value) => ({ ...value, path: "api/openapi.yaml" }))); + expect(yamlBefore.diagnostics).toEqual([]); + expect(yamlBefore.surfaces[0]).toMatchObject({ kind: "openapi", version: "3.1.0", name: "Users" }); + expect(yamlBefore.surfaces[0]!.entries).toEqual(jsonBefore.surfaces[0]!.entries); + + const strip = (comparison: ReturnType) => + comparison.changes.map(({ compatibility, change, entry, before, after, reason }) => ({ compatibility, change, entry, before, after, reason })); + const jsonDelta = compare("api/openapi.json", JSON.stringify(beforeJson), JSON.stringify(afterJson)); + const yamlDelta = compare("api/openapi.yaml", beforeYaml, afterYaml); + expect(strip(yamlDelta)).toEqual(strip(jsonDelta)); + expect(yamlDelta.changes).toEqual(expect.arrayContaining([ + expect.objectContaining({ entry: "operation:DELETE /users/{id}", compatibility: "breaking" }), + expect.objectContaining({ entry: "argument:GET /users/{id}:path:id", change: "entry-changed", compatibility: "breaking" }), + expect.objectContaining({ entry: "argument:GET /users/{id}:query:expand", compatibility: "compatible" }), + expect.objectContaining({ entry: "field:User.email", compatibility: "breaking" }) + ])); + }); + + it("produces identical AsyncAPI deltas for JSON and YAML", () => { + const before = { asyncapi: "2.6.0", info: { title: "Events" }, channels: { "user.created": { publish: { message: {} } }, "user.deleted": { subscribe: {} } } }; + const after = { asyncapi: "2.6.0", info: { title: "Events" }, channels: { "user.created": { publish: { message: {} } } } }; + const beforeYaml = "asyncapi: 2.6.0\ninfo:\n title: Events\nchannels:\n user.created:\n publish:\n message: {}\n user.deleted:\n subscribe: {}\n"; + const afterYaml = "asyncapi: 2.6.0\ninfo:\n title: Events\nchannels:\n user.created:\n publish:\n message: {}\n"; + const json = compare("asyncapi.json", JSON.stringify(before), JSON.stringify(after)); + const yaml = compare("asyncapi.yml", beforeYaml, afterYaml); + expect(yaml.changes.map((change) => [change.entry, change.compatibility])).toEqual(json.changes.map((change) => [change.entry, change.compatibility])); + expect(yaml.changes).toEqual([expect.objectContaining({ entry: "operation:subscribe:user.deleted", compatibility: "breaking" })]); + }); + + it("reports unsupported or malformed YAML as an unparseable contract instead of guessing", () => { + for (const content of [ + "openapi: 3.1.0\ncomponents:\n schemas:\n Base: &base\n type: object\n User: *base\n", + "openapi: 3.1.0\npaths:\n /a:\n get: {}\n /a:\n post: {}\n", + "openapi: 3.1.0\npaths: {unterminated\n", + "openapi: 3.1.0\n---\nopenapi: 3.0.0\n" + ]) { + const inventory = inventoryContracts([source("openapi.yaml", content, "bad")]); + expect(inventory.surfaces).toEqual([]); + expect(inventory.diagnostics).toEqual([expect.objectContaining({ code: "contract-parse-failed", path: "openapi.yaml" })]); + } + }); + + it("records declared specification versions", () => { + const inventory = inventoryContracts([ + source("a.proto", "syntax = \"proto3\";\nmessage A { string id = 1; }", "a"), + source("openapi.yaml", "openapi: 3.0\npaths: {}\n", "b"), + source("schema.graphql", "type Query { ok: Boolean }", "c") + ]); + expect(inventory.surfaces.map((surface) => [surface.kind, surface.version])).toEqual([ + ["graphql", undefined], ["openapi", "3.0"], ["protobuf", "proto3"] + ]); + }); + it("fails closed on duplicate paths and invalid source paths", () => { const valid = source("schema.graphql", "type Query { ok: Boolean }", "one"); expect(() => inventoryContracts([valid, valid])).toThrow("Duplicate contract source path"); From a31eff8e082ecc8bbe7b8ee25c5d93d4b3268be8 Mon Sep 17 00:00:00 2001 From: Aryam Goyal Date: Sun, 22 Nov 2026 20:16:39 +0530 Subject: [PATCH 6/9] build(action): rebuild bundle with reviewer-routing Core changes Co-Authored-By: Claude Opus 5.5 --- packages/action/dist/index.mjs | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/packages/action/dist/index.mjs b/packages/action/dist/index.mjs index fc2ef17d..4403d73a 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; From eaeeaebde70e49eff85854b87e366e2071364694 Mon Sep 17 00:00:00 2001 From: Aryam Goyal Date: Sun, 22 Nov 2026 20:16:55 +0530 Subject: [PATCH 7/9] build(action): rebuild bundle on latest main Co-Authored-By: Claude Opus 5.5 --- packages/action/dist/index.mjs | 649 +++++++++++++++++++++++++++------ 1 file changed, 536 insertions(+), 113 deletions(-) diff --git a/packages/action/dist/index.mjs b/packages/action/dist/index.mjs index fa3c41c5..d7d9bedf 100644 --- a/packages/action/dist/index.mjs +++ b/packages/action/dist/index.mjs @@ -1244,7 +1244,7 @@ function isVagueTaskText(issueText) { return residual.size <= MAX_RESIDUAL_TOKENS_FOR_VAGUE; } function removeIdentifiers(text, identifiers) { - return identifiers.reduce((current, identifier) => current.replace(new RegExp(escapeRegExp(identifier), "g"), " "), text); + return identifiers.reduce((current2, identifier) => current2.replace(new RegExp(escapeRegExp(identifier), "g"), " "), text); } function escapeRegExp(value) { return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); @@ -1309,11 +1309,11 @@ function composerDependencyClosure(projects, projectPath) { const reachable = /* @__PURE__ */ new Set(); const pending = [projectPath]; while (pending.length > 0) { - const current = pending.shift(); - if (reachable.has(current)) + const current2 = pending.shift(); + if (reachable.has(current2)) continue; - reachable.add(current); - for (const dependency of byPath.get(current)?.pathDependencies ?? []) { + reachable.add(current2); + for (const dependency of byPath.get(current2)?.pathDependencies ?? []) { if (!reachable.has(dependency.projectPath)) pending.push(dependency.projectPath); } @@ -1580,11 +1580,11 @@ function dotnetReferenceClosure(projects, projectPath) { const reachable = /* @__PURE__ */ new Set(); const pending = [projectPath]; while (pending.length > 0) { - const current = pending.shift(); - if (reachable.has(current)) + const current2 = pending.shift(); + if (reachable.has(current2)) continue; - reachable.add(current); - for (const reference of byPath.get(current)?.references ?? []) { + reachable.add(current2); + for (const reference of byPath.get(current2)?.references ?? []) { if (!reachable.has(reference)) pending.push(reference); } @@ -2874,11 +2874,11 @@ function dotnetReferenceClosureFromIndex(projectsByPath, projectPath) { const reachable = /* @__PURE__ */ new Set(); const pending = [projectPath]; while (pending.length > 0) { - const current = pending.shift(); - if (reachable.has(current)) + const current2 = pending.shift(); + if (reachable.has(current2)) continue; - reachable.add(current); - for (const reference of projectsByPath.get(current)?.references ?? []) { + reachable.add(current2); + for (const reference of projectsByPath.get(current2)?.references ?? []) { if (!reachable.has(reference)) pending.push(reference); } @@ -3107,12 +3107,12 @@ function buildImpactMap(repo, requestedSeeds, testRoutes = [], limit = DEFAULT_I const addEvidence = (path, score, evidence) => { if (seedSet.has(path) || !repositoryPaths.has(path) || isGeneratedPath(path) || isBackupPath(path)) return; - const current = candidates.get(path) ?? { path, score: 0, evidence: [] }; - if (!current.evidence.some((entry2) => entry2.kind === evidence.kind && entry2.seed === evidence.seed)) { - current.evidence.push(evidence); - current.score += score; + const current2 = candidates.get(path) ?? { path, score: 0, evidence: [] }; + if (!current2.evidence.some((entry2) => entry2.kind === evidence.kind && entry2.seed === evidence.seed)) { + current2.evidence.push(evidence); + current2.score += score; } - candidates.set(path, current); + candidates.set(path, current2); }; const graph = buildImportGraph(repo.files, languageContext); const primarySet = new Set(primaryPaths.filter((path) => repositoryPaths.has(path))); @@ -6469,10 +6469,10 @@ function reportEscapedLinks(diagnostics, paths) { paths: unique.slice(0, 8) }); } -async function walkFiles(root, current, diagnostics, state, internalCacheRoot, internalPaths, languageRegistry) { +async function walkFiles(root, current2, diagnostics, state, internalCacheRoot, internalPaths, languageRegistry) { let entries; try { - entries = await readdir(current, { withFileTypes: true }); + entries = await readdir(current2, { withFileTypes: true }); } catch { return []; } @@ -6486,14 +6486,14 @@ async function walkFiles(root, current, diagnostics, state, internalCacheRoot, i break; } if (entry2.isSymbolicLink()) { - state.linkedPaths.push(normalizePath3(relative(root, join(current, entry2.name)))); + state.linkedPaths.push(normalizePath3(relative(root, join(current2, entry2.name)))); continue; } if (entry2.isDirectory()) { if (WALK_IGNORED_DIRS.has(entry2.name)) { continue; } - const directory = join(current, entry2.name); + const directory = join(current2, entry2.name); if (internalCacheRoot && sameFilesystemPath(directory, internalCacheRoot)) continue; results.push(...await walkFiles(root, directory, diagnostics, state, internalCacheRoot, internalPaths, languageRegistry)); @@ -6502,7 +6502,7 @@ async function walkFiles(root, current, diagnostics, state, internalCacheRoot, i if (!entry2.isFile()) { continue; } - const absolutePath = join(current, entry2.name); + const absolutePath = join(current2, entry2.name); const relativePath = normalizePath3(relative(root, absolutePath)); if (hasInternalPath(internalPaths, relativePath) || isInternalCachePath(root, relativePath, internalCacheRoot)) continue; @@ -6685,19 +6685,19 @@ function sampleDiffText(diffText, diagnostics) { if (diffText.length <= MAX_DIFF_TEXT_CHARS) return diffText; const groups = []; - let current; + let current2; for (const line of diffText.split(/\r?\n/)) { if (line.startsWith("diff --git ")) { - current = []; - groups.push(current); + current2 = []; + groups.push(current2); continue; } if (line.startsWith("+") && !line.startsWith("+++")) { - if (!current) { - current = []; - groups.push(current); + if (!current2) { + current2 = []; + groups.push(current2); } - current.push(line); + current2.push(line); } } const queues = groups.filter((group) => group.length > 0); @@ -8130,6 +8130,435 @@ function encodePart(value) { return value.split("/").map(encodeURIComponent).join("/"); } +// packages/core/dist/yaml-subset.js +var YamlSubsetError = class extends Error { +}; +var MAX_DEPTH = 64; +function parseYamlSubset(content) { + const lines = toLines(content); + if (lines.length === 0) + return null; + const state = { lines, index: 0 }; + const value = parseNode(state, lines[0].indent, 0); + if (state.index < lines.length) + fail(lines[state.index], "unexpected content after the document"); + return value; +} +function toLines(content) { + const rawLines = content.replace(/^\uFEFF/, "").split(/\r?\n/); + const lines = []; + let started = false; + for (let index = 0; index < rawLines.length; index += 1) { + const raw = rawLines[index]; + if (/^%/.test(raw) && !started) + continue; + if (/^---(?:\s|$)/.test(raw)) { + if (started || lines.length > 0) + throw new YamlSubsetError(`line ${index + 1}: multiple YAML documents are not supported`); + started = true; + if (raw.slice(3).trim() && !raw.slice(3).trim().startsWith("#")) { + throw new YamlSubsetError(`line ${index + 1}: content on the document marker is not supported`); + } + continue; + } + if (/^\.\.\.(?:\s|$)/.test(raw)) { + if (rawLines.slice(index + 1).some((rest) => rest.trim() && !rest.trim().startsWith("#"))) { + throw new YamlSubsetError(`line ${index + 1}: multiple YAML documents are not supported`); + } + break; + } + const leading = /^[ \t]*/.exec(raw)[0]; + const text = stripComment(raw.slice(leading.length)).trimEnd(); + if (!text) { + lines.push({ number: index + 1, indent: -1, text: "", raw }); + continue; + } + if (leading.includes(" ")) + throw new YamlSubsetError(`line ${index + 1}: tab indentation is not supported`); + lines.push({ number: index + 1, indent: leading.length, text, raw }); + } + return lines; +} +function stripComment(text) { + if (text.startsWith("#")) + return ""; + let quote; + for (let index = 0; index < text.length; index += 1) { + const char = text[index]; + if (quote) { + if (quote === '"' && char === "\\") + index += 1; + else if (char === quote) + quote = void 0; + continue; + } + if ((char === '"' || char === "'") && (index === 0 || /[\s:\[\]{},-]/.test(text[index - 1]))) + quote = char; + else if (char === "#" && /\s/.test(text[index - 1] ?? "")) + return text.slice(0, index); + } + return text; +} +function current(state) { + while (state.index < state.lines.length && state.lines[state.index].indent < 0) + state.index += 1; + return state.lines[state.index]; +} +function parseNode(state, indent, depth5) { + if (depth5 > MAX_DEPTH) + throw new YamlSubsetError("YAML nesting is deeper than FixMap reads"); + const line = current(state); + if (!line || line.indent < indent) + return null; + if (isSequenceItem(line.text)) + return parseSequence(state, line.indent, depth5); + if (splitKey(line.text)) + return parseMapping(state, line.indent, depth5); + state.index += 1; + return parseInlineValue(line, line.text, state, line.indent, depth5); +} +function isSequenceItem(text) { + return text === "-" || text.startsWith("- "); +} +function parseSequence(state, indent, depth5) { + const values = []; + for (let line = current(state); line && line.indent === indent && isSequenceItem(line.text); line = current(state)) { + const rest = line.text.slice(1).trimStart(); + if (!rest) { + state.index += 1; + const next = current(state); + values.push(next && next.indent > indent ? parseNode(state, next.indent, depth5 + 1) : null); + continue; + } + const column = indent + (line.text.length - rest.length); + state.lines[state.index] = { ...line, indent: column, text: rest }; + if (isSequenceItem(rest) || splitKey(rest)) + values.push(parseNode(state, column, depth5 + 1)); + else { + state.index += 1; + values.push(parseInlineValue(line, rest, state, indent, depth5)); + } + } + const after = current(state); + if (after && after.indent > indent) + fail(after, "unexpected indentation in a sequence"); + return values; +} +function parseMapping(state, indent, depth5) { + const result = {}; + for (let line = current(state); line && line.indent === indent; line = current(state)) { + const split = splitKey(line.text); + if (!split) + fail(line, "expected a mapping key"); + const key = parseKey(line, split.key); + if (key === "<<") + fail(line, "merge keys are not supported"); + if (Object.prototype.hasOwnProperty.call(result, key)) + fail(line, `duplicate key ${JSON.stringify(key)}`); + state.index += 1; + if (!split.value) { + const next = current(state); + if (next && (next.indent > indent || next.indent === indent && isSequenceItem(next.text))) { + result[key] = parseNode(state, next.indent, depth5 + 1); + } else { + result[key] = null; + } + } else { + result[key] = parseInlineValue(line, split.value, state, indent, depth5); + } + } + const after = current(state); + if (after && after.indent > indent) + fail(after, "unexpected indentation in a mapping"); + return result; +} +function splitKey(text) { + if (isSequenceItem(text) || text.startsWith("{") || text.startsWith("[")) + return void 0; + let index = 0; + if (text.startsWith('"') || text.startsWith("'")) { + const end = closingQuote(text, 0); + if (end === -1) + return void 0; + index = end + 1; + const rest = text.slice(index); + const match = /^\s*:(?:\s|$)/.exec(rest); + if (!match) + return void 0; + return { key: text.slice(0, index), value: rest.slice(match[0].length).trim() }; + } + for (; index < text.length; index += 1) { + if (text[index] === ":" && (index + 1 === text.length || /\s/.test(text[index + 1]))) { + return { key: text.slice(0, index).trimEnd(), value: text.slice(index + 1).trim() }; + } + } + return void 0; +} +function parseKey(line, raw) { + if (raw.startsWith("? ")) + fail(line, "complex mapping keys are not supported"); + if (raw.startsWith('"') || raw.startsWith("'")) + return parseQuoted(line, raw); + if (/^[&*!]/.test(raw)) + fail(line, "anchors, aliases, and tags are not supported"); + return raw; +} +function parseInlineValue(line, value, state, parentIndent, depth5) { + if (/^[&*!]/.test(value)) + fail(line, "anchors, aliases, and tags are not supported"); + if (/^[|>]/.test(value)) + return parseBlockScalar(line, value, state, parentIndent); + if (value.startsWith("{") || value.startsWith("[")) { + let text2 = value; + while (!flowBalanced(text2)) { + const next = current(state); + if (!next || next.indent <= parentIndent) + fail(line, "unterminated flow collection"); + text2 += ` ${next.text}`; + state.index += 1; + } + const parser = { text: text2, index: 0, line }; + const result = parseFlowValue(parser, depth5); + skipSpace(parser); + if (parser.index !== text2.length) + fail(line, "unexpected content after a flow collection"); + return result; + } + if (value.startsWith('"') || value.startsWith("'")) { + let text2 = value; + while (closingQuote(text2, 0) === -1) { + const next = current(state); + if (!next) + fail(line, "unterminated quoted scalar"); + text2 += ` ${next.raw.trim()}`; + state.index += 1; + } + const end = closingQuote(text2, 0); + if (text2.slice(end + 1).trim()) + fail(line, "unexpected content after a quoted scalar"); + return parseQuoted(line, text2); + } + let text = value; + for (let next = current(state); next && next.indent > parentIndent; next = current(state)) { + if (splitKey(next.text) || isSequenceItem(next.text)) + fail(next, "a scalar value cannot also open a nested block"); + text += ` ${next.text}`; + state.index += 1; + } + return resolvePlain(text); +} +function parseBlockScalar(line, header, state, parentIndent) { + const match = /^([|>])([+-]?)(\d?)([+-]?)$/.exec(header.trim()); + if (!match) + fail(line, "unsupported block scalar header"); + const folded = match[1] === ">"; + const chomping = match[2] || match[4]; + const explicit = match[3] ? Number(match[3]) : void 0; + const collected = []; + let contentIndent = explicit !== void 0 ? parentIndent + explicit : void 0; + while (state.index < state.lines.length) { + const next = state.lines[state.index]; + const blank = next.raw.trim() === ""; + const leading = /^ */.exec(next.raw)[0].length; + if (!blank && leading <= parentIndent) + break; + if (!blank) { + contentIndent ??= leading; + if (leading < contentIndent) + fail(next, "block scalar line is less indented than its first line"); + } + collected.push(blank ? "" : next.raw.slice(contentIndent)); + state.index += 1; + } + while (collected.length > 0 && collected.at(-1) === "" && chomping !== "+") + collected.pop(); + let text = folded ? foldLines(collected) : collected.join("\n"); + if (chomping !== "-" && collected.length > 0) + text += "\n"; + return text; +} +function foldLines(lines) { + let result = ""; + for (let index = 0; index < lines.length; index += 1) { + const line = lines[index]; + if (index === 0) { + result = line; + continue; + } + const previous = lines[index - 1]; + if (line === "") + result += "\n"; + else if (previous === "" || /^\s/.test(line) || /^\s/.test(previous)) + result += (previous === "" ? "" : "\n") + line; + else + result += ` ${line}`; + } + return result; +} +function resolvePlain(text) { + const value = text.trim(); + if (value === "" || value === "~" || /^(?:null|Null|NULL)$/.test(value)) + return null; + if (/^(?:true|True|TRUE)$/.test(value)) + return true; + if (/^(?:false|False|FALSE)$/.test(value)) + return false; + if (/^[-+]?(?:0|[1-9][0-9]*)$/.test(value)) { + const numeric = Number(value); + return Number.isSafeInteger(numeric) ? numeric : value; + } + if (/^[-+]?(?:[0-9]+\.[0-9]*|\.[0-9]+)(?:[eE][-+]?[0-9]+)?$/.test(value) || /^[-+]?[0-9]+[eE][-+]?[0-9]+$/.test(value)) + return Number(value); + return value; +} +function closingQuote(text, start) { + const quote = text[start]; + for (let index = start + 1; index < text.length; index += 1) { + if (quote === '"' && text[index] === "\\") { + index += 1; + continue; + } + if (text[index] === quote) { + if (quote === "'" && text[index + 1] === "'") { + index += 1; + continue; + } + return index; + } + } + return -1; +} +function parseQuoted(line, text) { + const end = closingQuote(text, 0); + if (end === -1) + fail(line, "unterminated quoted scalar"); + const body = text.slice(1, end); + if (text[0] === "'") + return body.replace(/''/g, "'"); + return body.replace(/\\(u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|.)/g, (_, escape) => { + if (escape.length > 1) + return String.fromCharCode(parseInt(escape.slice(1), 16)); + const simple = { n: "\n", t: " ", r: "\r", "0": "\0", '"': '"', "\\": "\\", "/": "/", " ": " ", b: "\b", f: "\f" }; + if (!(escape in simple)) + fail(line, `unsupported escape \\${escape}`); + return simple[escape]; + }); +} +function flowBalanced(text) { + let depth5 = 0; + let quote; + for (let index = 0; index < text.length; index += 1) { + const char = text[index]; + if (quote) { + if (quote === '"' && char === "\\") + index += 1; + else if (char === quote) + quote = void 0; + } else if (char === '"' || char === "'") + quote = char; + else if (char === "{" || char === "[") + depth5 += 1; + else if (char === "}" || char === "]") + depth5 -= 1; + } + return depth5 <= 0 && !quote; +} +function skipSpace(parser) { + while (parser.index < parser.text.length && /\s/.test(parser.text[parser.index])) + parser.index += 1; +} +function parseFlowValue(parser, depth5) { + if (depth5 > MAX_DEPTH) + throw new YamlSubsetError("YAML nesting is deeper than FixMap reads"); + skipSpace(parser); + const char = parser.text[parser.index]; + if (char === "{") + return parseFlowMapping(parser, depth5 + 1); + if (char === "[") + return parseFlowSequence(parser, depth5 + 1); + if (char === '"' || char === "'") { + const end = closingQuote(parser.text, parser.index); + if (end === -1) + fail(parser.line, "unterminated quoted scalar"); + const value = parseQuoted(parser.line, parser.text.slice(parser.index, end + 1)); + parser.index = end + 1; + return value; + } + if (char !== void 0 && /[&*!]/.test(char)) + fail(parser.line, "anchors, aliases, and tags are not supported"); + const start = parser.index; + while (parser.index < parser.text.length && !/[,\]}]/.test(parser.text[parser.index]) && !(parser.text[parser.index] === ":" && /[\s,\]}]/.test(parser.text[parser.index + 1] ?? " "))) + parser.index += 1; + return resolvePlain(parser.text.slice(start, parser.index)); +} +function parseFlowSequence(parser, depth5) { + parser.index += 1; + const values = []; + skipSpace(parser); + if (parser.text[parser.index] === "]") { + parser.index += 1; + return values; + } + for (; ; ) { + values.push(parseFlowValue(parser, depth5)); + skipSpace(parser); + const char = parser.text[parser.index]; + parser.index += 1; + if (char === "]") + return values; + if (char !== ",") + fail(parser.line, "expected , or ] in a flow sequence"); + skipSpace(parser); + if (parser.text[parser.index] === "]") { + parser.index += 1; + return values; + } + } +} +function parseFlowMapping(parser, depth5) { + parser.index += 1; + const result = {}; + skipSpace(parser); + if (parser.text[parser.index] === "}") { + parser.index += 1; + return result; + } + for (; ; ) { + const keyValue = parseFlowValue(parser, depth5); + if (keyValue !== null && typeof keyValue === "object") + fail(parser.line, "complex mapping keys are not supported"); + const key = keyValue === null ? "" : String(keyValue); + if (key === "<<") + fail(parser.line, "merge keys are not supported"); + if (Object.prototype.hasOwnProperty.call(result, key)) + fail(parser.line, `duplicate key ${JSON.stringify(key)}`); + skipSpace(parser); + if (parser.text[parser.index] === ":") { + parser.index += 1; + skipSpace(parser); + const next = parser.text[parser.index]; + result[key] = next === "," || next === "}" ? null : parseFlowValue(parser, depth5); + } else { + result[key] = null; + } + skipSpace(parser); + const char = parser.text[parser.index]; + parser.index += 1; + if (char === "}") + return result; + if (char !== ",") + fail(parser.line, "expected , or } in a flow mapping"); + skipSpace(parser); + if (parser.text[parser.index] === "}") { + parser.index += 1; + return result; + } + } +} +function fail(line, message2) { + throw new YamlSubsetError(`line ${line.number}: ${message2}`); +} + // packages/core/dist/contracts.js var HTTP_METHODS = /* @__PURE__ */ new Set(["get", "put", "post", "delete", "options", "head", "patch", "trace"]); var CONTRACT_PATH = /(?:^|\/)(?:openapi|swagger|asyncapi)(?:\.[^/]+)?\.(?:json|ya?ml)$|\.(?:graphql|gql|proto)$|(?:^|\/)migrations?\/.*\.sql$|\.schema\.json$/i; @@ -8137,7 +8566,7 @@ function contractSourcesFromRepo(repo) { const sources = []; const diagnostics = []; for (const file of repo.files.filter((candidate) => isContractCandidate(candidate.path, candidate.textSample))) { - if (file.textSampleComplete === false || !file.contentFingerprint) { + if (file.textSampleComplete === false || !file.contentFingerprint || !file.isSource) { diagnostics.push({ code: "contract-source-incomplete", severity: "warning", @@ -8180,23 +8609,38 @@ function parseContract(source) { } return parsed(source, "graphql", graphql); } - if (lower.endsWith(".proto")) - return parsed(source, "protobuf", parseProtobuf(source.content)); + if (lower.endsWith(".proto")) { + const syntax = /^\s*(?:syntax|edition)\s*=\s*["']([^"']+)["']/m.exec(source.content.replace(/\/\/[^\r\n]*/g, ""))?.[1]; + return parsed(source, "protobuf", { ...parseProtobuf(source.content), ...syntax ? { version: syntax } : {} }); + } if (/(?:^|\/)migrations?\/.*\.sql$/i.test(source.path)) return parsed(source, "migration", parseMigration(source.content)); const json = parseJson(source.content); - if (json) { - if (typeof json.openapi === "string" || typeof json.swagger === "string") - return parsed(source, "openapi", parseOpenApiJson(json)); - if (typeof json.asyncapi === "string") - return parsed(source, "asyncapi", parseAsyncApiJson(json)); - if (typeof json.$schema === "string" || isRecord7(json.properties)) - return parsed(source, "json-schema", parseJsonSchema(json)); - } - if (/^\s*(?:openapi|swagger)\s*:/m.test(source.content)) - return parsed(source, "openapi", parseOpenApiYaml(source.content)); - if (/^\s*asyncapi\s*:/m.test(source.content)) - return parsed(source, "asyncapi", parseAsyncApiYaml(source.content)); + if (json) + return parsedStructured(source, json); + const yamlLike = /\.ya?ml$/i.test(source.path) || /^\s*(?:openapi|swagger|asyncapi)\s*:/m.test(source.content); + if (yamlLike) { + let document; + try { + document = parseYamlSubset(source.content); + } catch (error) { + if (!(error instanceof YamlSubsetError)) + throw error; + return parseFailed(source, `YAML ${error.message}.`); + } + if (isRecord7(document)) { + for (const key of ["openapi", "swagger", "asyncapi"]) { + if (typeof document[key] !== "number") + continue; + const written = new RegExp(`^${key}\\s*:\\s*([^\\s#]+)`, "m").exec(source.content)?.[1]; + if (written) + document[key] = written; + } + const structured = parsedStructured(source, document); + if (structured.surface || structured.diagnostic) + return structured; + } + } if (CONTRACT_PATH.test(source.path)) { return { diagnostic: { @@ -8209,6 +8653,31 @@ function parseContract(source) { } return {}; } +function parsedStructured(source, document) { + const openapi = specVersion(document.openapi) ?? specVersion(document.swagger); + if (openapi) + return parsed(source, "openapi", { ...parseOpenApiJson(document), version: openapi }); + const asyncapi = specVersion(document.asyncapi); + if (asyncapi) + return parsed(source, "asyncapi", { ...parseAsyncApiJson(document), version: asyncapi }); + if (typeof document.$schema === "string" || isRecord7(document.properties)) { + return parsed(source, "json-schema", { + ...parseJsonSchema(document), + ...typeof document.$schema === "string" ? { version: document.$schema } : {} + }); + } + if (CONTRACT_PATH.test(source.path)) { + return parseFailed(source, "the document has no openapi, swagger, asyncapi, $schema, or properties marker."); + } + return {}; +} +function specVersion(value) { + if (typeof value === "string" && value.trim()) + return value.trim(); + if (typeof value === "number" && Number.isFinite(value)) + return String(value); + return void 0; +} function parseFailed(source, detail) { return { diagnostic: { @@ -8226,6 +8695,7 @@ function parsed(source, kind, parsedSurface) { kind, path: source.path.replace(/\\/g, "/"), name: parsedSurface.name ?? source.path.split(/[\\/]/).at(-1) ?? source.path, + ...parsedSurface.version ? { version: parsedSurface.version } : {}, sourceFingerprint: source.fingerprint, entries: normalizeEntries(parsedSurface.entries) } @@ -8361,50 +8831,6 @@ function parseMigration(content) { } return { entries }; } -function parseOpenApiYaml(content) { - return parseChannelYaml(content, "paths", HTTP_METHODS); -} -function parseAsyncApiYaml(content) { - return parseChannelYaml(content, "channels", /* @__PURE__ */ new Set(["publish", "subscribe"])); -} -function parseChannelYaml(content, sectionName, operations) { - const entries = []; - const lines = content.split(/\r?\n/); - let inSection = false; - let sectionIndent = -1; - let currentPath; - let pathIndent = -1; - for (const raw of lines) { - const withoutComment = raw.replace(/\s+#.*$/, ""); - const trimmed = withoutComment.trim(); - if (!trimmed) - continue; - const indent = withoutComment.length - withoutComment.trimStart().length; - if (!inSection && trimmed === `${sectionName}:`) { - inSection = true; - sectionIndent = indent; - continue; - } - if (!inSection) - continue; - if (indent <= sectionIndent) - break; - const key = /^([^:]+):\s*$/.exec(trimmed)?.[1]?.trim(); - if (!key) - continue; - if (indent > sectionIndent && (currentPath === void 0 || indent <= pathIndent)) { - currentPath = unquote2(key); - pathIndent = indent; - continue; - } - if (currentPath && indent > pathIndent && operations.has(key.toLowerCase())) { - const operation = sectionName === "paths" ? `${key.toUpperCase()} ${currentPath}` : `${key.toLowerCase()} ${currentPath}`; - entries.push(entry(`operation:${sectionName === "paths" ? operation : `${key.toLowerCase()}:${currentPath}`}`, "operation", operation)); - } - } - const title = content.match(/^\s*title\s*:\s*["']?([^\r\n"']+)/m)?.[1]?.trim(); - return { ...title ? { name: title } : {}, entries }; -} function entry(key, role, signature, required = false) { return { key, role, signature: signature.trim(), required }; } @@ -8456,9 +8882,6 @@ function parseJson(content) { function isRecord7(value) { return typeof value === "object" && value !== null && !Array.isArray(value); } -function unquote2(value) { - return value.replace(/^["']|["']$/g, ""); -} function stableHash3(value) { let hash = 0xcbf29ce484222325n; for (const byte of new TextEncoder().encode(value)) { @@ -8470,7 +8893,7 @@ function stableHash3(value) { // packages/core/dist/change-scope.js var MAX_ANCHORS = 64; -var MAX_DEPTH = 8; +var MAX_DEPTH2 = 8; var MAX_NODES = 2e3; function buildChangeScope(repo, input) { if (!Number.isFinite(Date.parse(input.asOf))) @@ -8532,13 +8955,13 @@ function buildChangeScope(repo, input) { const visited = new Set(selectedPaths.keys()); const queue = [...selectedPaths.keys()].map((path) => ({ path, distance: 0 })); while (queue.length > 0) { - const current = queue.shift(); - if (current.distance >= traversal.maxDepth) + const current2 = queue.shift(); + if (current2.distance >= traversal.maxDepth) continue; - for (const neighbor of scopeNeighbors(graph, current.path, traversal.direction)) { + for (const neighbor of scopeNeighbors(graph, current2.path, traversal.direction)) { if (visited.has(neighbor.path)) { const existing = affected.get(neighbor.path); - if (existing && current.distance + 1 <= existing.distance && !existing.evidence.some((entry2) => evidenceKey2(entry2) === evidenceKey2(neighbor.evidence))) { + if (existing && current2.distance + 1 <= existing.distance && !existing.evidence.some((entry2) => evidenceKey2(entry2) === evidenceKey2(neighbor.evidence))) { existing.evidence.push(neighbor.evidence); existing.evidence.sort((left, right) => left.kind.localeCompare(right.kind) || left.reason.localeCompare(right.reason)); } @@ -8549,7 +8972,7 @@ function buildChangeScope(repo, input) { continue; } visited.add(neighbor.path); - const distance = current.distance + 1; + const distance = current2.distance + 1; affected.set(neighbor.path, { distance, evidence: [neighbor.evidence] }); queue.push({ path: neighbor.path, distance }); } @@ -8640,8 +9063,8 @@ function normalizeTraversal(input) { } const maxDepth = input.maxDepth ?? 2; const maxNodes = input.maxNodes ?? 200; - if (!Number.isSafeInteger(maxDepth) || maxDepth < 0 || maxDepth > MAX_DEPTH) { - throw new Error(`Change-scope maxDepth must be an integer from 0 to ${MAX_DEPTH}.`); + if (!Number.isSafeInteger(maxDepth) || maxDepth < 0 || maxDepth > MAX_DEPTH2) { + throw new Error(`Change-scope maxDepth must be an integer from 0 to ${MAX_DEPTH2}.`); } if (!Number.isSafeInteger(maxNodes) || maxNodes < 1 || maxNodes > MAX_NODES) { throw new Error(`Change-scope maxNodes must be an integer from 1 to ${MAX_NODES}.`); @@ -9432,21 +9855,21 @@ function capabilitySnapshot(historical, id, asOf) { testAssociations }; } -function comparePaths(previous, current) { - return compareMaps(new Map(previous.map((entry2) => [entry2.path, entry2.sourceFingerprint ?? "unknown"])), new Map(current.map((entry2) => [entry2.path, entry2.sourceFingerprint ?? "unknown"]))); +function comparePaths(previous, current2) { + return compareMaps(new Map(previous.map((entry2) => [entry2.path, entry2.sourceFingerprint ?? "unknown"])), new Map(current2.map((entry2) => [entry2.path, entry2.sourceFingerprint ?? "unknown"]))); } -function compareEntities(previous, current) { - return compareMaps(new Map(previous.map((entry2) => [entry2.id, entry2.fingerprint])), new Map(current.map((entry2) => [entry2.id, entry2.fingerprint]))); +function compareEntities(previous, current2) { + return compareMaps(new Map(previous.map((entry2) => [entry2.id, entry2.fingerprint])), new Map(current2.map((entry2) => [entry2.id, entry2.fingerprint]))); } -function compareMaps(previous, current) { - const keys = [.../* @__PURE__ */ new Set([...previous.keys(), ...current.keys()])].sort(); +function compareMaps(previous, current2) { + const keys = [.../* @__PURE__ */ new Set([...previous.keys(), ...current2.keys()])].sort(); const result = { added: [], removed: [], modified: [], unchanged: [] }; for (const key of keys) { if (!previous.has(key)) result.added.push(key); - else if (!current.has(key)) + else if (!current2.has(key)) result.removed.push(key); - else if (previous.get(key) !== current.get(key)) + else if (previous.get(key) !== current2.get(key)) result.modified.push(key); else result.unchanged.push(key); @@ -10284,19 +10707,19 @@ function trimToBoundary(text) { } function splitExcludeInput(raw) { const patterns2 = []; - let current = ""; + let current2 = ""; let depth5 = 0; for (const character of raw) { if (character === "{") depth5 += 1; else if (character === "}") depth5 = Math.max(0, depth5 - 1); if (character === "\n" || character === "\r" || character === "," && depth5 === 0) { - patterns2.push(current); - current = ""; + patterns2.push(current2); + current2 = ""; continue; } - current += character; + current2 += character; } - patterns2.push(current); + patterns2.push(current2); return patterns2.map((pattern) => pattern.trim()).filter(Boolean); } function fitStepSummary(markdown, limitBytes = STEP_SUMMARY_LIMIT_BYTES) { From 929e091c70876240b1ecd9d00941b2fa5269c577 Mon Sep 17 00:00:00 2001 From: Aryam Goyal Date: Sun, 22 Nov 2026 20:20:53 +0530 Subject: [PATCH 8/9] fix(cli): compare real paths before refusing contracts --output overwrites The repository root was realpath'd but the --output path was not, so on macOS (/var vs /private/var), through a symlinked directory, or a Windows junction, an output inside the repository looked outside it and an existing repository file was overwritten. Resolve the output's nearest existing directory through realpath (the leaf stays unresolved so a symlinked output file is still refused) and add a regression using a directory alias. Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/contracts-command.ts | 24 +++++++++++++++-- packages/cli/test/contracts-command.test.ts | 29 ++++++++++++++++++++- 2 files changed, 50 insertions(+), 3 deletions(-) diff --git a/packages/cli/src/contracts-command.ts b/packages/cli/src/contracts-command.ts index 194e78a5..93d48acf 100644 --- a/packages/cli/src/contracts-command.ts +++ b/packages/cli/src/contracts-command.ts @@ -1,6 +1,6 @@ import { lstat, readFile, realpath, stat, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; -import { isAbsolute, relative, resolve, sep } from "node:path"; +import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path"; import { compareContractRefs, inventoryWorkingTreeContracts, @@ -201,7 +201,11 @@ async function repositoryRoot(input: string): Promise { /** Refuses to overwrite a repository file unless it is a prior FixMap artifact. */ async function assertOutputSafe(repoRoot: string, output: string): Promise { - const absolute = resolve(output); + // repoRoot is a real path, so the output must be too: otherwise an alias such as macOS + // /var -> /private/var, a symlinked directory, or a Windows junction looks "outside". + // Only the directory is resolved, so a symlinked output file itself is still refused below. + const requested = resolve(output); + const absolute = resolve(await realOutputPath(dirname(requested)), basename(requested)); const outputRelative = relative(repoRoot, absolute); if (!outputRelative || outputRelative === ".." || outputRelative.startsWith(`..${sep}`) || isAbsolute(outputRelative)) return; const info = await lstat(absolute).catch(() => undefined); @@ -213,6 +217,22 @@ async function assertOutputSafe(repoRoot: string, output: string): Promise } } +/** Resolves the nearest existing ancestor through realpath and keeps the not-yet-existing tail. */ +async function realOutputPath(absolute: string): Promise { + const tail: string[] = []; + let current = absolute; + for (;;) { + try { + return resolve(await realpath(current), ...tail.reverse()); + } catch { + const parent = dirname(current); + if (parent === current) return absolute; + tail.push(basename(current)); + current = parent; + } + } +} + function contractsError(repo: string, error: unknown): string { const text = message(error); if (text === "not-directory") return `Contracts repository "${repo}" does not exist or is not a directory.`; diff --git a/packages/cli/test/contracts-command.test.ts b/packages/cli/test/contracts-command.test.ts index f3172055..92b47ff9 100644 --- a/packages/cli/test/contracts-command.test.ts +++ b/packages/cli/test/contracts-command.test.ts @@ -1,5 +1,5 @@ import { execFile } from "node:child_process"; -import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { promisify } from "node:util"; @@ -329,4 +329,31 @@ describe("contracts command", () => { } expect(JSON.parse(await readFile(target, "utf8")).contractListVersion).toBe(1); }, GIT_TEST_TIMEOUT); + + it("refuses repository overwrites through a realpath-aliased directory", async () => { + // macOS tmpdir is /var/... while realpath is /private/var/...; a directory link reproduces + // that alias on every platform (a junction on Windows needs no extra privilege). + const root = await repository(); + await commit(root, { "schema.graphql": "type Query { ok: Boolean }\n", "docs/notes.md": "keep me\n" }, "only"); + const aliasParent = await mkdtemp(join(tmpdir(), "fixmap-contracts-alias-")); + roots.push(aliasParent); + const alias = join(aliasParent, "repo-alias"); + await symlink(root, alias, process.platform === "win32" ? "junction" : "dir"); + + for (const [repoArg, outputArg] of [ + [root, join(alias, "docs", "notes.md")], + [alias, join(root, "docs", "notes.md")], + [alias, join(alias, "docs", "notes.md")] + ] as const) { + const io = capture(); + expect(await runCli(["contracts", "--repo", repoArg, "--output", outputArg], io.dependencies)).toBe(1); + expect(io.stderr.join("")).toContain("--output refuses to overwrite repository file docs/notes.md"); + } + expect(await readFile(join(root, "docs", "notes.md"), "utf8")).toBe("keep me\n"); + + // A new file under a not-yet-existing directory inside the aliased repository is allowed. + const fresh = capture(); + expect(await runCli(["contracts", "--repo", root, "--output", join(alias, "out", "contracts.md")], { ...fresh.dependencies, writeReport: async () => {} })).toBe(0); + expect(fresh.stderr).toEqual([]); + }, GIT_TEST_TIMEOUT); }); From 363a4a8fb3958959748b8a5103723a9b71700377 Mon Sep 17 00:00:00 2001 From: Aryam Goyal Date: Sun, 22 Nov 2026 20:26:37 +0530 Subject: [PATCH 9/9] release: FixMap v0.9.5 Integrates #688 (outcomes and dossiers), #689 (reviewer suggestions), #690 (architecture drift and historical plans), and #691 (Contract Guardian) on top of #686 (evidence attachment) and #687 (Action change scope and capabilities), with the Action bundle rebuilt once for the merged result. Bumps versions to 0.9.5, adds CHANGELOG.md and website changelog entries, and records progress on each ledger row. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 13 + README.md | 2 +- apps/web/app/changelog/page.tsx | 24 +- apps/web/package.json | 2 +- .../releases/v0.10.0-implementation-ledger.md | 16 +- package-lock.json | 16 +- package.json | 2 +- packages/action/dist/index.mjs | 631 ++++++++++-------- packages/action/package.json | 4 +- packages/cli/package.json | 4 +- packages/core/package.json | 2 +- server.json | 4 +- 12 files changed, 412 insertions(+), 308 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ec7b2dcc..7be2e5a6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,19 @@ Accuracy figures inside a released entry are the numbers measured **at that rele left as written. The current numbers live on the [evidence page](https://fixmap.aryam.me/evidence), which is generated from the recorded results rather than transcribed by hand. +## 0.9.5 - 2026-11-22 + +Every addition in this release is a preview: it works and is tested, but its output and options may change before v0.10.0. + +### Added + +- `fixmap plan --evidence ` (and MCP `fixmap_plan` `evidence`) attaches findings from other tools to the files in a plan. Bundles are data only and never executed; claims are labelled as unverified and unrelated items are counted rather than dropped silently. +- `fixmap contracts` and `fixmap contracts diff ..` list OpenAPI, AsyncAPI, GraphQL, Protobuf, JSON Schema, and SQL migration contracts and classify changes between two exact Git refs as compatible, breaking, or unknown, without a checkout. YAML specs behave like JSON. MCP: `fixmap_contracts`. +- `fixmap history` now reports architecture drift between two refs (added and removed imports, cycles, policy violations, coupling growth) and decision disagreements where an accepted architecture decision record's explicit rule is broken. Snapshots are cached per commit. `fixmap plan --at ` ranks against the repository as it was at a commit. +- `fixmap reviewers` suggests reviewers from CODEOWNERS, annotation owners, architecture policy, and history, with `.mailmap` support and `--no-history-authors`. Names are never written with `@`, so nobody is notified. MCP: `fixmap_reviewers`. +- `fixmap outcome` and `fixmap dossier` save prediction outcomes and change dossiers under `.fixmap/` with atomic writes, `--redact`, pruning, and calibration that never changes ranking weights. MCP: `fixmap_outcomes`, `fixmap_dossier`. +- The GitHub Action accepts `change-scope-touch`, `change-scope-add`, and `capability` to add change-scope and capability-map sections to its pull request comment. + ## 0.9.4 - 2026-11-22 ### Fixed diff --git a/README.md b/README.md index 51971503..4ba3190c 100644 --- a/README.md +++ b/README.md @@ -469,7 +469,7 @@ jobs: - uses: actions/checkout@v7 with: fetch-depth: 0 - - uses: aryamthecodebreaker/FixMap@v0.9.4 + - uses: aryamthecodebreaker/FixMap@v0.9.5 with: github-token: ${{ secrets.GITHUB_TOKEN }} ``` diff --git a/apps/web/app/changelog/page.tsx b/apps/web/app/changelog/page.tsx index 66ccf94a..8a0b5283 100644 --- a/apps/web/app/changelog/page.tsx +++ b/apps/web/app/changelog/page.tsx @@ -44,9 +44,31 @@ type Release = { const releases: Release[] = [ { - version: "0.9.4", + version: "0.9.5", date: "November 22, 2026", label: "Latest release", + summary: "Six previews: other tools' findings in plans, API contract checks, architecture drift and historical plans, reviewer suggestions, saved outcomes and dossiers, and new GitHub Action sections.", + groups: [ + { + label: "Added", + items: [ + "fixmap plan --evidence attaches findings from scanners, CI, or monitoring tools to the files in a plan, labelled as the tool's claim and never executed.", + "fixmap contracts lists API and schema contracts and classifies changes between two Git refs as compatible, breaking, or unknown.", + "fixmap history reports architecture drift and broken architecture decisions between two commits, and fixmap plan --at ranks against an older commit.", + "fixmap reviewers suggests reviewers from CODEOWNERS, notes, policy, and history without notifying anyone.", + "fixmap outcome and fixmap dossier save what a plan predicted against what changed, locally and with optional redaction.", + "The GitHub Action can add change-scope and capability-map sections to pull request comments." + ] + }, + { + label: "Improved", + items: ["All six are previews: they work and are tested, but may change before v0.10.0."] + } + ] + }, + { + version: "0.9.4", + date: "November 22, 2026", summary: "Local semantic search now finishes on large repositories, and an honest test on 28 never-seen projects keeps language support in preview because Java missed.", groups: [ { diff --git a/apps/web/package.json b/apps/web/package.json index a05cf785..f379d4db 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -17,7 +17,7 @@ "typecheck": "tsc --noEmit" }, "dependencies": { - "@aryam/fixmap-core": "0.9.4", + "@aryam/fixmap-core": "0.9.5", "@phosphor-icons/react": "^2.1.10", "next": "16.4.6", "react": "19.2.7", diff --git a/docs/releases/v0.10.0-implementation-ledger.md b/docs/releases/v0.10.0-implementation-ledger.md index f10b06bd..a0a15ce5 100644 --- a/docs/releases/v0.10.0-implementation-ledger.md +++ b/docs/releases/v0.10.0-implementation-ledger.md @@ -280,20 +280,20 @@ with one existing skip; the rebuilt Action artifact passes its freshness check. | Hybrid retrieval | in progress | Shipped Core preserves structural evidence scores and adds bounded whole-file BM25 and symbol-rank evidence; optional cosine ranks remain local and provenance-bearing. A separate development-only RRF artifact tests rank-only fusion without changing Core or established baseline artifacts. Direct repository evidence is preserved, remote providers are opt-in, failures fall back safely, and every shipped signal is explained through Core, reports, CLI, MCP, Context Packs, and graph export. An unseen post-change cohort, Action suitability, and measured semantic evaluation remain. | | Semantic index provenance | implemented | Local model bundles are fully hashed; runtime, dimensions, normalization, model identity, cache key, indexed/omitted scope, and disabled/failure behavior are recorded. The persistent cache is atomic, model-isolated, corruption-healing, and outside the repository. Candidate-scale performance evidence remains. Candidate-scale evidence 2026-11-22 (scripts/benchmark-semantic.mjs, all-MiniLM-L6-v2, @huggingface/transformers 3.8.1, CPU): 173 embedded files cost a 25.6 s cold first run and 1.7 s warm versus 0.94 s structural-only, with identical warm/cold rankings. A 1,000-candidate cold run exceeds the 120 s budget on CPU, so misses are now embedded in batches of 16 and every finished batch is persisted, letting repeated runs converge to a warm cache. | | Decision-relevant context optimization | planned | Context selection beats or ties the current pack at equal token budgets on frozen tasks without hiding omissions. | -| Explicit-anchor change scope | in progress | A browser-safe Core engine and `fixmap change-scope` CLI/`fixmap_change_scope` MCP surfaces now expand caller-supplied touch/add paths through allowlisted import/dependent edges with stable file identities, cycle-safe BFS, mandatory depth/node bounds, and visible unresolved/truncated state. Existing test routes, contracts, ADRs, CODEOWNERS/annotations/history reviewers, and architecture findings join with provenance; unrelated malformed contract/ADR surfaces stay isolated. Markdown/JSON output reports exact declared/observed/derived/unresolved counts and generated outputs are self-excluded. Cross-repository traversal, runtime/CI joins, historical comparison, Action/editor parity, and held-out product-building fixtures remain. No LLM, API, account, or semantic product inference is permitted. | -| Persistent product capability map | in progress | A strict versioned `.fixmap/capabilities.json` records human-owned capability names, explicit anchors, workspace/repository identity, and traversal bounds; unknown/generated conclusion fields fail validation. CLI create/update/remove uses repository-contained directory checks, a bounded stale lock, atomic temp-file replacement, and symlink/hardlink refusal. CLI and read-only MCP list/show rebuild current evidence with the exact store fingerprint. Core/CLI/MCP exact-ref diff reads immutable Git objects without checkout mutation and compares definition, selected/affected paths, content fingerprints, contracts, decisions, test associations, reviewers, and architecture findings while preserving absent-before state. Rename-aware identity continuity, MCP mutation, cross-repository evidence, Action/editor parity, and held-out fixtures remain. Exact declared/observed/derived/unresolved counts replace undefinable confidence percentages. | +| Explicit-anchor change scope | in progress | A browser-safe Core engine and `fixmap change-scope` CLI/`fixmap_change_scope` MCP surfaces now expand caller-supplied touch/add paths through allowlisted import/dependent edges with stable file identities, cycle-safe BFS, mandatory depth/node bounds, and visible unresolved/truncated state. Existing test routes, contracts, ADRs, CODEOWNERS/annotations/history reviewers, and architecture findings join with provenance; unrelated malformed contract/ADR surfaces stay isolated. Markdown/JSON output reports exact declared/observed/derived/unresolved counts and generated outputs are self-excluded. Cross-repository traversal, runtime/CI joins, historical comparison, Action/editor parity, and held-out product-building fixtures remain. No LLM, API, account, or semantic product inference is permitted. 0.9.5 (2026-11-22, PR #687): GitHub Action parity via preview `change-scope-touch`/`change-scope-add` inputs and the `change-scope-affected-count` output. | +| Persistent product capability map | in progress | A strict versioned `.fixmap/capabilities.json` records human-owned capability names, explicit anchors, workspace/repository identity, and traversal bounds; unknown/generated conclusion fields fail validation. CLI create/update/remove uses repository-contained directory checks, a bounded stale lock, atomic temp-file replacement, and symlink/hardlink refusal. CLI and read-only MCP list/show rebuild current evidence with the exact store fingerprint. Core/CLI/MCP exact-ref diff reads immutable Git objects without checkout mutation and compares definition, selected/affected paths, content fingerprints, contracts, decisions, test associations, reviewers, and architecture findings while preserving absent-before state. Rename-aware identity continuity, MCP mutation, cross-repository evidence, Action/editor parity, and held-out fixtures remain. Exact declared/observed/derived/unresolved counts replace undefinable confidence percentages. 0.9.5 (PR #687): GitHub Action parity via the preview `capability` input, including the read-only base-vs-head capability diff. | ## System intelligence | Capability | Status | Acceptance evidence | | --- | --- | --- | | Cross-repository workspace model | in progress | Multiple checkouts plus Node, Python, and Maven packages, versions, submodules, manifest/import consumers, exact source derivations, stable graph identities, and explicit enrichment nodes/edges form one provenance-preserving graph. The versioned local `fixmap workspace` CLI and `fixmap_workspace` MCP workflows validate 1-32 relative checkouts, reject duplicate real roots and remote paths, scan four repositories concurrently without executing code, and traverse provider-to-consumer impact from repeatable seeds in deterministic Markdown/JSON. Action parity, service/catalog/registry discovery, aliases in config, cross-repository Context/Verify narration, and held-out evidence remain. | -| Contract Guardian | in progress | Core inventories exact-version OpenAPI, AsyncAPI, GraphQL, Protobuf, JSON Schema, and SQL migration surfaces; emits deterministic compatible/breaking/unknown deltas with before/after fingerprints; and converts contracts into hierarchically owned graph nodes. YAML schema details, public-language APIs, known-consumer edges, CLI/MCP/Action parity, and held-out evidence remain. | +| Contract Guardian | in progress | Core inventories exact-version OpenAPI, AsyncAPI, GraphQL, Protobuf, JSON Schema, and SQL migration surfaces; emits deterministic compatible/breaking/unknown deltas with before/after fingerprints; and converts contracts into hierarchically owned graph nodes. YAML schema details, public-language APIs, known-consumer edges, CLI/MCP/Action parity, and held-out evidence remain. 0.9.5 (PR #691): CLI `fixmap contracts` list/diff over exact refs without checkout, MCP `fixmap_contracts`, and YAML/JSON delta parity, with tests for malformed specs, unknown refs, and unchanged HEAD/status. Action parity and held-out evidence remain. | | ADR and rationale ingestion | implemented | Local ADR/PR-export ingestion preserves authored text, original and normalized status, dates, supersession references, exact fingerprints, and explicitly unverified local attribution without fetching. Workspace rationale/mention edges preserve identity and invalidation boundaries. Report, Context, Ask, Verify, change-scope, reverse-docs, and editor consumers retain evidence. Real CLI/Action/MCP parity and edit/exclusion/removal checks pass. Seven development documents across two conventions exposed repaired omissions; two additional same-repository documents passed field checks without parser changes (narrow validation, not broad generalization). Core checkpoint: 812 passed, one skipped. Exact implementation 0a9d6ab passes CI 34805930550 with four rationale process checks and external evaluation 34805930587. See docs/releases/decisions-acceptance.md. | | `fixmap annotate` | implemented | Durable Core/CLI/MCP/Action add/list/remove, declared file/symbol/service/contract scopes, owner/expiry, contained targets, atomic locking, and relevant Markdown/JSON/agent evidence are implemented. Real Git rename warnings preserve authored scope; bounded named-scope matching avoids substring pollution. The final focused sweep passes 36 tests across eight files. Packed cross-process lock/removal checks passed all four CI compatibility environments. Three pinned external workflows pass Core/CLI/Action and two separately frozen held-out JS/Python workflows pass Core/CLI/Action/MCP, including exact provenance and removal freshness. See `docs/releases/annotations-acceptance.md` and `docs/annotations.md` for evidence and explicit ownership/identity limits. Broader reviewer routing and enterprise authentication remain separate capabilities; final candidate-wide release gates still apply. | | Architecture policy | in progress | A bounded, versioned `.fixmap/policy.json` now enforces dependency boundaries, required test changes, required reviewers, and caller-supplied breaking-contract comparisons with exact policy provenance. Plan and Verify share the evaluator, machine-readable finding codes, Markdown/agent output, and evidence-backed Verify narration; contract baseline wiring, CLI authoring help, and held-out evidence remain. | -| Architecture drift | in progress | Core builds deterministic, exact-source architecture snapshots and compares added/removed import edges, cyclic components, boundary violations, and coupling growth. Historical-ref CLI integration, ADR disagreement, snapshot persistence, and held-out evidence remain. | -| Time-travel graph | in progress | Core resolves historical refs to immutable commit IDs, reads bounded exact Git blobs without checkout/worktree mutation, builds deterministic architecture snapshots, and compares two refs for drift. The `fixmap history` CLI and `fixmap_history` MCP tool now expose Markdown/JSON comparisons with both commit IDs, snapshot fingerprints, added/removed edges, new/resolved cycles and policy violations, and coupling growth. Argument bounds fail before Git, failures do not leak child commands, and integration tests prove HEAD/status remain unchanged. Historical Plan queries, snapshot caching, odd-path held-out fixtures, Action/editor parity, and performance evidence remain. | +| Architecture drift | in progress | Core builds deterministic, exact-source architecture snapshots and compares added/removed import edges, cyclic components, boundary violations, and coupling growth. Historical-ref CLI integration, ADR disagreement, snapshot persistence, and held-out evidence remain. 0.9.5 (PR #690): historical-ref CLI integration and ADR disagreement reporting implemented, with per-commit snapshot caching; held-out evidence remains. | +| Time-travel graph | in progress | Core resolves historical refs to immutable commit IDs, reads bounded exact Git blobs without checkout/worktree mutation, builds deterministic architecture snapshots, and compares two refs for drift. The `fixmap history` CLI and `fixmap_history` MCP tool now expose Markdown/JSON comparisons with both commit IDs, snapshot fingerprints, added/removed edges, new/resolved cycles and policy violations, and coupling growth. Argument bounds fail before Git, failures do not leak child commands, and integration tests prove HEAD/status remain unchanged. Historical Plan queries, snapshot caching, odd-path held-out fixtures, Action/editor parity, and performance evidence remain. 0.9.5 (PR #690): historical Plan queries (`fixmap plan --at `) and snapshot caching implemented; Action/editor parity and performance evidence remain. | | Sensitive-data flow evidence | in progress | The built-in local `fixmap-sensitive-data` evidence provider emits bounded credential/token/PII/payment source indicators, logging/network/storage/analytics sink indicators, and same-file or direct-import structural relationships. Every file item is low confidence, carries exact content fingerprint, detector version and rule IDs, omits matched values/snippets, and declares that it is not a taint or complete security proof. Plan/Verify surfacing, language-aware flow refinement, adversarial evaluation, and SARIF remain. | | Supply-chain evidence | in progress | Core validates a bounded version-1 normalized bundle of packages plus vulnerability, outdated-version, and license-policy findings; preserves external tool, tool/database version, timestamp, document SHA-256, confidence, advisory/fix/license provenance; and converts it to package-aware evidence relationships. The `fixmap supply-chain` CLI and `fixmap_supply_chain` MCP tool accept a versioned object/file, produce deterministic Markdown/JSON, reject traversal/unsafe URLs/input-output collisions, and explicitly state external-evidence-only, no FixMap vulnerability corpus/scanner execution/remediation authorization. CycloneDX/SPDX/OSV/Trivy adapters, signature/attestation verification, policy gates, Action/editor parity, and held-out evidence remain. | @@ -305,9 +305,9 @@ with one existing skip; the rebuilt Action artifact passes its freshness check. | Multi-agent conflict detection | in progress | Core compares up to 100 versioned change intents across explicit intended-edit, impact, and contract graph-identity zones; emits edit/edit errors, directional edit/impact and contract warnings, stale-baseline evidence, stable IDs, and deterministic ordering. Matching labels never imply identity; only reviewed alias/equivalence graph edges canonicalize zones, and unrelated work is not locked. CLI/MCP coordination transport, live intent lifecycle, symbol-range refinement, and held-out concurrency evidence remain. | | Migration planner | in progress | Core validates up to 500 explicit steps against one exact identity-graph fingerprint, topologically builds deterministic phases, and includes prerequisites, required compatibility strategy/exit criteria, verification commands/reasons, rollback triggers/actions, and edit/impact/contract blast radius. The `fixmap migrate` CLI and `fixmap_migrate` MCP tool accept a versioned local object/file, render deterministic Markdown/JSON, reject input/output collisions, never execute, and fail closed on cycles, missing identities, incomplete safety fields, and undeclared parallel edit/contract overlap. Report-to-step derivation, runtime gates, Action/editor parity, and held-out migrations remain. | | Alternative-plan comparison | in progress | Core validates 2-20 alternatives on the same exact graph fingerprint and compares intended edits, impact/contract/unique blast radius, compatible/breaking/unknown contracts, policy errors/warnings, planned tests and edit coverage, reversibility evidence, and high/medium uncertainty. It retains axis evidence and a Pareto-style non-dominated frontier without inventing a winner or scalar score. Report adapters, Markdown/CLI/MCP rendering, cost/time evidence, and held-out decision-quality evaluation remain. | -| Outcome feedback loop | in progress | Core owns versioned, validated, removable outcome records that keep predicted paths, actual edits, command pass/fail/timeout/crash/unavailable evidence, and human/agent/external/unassessed task assessment separate. Calibration exposes correct predictions, false positives, misses, micro precision/recall, test and assessment counts, per-record evidence, and `automaticWeightChanges: false`. Atomic local persistence, CLI capture/removal, privacy/retention controls, longitudinal cohorts, and reviewed weight experiments remain. | -| Change dossier | in progress | Core builds and validates a deterministic version-1 dossier linking request provenance, evidence-status assumptions, exact plan/graph references, ADR references, nullable diff state, command outcomes, observation/inference runtime evidence, reviews, and optional commit/PR/deployment/version identifiers. Confirmed/rejected assumptions and completed tests require evidence fingerprints; timestamps/paths are normalized; content mismatch fails fingerprint validation. Atomic local persistence, CLI lifecycle commands, external signatures/attestations, redaction, and cross-interface rendering remain. | -| Ownership and review routing | in progress | Core combines the highest-precedence CODEOWNERS file with last-rule-wins matching, active annotation owners, architecture-policy reviewers, and up to 250 bounded non-merge commits with recorded author names. Suggestions retain exact source/commit fingerprints, paths and CODEOWNERS lines, confidence, diagnostics, and `availabilityInferred: false`; matching names are not treated as identity or employment evidence. CLI/MCP/Action surfaces, mailmap/team identity integration, blame-at-symbol granularity, privacy controls, and held-out routing quality remain. | +| Outcome feedback loop | in progress | Core owns versioned, validated, removable outcome records that keep predicted paths, actual edits, command pass/fail/timeout/crash/unavailable evidence, and human/agent/external/unassessed task assessment separate. Calibration exposes correct predictions, false positives, misses, micro precision/recall, test and assessment counts, per-record evidence, and `automaticWeightChanges: false`. Atomic local persistence, CLI capture/removal, privacy/retention controls, longitudinal cohorts, and reviewed weight experiments remain. 0.9.5 (PR #688): atomic local persistence under `.fixmap/outcomes/`, CLI record/list/show/remove/calibrate/prune, `--redact`, and read-only MCP `fixmap_outcomes`; longitudinal cohorts and reviewed weight experiments remain. | +| Change dossier | in progress | Core builds and validates a deterministic version-1 dossier linking request provenance, evidence-status assumptions, exact plan/graph references, ADR references, nullable diff state, command outcomes, observation/inference runtime evidence, reviews, and optional commit/PR/deployment/version identifiers. Confirmed/rejected assumptions and completed tests require evidence fingerprints; timestamps/paths are normalized; content mismatch fails fingerprint validation. Atomic local persistence, CLI lifecycle commands, external signatures/attestations, redaction, and cross-interface rendering remain. 0.9.5 (PR #688): atomic local persistence under `.fixmap/dossiers/`, CLI create/list/show/remove, `--redact`, and read-only MCP `fixmap_dossier`; external signatures and cross-interface rendering remain. | +| Ownership and review routing | in progress | Core combines the highest-precedence CODEOWNERS file with last-rule-wins matching, active annotation owners, architecture-policy reviewers, and up to 250 bounded non-merge commits with recorded author names. Suggestions retain exact source/commit fingerprints, paths and CODEOWNERS lines, confidence, diagnostics, and `availabilityInferred: false`; matching names are not treated as identity or employment evidence. CLI/MCP/Action surfaces, mailmap/team identity integration, blame-at-symbol granularity, privacy controls, and held-out routing quality remain. 0.9.5 (PR #689): CLI `fixmap reviewers`, MCP `fixmap_reviewers`, `.mailmap` canonicalization, `--no-history-authors`, and mention-free output; Action parity, blame-at-symbol granularity, and held-out routing quality remain. | ## Runtime proof diff --git a/package-lock.json b/package-lock.json index e4ac61c5..d6d3c2bd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "fixmap-workspace", - "version": "0.9.4", + "version": "0.9.5", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "fixmap-workspace", - "version": "0.9.4", + "version": "0.9.5", "license": "MIT", "workspaces": [ "packages/*", @@ -30,7 +30,7 @@ "name": "@fixmap/web", "version": "0.0.0", "dependencies": { - "@aryam/fixmap-core": "0.9.4", + "@aryam/fixmap-core": "0.9.5", "@phosphor-icons/react": "^2.1.10", "next": "16.4.6", "react": "19.2.7", @@ -8944,18 +8944,18 @@ }, "packages/action": { "name": "@fixmap/action", - "version": "0.9.4", + "version": "0.9.5", "license": "MIT", "dependencies": { - "@aryam/fixmap-core": "0.9.4" + "@aryam/fixmap-core": "0.9.5" } }, "packages/cli": { "name": "@aryam/fixmap", - "version": "0.9.4", + "version": "0.9.5", "license": "MIT", "dependencies": { - "@aryam/fixmap-core": "0.9.4", + "@aryam/fixmap-core": "0.9.5", "@modelcontextprotocol/sdk": "1.32.0" }, "bin": { @@ -8967,7 +8967,7 @@ }, "packages/core": { "name": "@aryam/fixmap-core", - "version": "0.9.4", + "version": "0.9.5", "license": "MIT", "devDependencies": {}, "engines": { diff --git a/package.json b/package.json index 4e910b55..fba022be 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "fixmap-workspace", - "version": "0.9.4", + "version": "0.9.5", "private": true, "description": "Local-first repo intelligence for coding agents: ranked context, likely impact, test routes, risks, and repository benchmarks.", "license": "MIT", diff --git a/packages/action/dist/index.mjs b/packages/action/dist/index.mjs index 7bfcbbcb..c4d2b3d5 100644 --- a/packages/action/dist/index.mjs +++ b/packages/action/dist/index.mjs @@ -5,11 +5,11 @@ import { randomUUID as randomUUID3 } from "node:crypto"; // packages/action/src/annotations.ts import { realpath as realpath3, stat as stat3 } from "node:fs/promises"; -import { isAbsolute as isAbsolute2, relative as relative2, resolve as resolve5 } from "node:path"; +import { isAbsolute as isAbsolute3, relative as relative3, resolve as resolve5 } from "node:path"; // packages/core/dist/plan.js import { readFile as readFile2 } from "node:fs/promises"; -import { join as join2, resolve as resolve2 } from "node:path"; +import { join as join3, resolve as resolve3 } from "node:path"; // packages/core/dist/exclude.js var COMMENT = /^\s*#/; @@ -1333,11 +1333,11 @@ function resolveComposerSymbol(project, symbol, repoPaths, suffixPaths) { for (const mapping of project.psr4) { if (!symbol.startsWith(mapping.prefix)) continue; - const relative3 = symbol.slice(mapping.prefix.length).replace(/\\/g, "/"); - if (!relative3) + const relative4 = symbol.slice(mapping.prefix.length).replace(/\\/g, "/"); + if (!relative4) continue; for (const root of mapping.roots) { - const candidate = [root, `${relative3}.php`].filter(Boolean).join("/"); + const candidate = [root, `${relative4}.php`].filter(Boolean).join("/"); if (repoPaths.has(candidate)) targets.add(candidate); } @@ -1637,23 +1637,23 @@ function buildRubyProjects(files) { if (/^\s*gem\s*(?:\(|\s)\s*["']rails["']/im.test(manifest.textSample)) railsEvidence.add(manifest.path); for (const file of scoped) { - const relative3 = root ? file.path.slice(root.length + 1) : file.path; - if (relative3.toLowerCase() === ".rspec" || /(?:^|\/)spec\/(?:spec_helper|rails_helper)\.rb$/i.test(relative3) || /_spec\.rb$/i.test(relative3)) { + const relative4 = root ? file.path.slice(root.length + 1) : file.path; + if (relative4.toLowerCase() === ".rspec" || /(?:^|\/)spec\/(?:spec_helper|rails_helper)\.rb$/i.test(relative4) || /_spec\.rb$/i.test(relative4)) { rspecEvidence.add(file.path); } - if (/(?:^|\/)test\/test_helper\.rb$/i.test(relative3) || /_test\.rb$/i.test(relative3) || /^(?:\s*require\s*\(?\s*["']minitest|\s*class\s+[^\n<]+<\s*(?:Minitest::Test|MiniTest::Unit)\b)/m.test(file.textSample)) { + if (/(?:^|\/)test\/test_helper\.rb$/i.test(relative4) || /_test\.rb$/i.test(relative4) || /^(?:\s*require\s*\(?\s*["']minitest|\s*class\s+[^\n<]+<\s*(?:Minitest::Test|MiniTest::Unit)\b)/m.test(file.textSample)) { minitestEvidence.add(file.path); } } const application = scoped.find((file) => { - const relative3 = root ? file.path.slice(root.length + 1) : file.path; - return relative3.toLowerCase() === "config/application.rb" && /\bclass\s+Application\s*<\s*Rails::Application\b/.test(file.textSample); + const relative4 = root ? file.path.slice(root.length + 1) : file.path; + return relative4.toLowerCase() === "config/application.rb" && /\bclass\s+Application\s*<\s*Rails::Application\b/.test(file.textSample); }); if (application) railsEvidence.add(application.path); const autoloadFiles = railsEvidence.size === 2 ? scoped.filter((file) => { - const relative3 = root ? file.path.slice(root.length + 1) : file.path; - return /^app\/(?!assets(?:\/|$)|javascript(?:\/|$)|views(?:\/|$))[^/]+\/.+\.rb$/i.test(relative3); + const relative4 = root ? file.path.slice(root.length + 1) : file.path; + return /^app\/(?!assets(?:\/|$)|javascript(?:\/|$)|views(?:\/|$))[^/]+\/.+\.rb$/i.test(relative4); }).map((file) => file.path).sort((left, right) => left.localeCompare(right)) : []; const rakefile = scoped.find((file) => file.path.split("/").pop()?.toLowerCase() === "rakefile"); const rakeTestPath = rakefile && /\b(?:Rake::TestTask|task\s*(?:\(|\s)\s*:test\b)/.test(rakefile.textSample) ? rakefile.path : void 0; @@ -1701,9 +1701,9 @@ function rubyTestCommandForProject(project, relatedTests = []) { const testPath = relatedMinitest[0] ?? project.minitestEvidence.find((path) => /_test\.rb$/i.test(path)); if (!testPath) return void 0; - const relative3 = project.root ? testPath.slice(project.root.length + 1) : testPath; + const relative4 = project.root ? testPath.slice(project.root.length + 1) : testPath; return { - command: scopedBundleCommand(project.root, `ruby -Itest ${relative3}`), + command: scopedBundleCommand(project.root, `ruby -Itest ${relative4}`), reason: `${testPath} provides executable Minitest evidence for ${project.path}`, scopeDir: project.root }; @@ -4732,6 +4732,7 @@ function parseDecisionRecord(input) { const heading = documentHeadings(body).find((entry2) => entry2.level === 1); const titleDate = heading ? /^\s*Date:[ \t]*(\d{4}-\d{2}-\d{2})[ \t]*(?:\r?\n|$)/i.exec(body.slice(heading.end))?.[1] : void 0; const date = normalizeDate(frontmatter.date ?? section(sections, ["date"]) ?? titleDate); + const dependencyRules = parseDependencyRules(frontmatter["fixmap-deny-imports"]); const sourceUrl = frontmatter["fixmap-source-pr"]; if (sourceUrl !== void 0 && !isDecisionPullRequestUrl(sourceUrl)) throw new Error("Invalid decision pull-request source."); @@ -4748,6 +4749,7 @@ function parseDecisionRecord(input) { ...consequences ? { consequences: normalizeProse(consequences, 8e3) } : {}, targets, supersedes: parseReferences(supersedesText), + ...dependencyRules.length > 0 ? { dependencyRules } : {}, sourceFingerprint: input.fingerprint, ...sourceUrl ? { source: { kind: "pull-request", url: sourceUrl, verification: "unverified-local-attribution" } } : {} } @@ -4868,6 +4870,28 @@ function targetKey(target) { return `symbol:${target.path ?? ""}:${target.name}`; return `${target.kind}:${target.name}`; } +var MAX_DEPENDENCY_RULES = 100; +function parseDependencyRules(text) { + if (text === void 0 || !text.trim()) + return []; + const rules = text.split("\n").map((line) => line.trim()).filter(Boolean).map((line) => { + const match = /^(.+?)\s*->\s*(.+)$/.exec(unquote(line.replace(/^`|`$/g, ""))); + if (!match) + throw new Error(`Invalid fixmap-deny-imports rule: ${line}`); + return { from: dependencyPattern(match[1]), deny: dependencyPattern(match[2]) }; + }); + if (rules.length > MAX_DEPENDENCY_RULES) + throw new Error(`fixmap-deny-imports exceeds the ${MAX_DEPENDENCY_RULES}-rule bound.`); + const unique = new Map(rules.map((rule) => [`${rule.from}\0${rule.deny}`, rule])); + return [...unique.values()].sort((a, b) => a.from.localeCompare(b.from) || a.deny.localeCompare(b.deny)); +} +function dependencyPattern(value) { + const pattern = value.trim().replace(/^`|`$/g, "").replace(/\\/g, "/"); + if (!pattern || pattern.length > 500 || pattern.startsWith("!") || pattern.includes("\0") || pattern.includes("->") || /^(?:\/|[A-Za-z]:)/.test(pattern) || pattern.split("/").includes("..")) { + throw new Error(`Invalid fixmap-deny-imports pattern: ${value}`); + } + return pattern; +} function parseReferences(text) { return [...new Set(text.split(/[\n,]/).map((value) => value.replace(/^\s*[-*]\s+/, "").trim()).filter(Boolean))].sort(); } @@ -6990,6 +7014,233 @@ function normalizePath3(path) { return path.split(sep).join("/"); } +// packages/core/dist/architecture-history.js +import { execFile as execFile2, spawn } from "node:child_process"; +import { dirname as dirname2, extname as extname2, isAbsolute as isAbsolute2, join as join2, relative as relative2, resolve as resolve2, sep as sep2 } from "node:path"; +import { promisify as promisify2 } from "node:util"; +var exec2 = promisify2(execFile2); +var MAX_REF_LENGTH = 500; +var MAX_TREE_BYTES = 32 * 1024 * 1024; +var MAX_FILES = 25e3; +var MAX_TEXT_SAMPLE_BYTES2 = 64e3; +var MAX_BATCH_BYTES = 64 * 1024 * 1024; +var MAX_BATCH_OUTPUT_BYTES = MAX_BATCH_BYTES + 2 * 1024 * 1024; +var ARCHITECTURE_CACHE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3; +async function scanRepoAtRef(input) { + const repoRoot = resolve2(input.repoRoot); + const requestedRef = validateRef(input.ref); + return scanCommit(repoRoot, requestedRef, await resolveCommit(repoRoot, requestedRef)); +} +async function scanCommit(repoRoot, requestedRef, commit) { + const { stdout } = await exec2("git", ["ls-tree", "-r", "-z", "-l", "--full-tree", commit, "--"], { + cwd: repoRoot, + encoding: "utf8", + maxBuffer: MAX_TREE_BYTES + }); + const allEntries = parseTree(stdout).filter((entry2) => entry2.mode !== "120000"); + const entries = allEntries.slice(0, MAX_FILES); + const diagnostics = []; + if (allEntries.length > entries.length) + diagnostics.push({ + code: "scan-limit-reached", + severity: "warning", + message: `Historical scan stopped after ${MAX_FILES.toLocaleString()} files at ${commit}.` + }); + const readable = []; + let scheduledBytes = 0; + for (const entry2 of entries) { + if (!isSourcePath(entry2.path) && entry2.path !== ".fixmapignore" || entry2.size > MAX_TEXT_SAMPLE_BYTES2) + continue; + if (scheduledBytes + entry2.size > MAX_BATCH_BYTES) + continue; + readable.push(entry2); + scheduledBytes += entry2.size; + } + const content = await readBlobs(repoRoot, readable); + const files = entries.map((entry2) => buildRepoFile(entry2, content.get(entry2.oid))); + const ignoreEntry = entries.find((entry2) => entry2.path === ".fixmapignore"); + const ignoreBytes = ignoreEntry ? content.get(ignoreEntry.oid) : void 0; + return { + requestedRef, + commit, + repo: { + root: repoRoot, + files, + trackedFiles: entries.map((entry2) => entry2.path), + packageScripts: historicalPackageScripts(files, diagnostics), + changedFiles: [], + diffText: "", + packageManager: inferPackageManager(entries), + diagnostics + }, + ...ignoreBytes ? { ignoreFile: ignoreBytes.toString("utf8") } : {} + }; +} +function isRecord6(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function historicalPackageScripts(files, diagnostics) { + return files.filter((file) => file.path === "package.json" || file.path.endsWith("/package.json")).flatMap((manifest) => { + if (manifest.textSampleComplete !== true) + return []; + try { + const parsed2 = JSON.parse(manifest.textSample.replace(/^/, "")); + const packageDir = manifest.path.includes("/") ? manifest.path.slice(0, manifest.path.lastIndexOf("/")) : ""; + const packageName = typeof parsed2.name === "string" && parsed2.name.trim() ? parsed2.name.trim() : void 0; + const scripts = isRecord6(parsed2.scripts) ? parsed2.scripts : {}; + return Object.entries(scripts).flatMap(([name, command]) => typeof command === "string" ? [{ name, command, packageDir, ...packageName ? { packageName } : {} }] : []); + } catch { + diagnostics.push({ + code: "package-json-invalid", + severity: "warning", + message: `Could not parse ${manifest.path} at this commit; scripts from that package were skipped.` + }); + return []; + } + }); +} +function validateRef(value) { + const ref = value.trim(); + if (!ref || ref.length > MAX_REF_LENGTH || /[\0\r\n]/.test(ref)) + throw new Error("Git ref must be a bounded single-line value."); + return ref; +} +async function resolveCommit(repoRoot, ref) { + try { + const { stdout } = await exec2("git", ["rev-parse", "--verify", "--end-of-options", `${ref}^{commit}`], { + cwd: repoRoot, + encoding: "utf8", + maxBuffer: 1024 * 1024 + }); + const commit = stdout.trim(); + if (!/^[a-f0-9]{40,64}$/i.test(commit)) + throw new Error("Git returned an invalid commit identity."); + return commit.toLowerCase(); + } catch (error) { + throw new Error(`Could not resolve Git ref ${JSON.stringify(ref)}: ${error instanceof Error ? error.message : String(error)}`); + } +} +function parseTree(value) { + return value.split("\0").flatMap((record3) => { + if (!record3) + return []; + const tab = record3.indexOf(" "); + const header = tab === -1 ? "" : record3.slice(0, tab); + const path = tab === -1 ? "" : record3.slice(tab + 1).replace(/\\/g, "/"); + const match = /^(\d+) blob ([a-f0-9]{40,64})\s+(\d+)$/.exec(header); + if (!match || !safePath(path)) + return []; + return [{ mode: match[1], oid: match[2].toLowerCase(), size: Number(match[3]), path }]; + }); +} +async function readBlobs(repoRoot, entries) { + if (entries.length === 0) + return /* @__PURE__ */ new Map(); + const uniqueOids = [...new Set(entries.map((entry2) => entry2.oid))]; + const child = spawn("git", ["cat-file", "--batch"], { cwd: repoRoot, stdio: ["pipe", "pipe", "pipe"], windowsHide: true }); + const stdout = []; + const stderr = []; + let outputBytes = 0; + child.stdout.on("data", (chunk) => { + outputBytes += chunk.length; + if (outputBytes > MAX_BATCH_OUTPUT_BYTES) + child.kill(); + else + stdout.push(chunk); + }); + child.stderr.on("data", (chunk) => stderr.push(chunk)); + child.stdin.end(`${uniqueOids.join("\n")} +`); + const exitCode = await new Promise((resolveExit, reject) => { + child.once("error", reject); + child.once("close", resolveExit); + }); + if (exitCode !== 0 || outputBytes > MAX_BATCH_OUTPUT_BYTES) { + throw new Error(`git cat-file failed while reading historical sources: ${Buffer.concat(stderr).toString("utf8").trim() || `exit ${exitCode}`}`); + } + return parseBatch(Buffer.concat(stdout), uniqueOids); +} +function parseBatch(output, oids) { + const result = /* @__PURE__ */ new Map(); + let offset = 0; + for (const expected of oids) { + const newline = output.indexOf(10, offset); + if (newline === -1) + throw new Error("git cat-file returned a truncated header."); + const header = output.subarray(offset, newline).toString("ascii"); + const match = /^([a-f0-9]{40,64}) blob (\d+)$/.exec(header); + if (!match || match[1].toLowerCase() !== expected) + throw new Error("git cat-file returned an unexpected object."); + const size = Number(match[2]); + const start = newline + 1; + const end = start + size; + if (!Number.isSafeInteger(size) || end >= output.length || output[end] !== 10) { + throw new Error("git cat-file returned a truncated object."); + } + result.set(expected, output.subarray(start, end)); + offset = end + 1; + } + if (offset !== output.length) + throw new Error("git cat-file returned trailing output."); + return result; +} +function buildRepoFile(entry2, bytes) { + const extension = extname2(entry2.path).toLowerCase(); + const isSource = isSourcePath(entry2.path); + let textSample = ""; + let textSampleComplete; + let textSampleSkipReason; + if (isSource) { + if (!bytes) { + textSampleComplete = false; + textSampleSkipReason = "too-large"; + } else { + try { + textSample = new TextDecoder("utf-8", { fatal: true }).decode(bytes); + textSampleComplete = true; + } catch { + textSampleComplete = false; + textSampleSkipReason = "not-text"; + } + } + } + return { + path: entry2.path, + contentFingerprint: `git:${entry2.oid}`, + extension, + sizeBytes: entry2.size, + isTest: isLanguageTestPath(entry2.path, extension) || /(?:^|\/)(?:__tests__|tests?|spec)(?:\/|$)/i.test(entry2.path), + isSource, + kind: classify(entry2.path, extension), + textSample, + ...textSampleComplete !== void 0 ? { textSampleComplete } : {}, + ...textSampleSkipReason ? { textSampleSkipReason } : {} + }; +} +function isSourcePath(path) { + return SOURCE_FILE_EXTENSIONS.has(extname2(path).toLowerCase()) || /(?:^|\/)(?:dockerfile|makefile|pom\.xml|pyproject\.toml)$/i.test(path); +} +function classify(path, extension) { + if (/\.(?:md|mdx)$/i.test(extension) || /(?:^|\/)docs?\//i.test(path)) + return "documentation"; + if (/\.(?:json|ya?ml|toml)$/i.test(extension) || /(?:^|\/)(?:dockerfile|makefile|pom\.xml)$/i.test(path)) + return "config"; + return isSourcePath(path) ? "code" : "other"; +} +function inferPackageManager(entries) { + const names = new Set(entries.map((entry2) => entry2.path.split("/").at(-1)?.toLowerCase())); + if (names.has("pnpm-lock.yaml")) + return "pnpm"; + if (names.has("yarn.lock")) + return "yarn"; + if (names.has("bun.lock") || names.has("bun.lockb")) + return "bun"; + return "npm"; +} +function safePath(path) { + return Boolean(path) && !path.includes("\0") && !path.includes("\uFFFD") && !/^[\/]/.test(path) && path.split("/").every((part) => part && part !== "." && part !== ".."); +} + // packages/core/dist/custom-language-context.js var KINDS = /* @__PURE__ */ new Set(["function", "method", "class", "interface", "type", "variable"]); var record = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value); @@ -7201,7 +7452,7 @@ async function collectEvidence(providers, context, options = {}) { }; } function validateProviderResult(result) { - if (!isRecord6(result) || !Array.isArray(result.items) || !(result.relationships === void 0 || Array.isArray(result.relationships))) { + if (!isRecord7(result) || !Array.isArray(result.items) || !(result.relationships === void 0 || Array.isArray(result.relationships))) { return { success: false, message: "expected { items, relationships? } arrays" }; } const items = result.items; @@ -7233,7 +7484,7 @@ function validateProviderResult(result) { }; } function validateEvidenceItem(candidate) { - if (!isRecord6(candidate) || typeof candidate.id !== "string" || !LOCAL_ID.test(candidate.id)) + if (!isRecord7(candidate) || typeof candidate.id !== "string" || !LOCAL_ID.test(candidate.id)) return "an item has an invalid ID"; if (!isEvidenceKind(candidate.kind)) return `item ${candidate.id} has an invalid kind`; @@ -7250,7 +7501,7 @@ function validateEvidenceItem(candidate) { return void 0; } function validateRelationship(candidate, itemIds) { - if (!isRecord6(candidate) || typeof candidate.id !== "string" || !LOCAL_ID.test(candidate.id)) + if (!isRecord7(candidate) || typeof candidate.id !== "string" || !LOCAL_ID.test(candidate.id)) return "a relationship has an invalid ID"; if (typeof candidate.from !== "string" || !itemIds.has(candidate.from) || typeof candidate.to !== "string" || !itemIds.has(candidate.to)) return `relationship ${candidate.id} references an unknown item`; @@ -7263,7 +7514,7 @@ function validateRelationship(candidate, itemIds) { return void 0; } function isEvidenceSubject(candidate) { - if (!isRecord6(candidate)) + if (!isRecord7(candidate)) return false; if (candidate.kind === "repository") return typeof candidate.repository === "string" && candidate.repository.trim().length > 0; @@ -7283,7 +7534,7 @@ function isSafeRelativePath(path) { return path.replace(/\\/g, "/").split("/").every((segment) => segment.length > 0 && segment !== "." && segment !== ".."); } function isScalarMetadata(candidate) { - if (!isRecord6(candidate) || Object.keys(candidate).length > 50) + if (!isRecord7(candidate) || Object.keys(candidate).length > 50) return false; return Object.entries(candidate).every(([key, value]) => key.length > 0 && key.length <= 100 && (typeof value === "string" && value.length <= 1e3 || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value))); } @@ -7321,7 +7572,7 @@ function withTimeout(promise, timeoutMs, controller) { }); }); } -function isRecord6(candidate) { +function isRecord7(candidate) { return typeof candidate === "object" && candidate !== null && !Array.isArray(candidate); } @@ -7355,7 +7606,8 @@ async function buildFixMapReport(input) { return (await buildFixMapAnalysis(input)).report; } async function buildFixMapAnalysis(input) { - const scannedRepo = await scanRepo({ ...input, includeHistory: input.includeHistory !== false }); + const historical = input.atRef === void 0 ? void 0 : await scanHistoricalRepo(input.repoRoot, input.atRef, input); + const scannedRepo = historical?.repo ?? await scanRepo({ ...input, includeHistory: input.includeHistory !== false }); const generatedArtifacts = scannedRepo.files.filter(isFixMapArtifact); const generatedPaths = new Set(generatedArtifacts.map((file) => file.path)); const repo = generatedArtifacts.length === 0 ? scannedRepo : { @@ -7364,7 +7616,7 @@ async function buildFixMapAnalysis(input) { changedFiles: scannedRepo.changedFiles.filter((path) => !generatedPaths.has(path)), ...scannedRepo.trackedFiles ? { trackedFiles: scannedRepo.trackedFiles.filter((path) => !generatedPaths.has(path)) } : {} }; - const requestedExclude = await resolveExclusions(input.repoRoot, input.exclude ?? []); + const requestedExclude = historical ? excluderFor(input.repoRoot, [...parseIgnoreFile(historical.ignoreFile ?? ""), ...input.exclude ?? []]) : await resolveExclusions(input.repoRoot, input.exclude ?? []); const internalExclude = buildPathExcluder((input.internalExclude ?? []).map((pattern) => normalizeAbsolutePattern(input.repoRoot, pattern))); const exclude = combineExclusions(requestedExclude, internalExclude); const languageContext = input.languageRegistry ? createCustomLanguageContext(input.languageRegistry) : void 0; @@ -7442,14 +7694,29 @@ function combineExclusions(primary, internal) { }; } async function resolveExclusions(repoRoot, patterns2) { - const combined = [...await readIgnoreFile(repoRoot), ...patterns2].map((pattern) => normalizeAbsolutePattern(repoRoot, pattern)); + return excluderFor(repoRoot, [...await readIgnoreFile(repoRoot), ...patterns2]); +} +function excluderFor(repoRoot, patterns2) { + const combined = patterns2.map((pattern) => normalizeAbsolutePattern(repoRoot, pattern)); return combined.length > 0 ? buildPathExcluder(combined) : NO_EXCLUSIONS; } +async function scanHistoricalRepo(repoRoot, ref, input) { + if (input.diffSpec !== void 0 || input.baseRef !== void 0 || input.headRef !== void 0 || input.workingTree || input.includeUntracked) { + throw new Error("A historical plan ranks one committed state, so it cannot be combined with a diff or the working tree."); + } + const historical = await scanRepoAtRef({ repoRoot, ref }); + historical.repo.diagnostics.unshift({ + code: "historical-plan", + severity: "info", + message: `Preview: ranked against ${markdownCode(historical.requestedRef)} at commit ${markdownCode(historical.commit)}, read from committed Git objects without checking out or changing the worktree. Co-change history and uncommitted files were not used.` + }); + return historical; +} function normalizeAbsolutePattern(repoRoot, pattern) { const trimmed = pattern.trim(); const negated = trimmed.startsWith("!"); const body = (negated ? trimmed.slice(1) : trimmed).replace(/\\/g, "/"); - const normalizedRoot = resolve2(repoRoot).replace(/\\/g, "/").replace(/\/$/, ""); + const normalizedRoot = resolve3(repoRoot).replace(/\\/g, "/").replace(/\/$/, ""); const caseInsensitive = /^[A-Za-z]:\//.test(normalizedRoot); const comparableBody = caseInsensitive ? body.toLowerCase() : body; const comparableRoot = caseInsensitive ? normalizedRoot.toLowerCase() : normalizedRoot; @@ -7459,7 +7726,7 @@ function normalizeAbsolutePattern(repoRoot, pattern) { } async function readIgnoreFile(repoRoot) { try { - return parseIgnoreFile(await readFile2(join2(repoRoot, ".fixmapignore"), "utf8")); + return parseIgnoreFile(await readFile2(join3(repoRoot, ".fixmapignore"), "utf8")); } catch { return []; } @@ -7778,7 +8045,7 @@ function renderVerifyMarkdown(result) { // packages/core/dist/annotation-store.js import { mkdir as mkdir2, open as open2, readFile as readFile3, realpath as realpath2, rename as rename2, rm, stat as stat2, lstat } from "node:fs/promises"; -import { resolve as resolve3 } from "node:path"; +import { resolve as resolve4 } from "node:path"; import { randomUUID as randomUUID2 } from "node:crypto"; async function readAnnotationStore(repoRoot) { return readStore(await annotationRoot(repoRoot)); @@ -7799,7 +8066,7 @@ async function annotationRoot(path) { } async function readStore(repoRoot) { await assertStoreBoundary(repoRoot); - const path = resolve3(repoRoot, ".fixmap", "annotations.json"); + const path = resolve4(repoRoot, ".fixmap", "annotations.json"); try { return validateAnnotationStore(JSON.parse(await readFile3(path, "utf8"))); } catch (error) { @@ -7811,11 +8078,11 @@ async function readStore(repoRoot) { } } async function writeStore(repoRoot, store) { - const directory = resolve3(repoRoot, ".fixmap"); + const directory = resolve4(repoRoot, ".fixmap"); await mkdir2(directory, { recursive: true }); await assertStoreBoundary(repoRoot); - const target = resolve3(directory, "annotations.json"); - const temporary = resolve3(directory, `.annotations.${process.pid}.${randomUUID2()}.tmp`); + const target = resolve4(directory, "annotations.json"); + const temporary = resolve4(directory, `.annotations.${process.pid}.${randomUUID2()}.tmp`); const handle = await open2(temporary, "wx", 384); try { await handle.writeFile(`${JSON.stringify(validateAnnotationStore(store), null, 2)} @@ -7833,10 +8100,10 @@ async function writeStore(repoRoot, store) { } async function withStoreLock(repoRoot, operation) { await assertStoreBoundary(repoRoot); - const directory = resolve3(repoRoot, ".fixmap"); + const directory = resolve4(repoRoot, ".fixmap"); await mkdir2(directory, { recursive: true }); await assertStoreBoundary(repoRoot); - const lockPath = resolve3(directory, "annotations.lock"); + const lockPath = resolve4(directory, "annotations.lock"); let handle; try { handle = await open2(lockPath, "wx", 384); @@ -7859,7 +8126,7 @@ async function withStoreLock(repoRoot, operation) { } } async function assertStoreBoundary(repoRoot) { - const directory = resolve3(repoRoot, ".fixmap"); + const directory = resolve4(repoRoot, ".fixmap"); const directoryInfo = await lstat(directory).catch((error) => { if (isNodeError(error, "ENOENT")) return void 0; @@ -7871,7 +8138,7 @@ async function assertStoreBoundary(repoRoot) { throw new Error("Annotation store directory must be a real repository-local .fixmap directory, not a link or junction."); } for (const name of ["annotations.json", "annotations.lock"]) { - const info = await lstat(resolve3(directory, name)).catch((error) => { + const info = await lstat(resolve4(directory, name)).catch((error) => { if (isNodeError(error, "ENOENT")) return void 0; throw error; @@ -8060,12 +8327,12 @@ function add(accumulated, reviewer, confidence, path, evidence) { } function normalizePaths(values) { const normalized = values.map((value) => value.replace(/\\/g, "/")); - const invalid = normalized.find((value) => !safePath(value)); + const invalid = normalized.find((value) => !safePath2(value)); if (invalid !== void 0) throw new Error(`Invalid review-routing path: ${String(invalid)}`); return [...new Set(normalized)].sort(); } -function safePath(value) { +function safePath2(value) { return Boolean(value) && value.length <= 1e3 && !value.includes("\0") && !/^(?:[\/]|[A-Za-z]:)/.test(value) && value.split("/").every((part) => part && part !== "." && part !== ".."); } function validOwner(value) { @@ -8082,9 +8349,9 @@ function confidenceOrder(value) { } // packages/core/dist/sandbox.js -import { execFile as execFile2, spawn } from "node:child_process"; -import { promisify as promisify2 } from "node:util"; -var exec2 = promisify2(execFile2); +import { execFile as execFile3, spawn as spawn2 } from "node:child_process"; +import { promisify as promisify3 } from "node:util"; +var exec3 = promisify3(execFile3); var DEFAULT_LIMITS = { timeoutMs: 5 * 6e4, outputBytes: 1e6, @@ -8638,7 +8905,7 @@ function parseContract(source) { throw error; return parseFailed(source, `YAML ${error.message}.`); } - if (isRecord7(document)) { + if (isRecord8(document)) { for (const key of ["openapi", "swagger", "asyncapi"]) { if (typeof document[key] !== "number") continue; @@ -8670,7 +8937,7 @@ function parsedStructured(source, document) { const asyncapi = specVersion(document.asyncapi); if (asyncapi) return parsed(source, "asyncapi", { ...parseAsyncApiJson(document), version: asyncapi }); - if (typeof document.$schema === "string" || isRecord7(document.properties)) { + if (typeof document.$schema === "string" || isRecord8(document.properties)) { return parsed(source, "json-schema", { ...parseJsonSchema(document), ...typeof document.$schema === "string" ? { version: document.$schema } : {} @@ -8741,7 +9008,7 @@ function parseAsyncApiJson(root) { for (const [channel, channelValue] of Object.entries(recordValue(root.channels))) { const channelRecord = recordValue(channelValue); for (const operation of ["publish", "subscribe"]) { - if (!isRecord7(channelRecord[operation])) + if (!isRecord8(channelRecord[operation])) continue; entries.push(entry(`operation:${operation}:${channel}`, "operation", `${operation} ${channel}`)); } @@ -8879,17 +9146,17 @@ function titleFromRoot(root) { return typeof title === "string" && title.trim() ? { name: title.trim() } : {}; } function recordValue(value) { - return isRecord7(value) ? value : {}; + return isRecord8(value) ? value : {}; } function parseJson(content) { try { const parsed2 = JSON.parse(content); - return isRecord7(parsed2) ? parsed2 : void 0; + return isRecord8(parsed2) ? parsed2 : void 0; } catch { return void 0; } } -function isRecord7(value) { +function isRecord8(value) { return typeof value === "object" && value !== null && !Array.isArray(value); } function stableHash3(value) { @@ -9164,7 +9431,7 @@ function validateFixMapReport(candidate, label) { } const versioned = record3.reportVersion === 1; const contextFiles = candidate.contextFiles; - const unsafeContextPath = contextFiles.findIndex((file) => isRecord8(file) && typeof file.path === "string" && file.path.trim().length > 0 && !isRepositoryRelativePath(file.path)); + const unsafeContextPath = contextFiles.findIndex((file) => isRecord9(file) && typeof file.path === "string" && file.path.trim().length > 0 && !isRepositoryRelativePath(file.path)); if (unsafeContextPath !== -1) { const path = contextFiles[unsafeContextPath].path; return { @@ -9173,7 +9440,7 @@ function validateFixMapReport(candidate, label) { }; } const invalid = contextFiles.findIndex((file) => { - if (!isRecord8(file)) + if (!isRecord9(file)) return true; const ranked = file; if (!isRepositoryRelativePath(ranked.path)) @@ -9216,7 +9483,7 @@ function validateFixMapReport(candidate, label) { } const testRoutes = record3.testRoutes; const invalidRoute = testRoutes.findIndex((route) => { - if (!isRecord8(route)) + if (!isRecord9(route)) return true; return typeof route.command !== "string" || !route.command.trim() || !isRepositoryRelativePathArray(route.relatedFiles) || (versioned || route.kind !== void 0) && route.kind !== "test" && route.kind !== "validation" || (versioned || route.reason !== void 0) && typeof route.reason !== "string"; }); @@ -9228,7 +9495,7 @@ function validateFixMapReport(candidate, label) { } const risks = record3.risks; const invalidRisk = risks.findIndex((risk) => { - if (!isRecord8(risk)) + if (!isRecord9(risk)) return true; return typeof risk.area !== "string" || !risk.area.trim() || (versioned || risk.reason !== void 0) && typeof risk.reason !== "string" || (versioned || risk.severity !== void 0) && risk.severity !== "low" && risk.severity !== "medium" && risk.severity !== "high"; }); @@ -9240,14 +9507,14 @@ function validateFixMapReport(candidate, label) { } if (record3.impact !== void 0) { const impact = record3.impact; - const history = isRecord8(impact) ? impact.history : void 0; - if (!isRecord8(impact) || !isRepositoryRelativePathArray(impact.seeds) || !Array.isArray(impact.files) || !isRepositoryRelativePathArray(impact.inspectionOrder) || !isRecord8(history) || typeof history.available !== "boolean" || typeof history.eligibleCommits !== "number" || !Number.isSafeInteger(history.eligibleCommits) || history.eligibleCommits < 0 || typeof history.shallow !== "boolean" || typeof history.truncated !== "boolean") { + const history = isRecord9(impact) ? impact.history : void 0; + if (!isRecord9(impact) || !isRepositoryRelativePathArray(impact.seeds) || !Array.isArray(impact.files) || !isRepositoryRelativePathArray(impact.inspectionOrder) || !isRecord9(history) || typeof history.available !== "boolean" || typeof history.eligibleCommits !== "number" || !Number.isSafeInteger(history.eligibleCommits) || history.eligibleCommits < 0 || typeof history.shallow !== "boolean" || typeof history.truncated !== "boolean") { return { success: false, message: `${label} has an invalid impact graph envelope.` }; } const invalidImpact = impact.files.findIndex((file) => { - if (!isRecord8(file) || !isRepositoryRelativePath(file.path) || typeof file.score !== "number" || !Number.isFinite(file.score) || file.score < 0 || file.confidence !== "high" && file.confidence !== "medium" && file.confidence !== "low" || !Array.isArray(file.evidence)) + if (!isRecord9(file) || !isRepositoryRelativePath(file.path) || typeof file.score !== "number" || !Number.isFinite(file.score) || file.score < 0 || file.confidence !== "high" && file.confidence !== "medium" && file.confidence !== "low" || !Array.isArray(file.evidence)) return true; - return file.evidence.some((evidence) => !isRecord8(evidence) || !["imports", "imported-by", "co-change", "test-route"].includes(String(evidence.kind)) || !isRepositoryRelativePath(evidence.seed) || typeof evidence.reason !== "string" || !evidence.reason.trim() || evidence.occurrences !== void 0 && (!Number.isSafeInteger(evidence.occurrences) || evidence.occurrences < 0) || evidence.seedChanges !== void 0 && (!Number.isSafeInteger(evidence.seedChanges) || evidence.seedChanges < 0)); + return file.evidence.some((evidence) => !isRecord9(evidence) || !["imports", "imported-by", "co-change", "test-route"].includes(String(evidence.kind)) || !isRepositoryRelativePath(evidence.seed) || typeof evidence.reason !== "string" || !evidence.reason.trim() || evidence.occurrences !== void 0 && (!Number.isSafeInteger(evidence.occurrences) || evidence.occurrences < 0) || evidence.seedChanges !== void 0 && (!Number.isSafeInteger(evidence.seedChanges) || evidence.seedChanges < 0)); }); if (invalidImpact !== -1) { return { success: false, message: `${label} has an invalid impact.files entry at index ${invalidImpact}.` }; @@ -9256,7 +9523,7 @@ function validateFixMapReport(candidate, label) { const primaryPaths = new Set(contextFiles.map((file) => file.path)); const seenEdges = /* @__PURE__ */ new Set(); if (!Array.isArray(impact.primaryImports) || impact.primaryImports.some((edge) => { - if (!isRecord8(edge) || !isRepositoryRelativePath(edge.from) || !isRepositoryRelativePath(edge.to) || edge.from === edge.to || !primaryPaths.has(edge.from) || !primaryPaths.has(edge.to)) + if (!isRecord9(edge) || !isRepositoryRelativePath(edge.from) || !isRepositoryRelativePath(edge.to) || edge.from === edge.to || !primaryPaths.has(edge.from) || !primaryPaths.has(edge.to)) return true; const key = JSON.stringify([edge.from, edge.to]); if (seenEdges.has(key)) @@ -9273,24 +9540,24 @@ function validateFixMapReport(candidate, label) { } if (record3.evidence !== void 0) { const evidence = record3.evidence; - const validSubject = (subject) => isRecord8(subject) && typeof subject.kind === "string" && (subject.path === void 0 || isRepositoryRelativePath(subject.path)); - if (!isRecord8(evidence) || evidence.evidenceVersion !== 1 || typeof evidence.collectedAt !== "string" || !Array.isArray(evidence.sources) || !evidence.sources.every((source) => isRecord8(source) && typeof source.provider === "string" && typeof source.version === "string" && (source.documentSha256 === void 0 || typeof source.documentSha256 === "string" && /^[a-f0-9]{64}$/.test(source.documentSha256))) || !Array.isArray(evidence.items) || evidence.items.length > 50 || !evidence.items.every((item) => isRecord8(item) && typeof item.id === "string" && typeof item.summary === "string" && typeof item.kind === "string" && ["high", "medium", "low"].includes(String(item.confidence)) && isRecord8(item.provider) && Array.isArray(item.subjects) && item.subjects.length > 0 && item.subjects.every(validSubject)) || !Number.isSafeInteger(evidence.omittedItems) || evidence.omittedItems < 0 || !Array.isArray(evidence.diagnostics)) { + const validSubject = (subject) => isRecord9(subject) && typeof subject.kind === "string" && (subject.path === void 0 || isRepositoryRelativePath(subject.path)); + if (!isRecord9(evidence) || evidence.evidenceVersion !== 1 || typeof evidence.collectedAt !== "string" || !Array.isArray(evidence.sources) || !evidence.sources.every((source) => isRecord9(source) && typeof source.provider === "string" && typeof source.version === "string" && (source.documentSha256 === void 0 || typeof source.documentSha256 === "string" && /^[a-f0-9]{64}$/.test(source.documentSha256))) || !Array.isArray(evidence.items) || evidence.items.length > 50 || !evidence.items.every((item) => isRecord9(item) && typeof item.id === "string" && typeof item.summary === "string" && typeof item.kind === "string" && ["high", "medium", "low"].includes(String(item.confidence)) && isRecord9(item.provider) && Array.isArray(item.subjects) && item.subjects.length > 0 && item.subjects.every(validSubject)) || !Number.isSafeInteger(evidence.omittedItems) || evidence.omittedItems < 0 || !Array.isArray(evidence.diagnostics)) { return { success: false, message: `${label} has invalid evidence; it needs evidenceVersion 1, sources, at most 50 items with safe repository-relative subjects, omittedItems, and diagnostics.` }; } } if (record3.languageAdapters !== void 0) { const adapters = record3.languageAdapters; - if (!Array.isArray(adapters) || adapters.length > 32 || !adapters.every((adapter) => isRecord8(adapter) && Object.keys(adapter).every((key) => key === "id" || key === "version" || key === "extensions") && typeof adapter.id === "string" && /^custom:[a-z][a-z0-9-]{0,63}$/.test(adapter.id) && typeof adapter.version === "string" && /^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(adapter.version) && Array.isArray(adapter.extensions) && adapter.extensions.length > 0 && adapter.extensions.length <= 32 && adapter.extensions.every((extension) => typeof extension === "string" && /^\.[a-z0-9][a-z0-9_-]{0,15}$/.test(extension)))) { + if (!Array.isArray(adapters) || adapters.length > 32 || !adapters.every((adapter) => isRecord9(adapter) && Object.keys(adapter).every((key) => key === "id" || key === "version" || key === "extensions") && typeof adapter.id === "string" && /^custom:[a-z][a-z0-9-]{0,63}$/.test(adapter.id) && typeof adapter.version === "string" && /^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(adapter.version) && Array.isArray(adapter.extensions) && adapter.extensions.length > 0 && adapter.extensions.length <= 32 && adapter.extensions.every((extension) => typeof extension === "string" && /^\.[a-z0-9][a-z0-9_-]{0,15}$/.test(extension)))) { return { success: false, message: `${label} has invalid languageAdapters; each entry needs a custom: id, a version, and lowercase extensions.` }; } } if (record3.annotations !== void 0) { const annotations = record3.annotations; - if (!isRecord8(annotations) || typeof annotations.asOf !== "string" || !Number.isFinite(Date.parse(annotations.asOf)) || !isRepositoryRelativePath(annotations.sourcePath) || typeof annotations.sourceFingerprint !== "string" || !/^(?:git|worktree):[a-f0-9]{40,64}$/i.test(annotations.sourceFingerprint) || !Array.isArray(annotations.entries)) { + if (!isRecord9(annotations) || typeof annotations.asOf !== "string" || !Number.isFinite(Date.parse(annotations.asOf)) || !isRepositoryRelativePath(annotations.sourcePath) || typeof annotations.sourceFingerprint !== "string" || !/^(?:git|worktree):[a-f0-9]{40,64}$/i.test(annotations.sourceFingerprint) || !Array.isArray(annotations.entries)) { return { success: false, message: `${label} has an invalid annotations envelope.` }; } const invalidAnnotation = annotations.entries.findIndex((assessment) => { - if (!isRecord8(assessment) || !isRecord8(assessment.annotation) || typeof assessment.message !== "string" || !["active", "expired", "missing-target", "renamed-target"].includes(String(assessment.status)) || assessment.suggestedPath !== void 0 && !isRepositoryRelativePath(assessment.suggestedPath)) + if (!isRecord9(assessment) || !isRecord9(assessment.annotation) || typeof assessment.message !== "string" || !["active", "expired", "missing-target", "renamed-target"].includes(String(assessment.status)) || assessment.suggestedPath !== void 0 && !isRepositoryRelativePath(assessment.suggestedPath)) return true; try { validateAnnotationStore({ annotationStoreVersion: 1, annotations: [assessment.annotation] }); @@ -9307,12 +9574,12 @@ function validateFixMapReport(candidate, label) { if (!Array.isArray(record3.decisions)) return { success: false, message: `${label} has invalid decisions; expected an array.` }; const invalidDecision = record3.decisions.findIndex((decision) => { - if (!isRecord8(decision) || typeof decision.id !== "string" || !/^decision:[a-f0-9]{16}$/.test(decision.id) || !isRepositoryRelativePath(decision.path) || typeof decision.title !== "string" || !decision.title.trim() || !["proposed", "accepted", "rejected", "deprecated", "superseded", "unknown"].includes(String(decision.status)) || typeof decision.decision !== "string" || !decision.decision.trim() || typeof decision.sourceFingerprint !== "string" || !/^(?:git|worktree):[a-f0-9]{40,64}$/i.test(decision.sourceFingerprint) || !Array.isArray(decision.targets) || !Array.isArray(decision.supersedes) || !decision.supersedes.every((value) => typeof value === "string" && value.trim()) || decision.date !== void 0 && (typeof decision.date !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(decision.date)) || decision.context !== void 0 && typeof decision.context !== "string" || decision.authoredStatus !== void 0 && (typeof decision.authoredStatus !== "string" || !decision.authoredStatus.trim() || decision.authoredStatus.length > 500 || decision.authoredStatus.includes("\0")) || decision.consequences !== void 0 && typeof decision.consequences !== "string") + if (!isRecord9(decision) || typeof decision.id !== "string" || !/^decision:[a-f0-9]{16}$/.test(decision.id) || !isRepositoryRelativePath(decision.path) || typeof decision.title !== "string" || !decision.title.trim() || !["proposed", "accepted", "rejected", "deprecated", "superseded", "unknown"].includes(String(decision.status)) || typeof decision.decision !== "string" || !decision.decision.trim() || typeof decision.sourceFingerprint !== "string" || !/^(?:git|worktree):[a-f0-9]{40,64}$/i.test(decision.sourceFingerprint) || !Array.isArray(decision.targets) || !Array.isArray(decision.supersedes) || !decision.supersedes.every((value) => typeof value === "string" && value.trim()) || decision.date !== void 0 && (typeof decision.date !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(decision.date)) || decision.context !== void 0 && typeof decision.context !== "string" || decision.authoredStatus !== void 0 && (typeof decision.authoredStatus !== "string" || !decision.authoredStatus.trim() || decision.authoredStatus.length > 500 || decision.authoredStatus.includes("\0")) || decision.consequences !== void 0 && typeof decision.consequences !== "string" || decision.dependencyRules !== void 0 && (!Array.isArray(decision.dependencyRules) || !decision.dependencyRules.every((rule) => isRecord9(rule) && typeof rule.from === "string" && rule.from.trim() && typeof rule.deny === "string" && rule.deny.trim()))) return true; - if (decision.source !== void 0 && (!isRecord8(decision.source) || decision.source.kind !== "pull-request" || decision.source.verification !== "unverified-local-attribution" || !isDecisionPullRequestUrl(decision.source.url))) + if (decision.source !== void 0 && (!isRecord9(decision.source) || decision.source.kind !== "pull-request" || decision.source.verification !== "unverified-local-attribution" || !isDecisionPullRequestUrl(decision.source.url))) return true; return decision.targets.some((target) => { - if (!isRecord8(target) || !["explicit", "literal-mention"].includes(String(target.evidence))) + if (!isRecord9(target) || !["explicit", "literal-mention"].includes(String(target.evidence))) return true; if (target.kind === "file") return !isRepositoryRelativePath(target.path); @@ -9326,13 +9593,13 @@ function validateFixMapReport(candidate, label) { } if (record3.policy !== void 0) { const policy = record3.policy; - if (!isRecord8(policy) || typeof policy.policyFingerprint !== "string" || !/^(?:git|worktree):[a-f0-9]{40,64}$/i.test(policy.policyFingerprint) || !Array.isArray(policy.findings)) { + if (!isRecord9(policy) || typeof policy.policyFingerprint !== "string" || !/^(?:git|worktree):[a-f0-9]{40,64}$/i.test(policy.policyFingerprint) || !Array.isArray(policy.findings)) { return { success: false, message: `${label} has an invalid architecture policy envelope.` }; } const invalidPolicyFinding = policy.findings.findIndex((finding) => { - if (!isRecord8(finding) || !["boundary-violation", "required-test-missing", "review-required", "breaking-contract"].includes(String(finding.code)) || !["info", "warning", "error"].includes(String(finding.severity)) || typeof finding.ruleId !== "string" || !/^[a-z0-9][a-z0-9._-]{0,63}$/.test(finding.ruleId) || typeof finding.message !== "string" || !finding.message.trim() || !isRepositoryRelativePathArray(finding.paths) || !Array.isArray(finding.evidence)) + if (!isRecord9(finding) || !["boundary-violation", "required-test-missing", "review-required", "breaking-contract"].includes(String(finding.code)) || !["info", "warning", "error"].includes(String(finding.severity)) || typeof finding.ruleId !== "string" || !/^[a-z0-9][a-z0-9._-]{0,63}$/.test(finding.ruleId) || typeof finding.message !== "string" || !finding.message.trim() || !isRepositoryRelativePathArray(finding.paths) || !Array.isArray(finding.evidence)) return true; - return finding.evidence.some((evidence) => !isRecord8(evidence) || !["import", "changed-file", "test-pattern", "reviewer", "contract-change", "decision-record"].includes(String(evidence.kind)) || typeof evidence.detail !== "string" || !evidence.detail.trim() || evidence.path !== void 0 && !isRepositoryRelativePath(evidence.path) || evidence.relatedPath !== void 0 && !isRepositoryRelativePath(evidence.relatedPath)); + return finding.evidence.some((evidence) => !isRecord9(evidence) || !["import", "changed-file", "test-pattern", "reviewer", "contract-change", "decision-record"].includes(String(evidence.kind)) || typeof evidence.detail !== "string" || !evidence.detail.trim() || evidence.path !== void 0 && !isRepositoryRelativePath(evidence.path) || evidence.relatedPath !== void 0 && !isRepositoryRelativePath(evidence.relatedPath)); }); if (invalidPolicyFinding !== -1) { return { success: false, message: `${label} has an invalid architecture policy finding at index ${invalidPolicyFinding}.` }; @@ -9340,7 +9607,7 @@ function validateFixMapReport(candidate, label) { } const diagnostics = record3.diagnostics; const invalidDiagnostic = diagnostics.findIndex((diagnostic) => { - if (!isRecord8(diagnostic)) + if (!isRecord9(diagnostic)) return true; return typeof diagnostic.code !== "string" || !diagnostic.code.trim() || typeof diagnostic.message !== "string" || diagnostic.severity !== "info" && diagnostic.severity !== "warning" && diagnostic.severity !== "error" || diagnostic.paths !== void 0 && !isRepositoryRelativePathArray(diagnostic.paths); }); @@ -9352,21 +9619,21 @@ function validateFixMapReport(candidate, label) { } if (record3.analysis !== void 0) { const analysis = record3.analysis; - const grounding = isRecord8(analysis) ? analysis.grounding : void 0; - const specificity = isRecord8(grounding) ? grounding.specificity : void 0; + const grounding = isRecord9(analysis) ? analysis.grounding : void 0; + const specificity = isRecord9(grounding) ? grounding.specificity : void 0; if (specificity !== "anchored" && specificity !== "descriptive" && specificity !== "vague") { return { success: false, message: `${label} has invalid analysis.grounding.specificity; expected anchored, descriptive, or vague.` }; } - if (!isRecord8(analysis) || !isRecord8(grounding) || !Array.isArray(grounding.identifiers) || !isStringArray(grounding.unresolvedIdentifiers) || !isStringArray(grounding.partiallyResolvedIdentifiers) || !isStringArray(grounding.unverifiedIdentifiers) || typeof grounding.scanComplete !== "boolean" || !isRecord8(analysis.ranking) || !isNullableFiniteNumber(analysis.ranking.topScore) || !isNullableFiniteNumber(analysis.ranking.runnerUpScore) || !isNullableFiniteNumber(analysis.ranking.topGap) || typeof analysis.ranking.clustered !== "boolean" || typeof analysis.nextAction !== "string") { + if (!isRecord9(analysis) || !isRecord9(grounding) || !Array.isArray(grounding.identifiers) || !isStringArray(grounding.unresolvedIdentifiers) || !isStringArray(grounding.partiallyResolvedIdentifiers) || !isStringArray(grounding.unverifiedIdentifiers) || typeof grounding.scanComplete !== "boolean" || !isRecord9(analysis.ranking) || !isNullableFiniteNumber(analysis.ranking.topScore) || !isNullableFiniteNumber(analysis.ranking.runnerUpScore) || !isNullableFiniteNumber(analysis.ranking.topGap) || typeof analysis.ranking.clustered !== "boolean" || typeof analysis.nextAction !== "string") { return { success: false, message: `${label} has incomplete or invalid analysis grounding, ranking, or nextAction fields.` }; } - const invalidIdentifier = grounding.identifiers.findIndex((identifier) => !isRecord8(identifier) || typeof identifier.identifier !== "string" || !identifier.identifier.trim() || !isIdentifierStatus(identifier.status) || !isRepositoryRelativePathArray(identifier.matchedFiles)); + const invalidIdentifier = grounding.identifiers.findIndex((identifier) => !isRecord9(identifier) || typeof identifier.identifier !== "string" || !identifier.identifier.trim() || !isIdentifierStatus(identifier.status) || !isRepositoryRelativePathArray(identifier.matchedFiles)); if (invalidIdentifier !== -1) { return { success: false, @@ -9375,15 +9642,15 @@ function validateFixMapReport(candidate, label) { } if (analysis.retrievalRanking !== void 0) { const retrievalRanking = analysis.retrievalRanking; - if (!isRecord8(retrievalRanking) || !isNullableFiniteNumber(retrievalRanking.topFusionScore) || !isNullableFiniteNumber(retrievalRanking.runnerUpFusionScore) || !isNullableFiniteNumber(retrievalRanking.topGap)) { + if (!isRecord9(retrievalRanking) || !isNullableFiniteNumber(retrievalRanking.topFusionScore) || !isNullableFiniteNumber(retrievalRanking.runnerUpFusionScore) || !isNullableFiniteNumber(retrievalRanking.topGap)) { return { success: false, message: `${label} has invalid analysis.retrievalRanking fields.` }; } } } if (record3.retrieval !== void 0) { const retrieval = record3.retrieval; - const weights = isRecord8(retrieval) ? retrieval.weights : void 0; - if (!isRecord8(retrieval) || retrieval.mode !== "structural-lexical" && retrieval.mode !== "structural-lexical-semantic" || !isRecord8(weights) || !isPositiveFiniteNumber(weights.structural) || !isPositiveFiniteNumber(weights.lexical) || !isPositiveFiniteNumber(weights.semantic) || !isPositiveFiniteNumber(weights.reciprocalRankConstant)) { + const weights = isRecord9(retrieval) ? retrieval.weights : void 0; + if (!isRecord9(retrieval) || retrieval.mode !== "structural-lexical" && retrieval.mode !== "structural-lexical-semantic" || !isRecord9(weights) || !isPositiveFiniteNumber(weights.structural) || !isPositiveFiniteNumber(weights.lexical) || !isPositiveFiniteNumber(weights.semantic) || !isPositiveFiniteNumber(weights.reciprocalRankConstant)) { return { success: false, message: `${label} has an invalid retrieval envelope.` }; } if (retrieval.mode === "structural-lexical-semantic" && !isSemanticProvenance(retrieval.semantic)) { @@ -9395,7 +9662,7 @@ function validateFixMapReport(candidate, label) { } return { success: true, report: candidate }; } -function isRecord8(candidate) { +function isRecord9(candidate) { return typeof candidate === "object" && candidate !== null && !Array.isArray(candidate); } function isStringArray(candidate) { @@ -9418,7 +9685,7 @@ function isIdentifierStatus(candidate) { return candidate === "exact-definition" || candidate === "exact-text" || candidate === "partial-definition" || candidate === "not-found" || candidate === "unverified"; } function isRetrievalSignal(candidate) { - if (!isRecord8(candidate)) + if (!isRecord9(candidate)) return false; const ranks = [candidate.structuralRank, candidate.lexicalRank, candidate.semanticRank]; if (ranks.every((rank) => rank === void 0)) @@ -9430,7 +9697,7 @@ function isRetrievalSignal(candidate) { return candidate.semanticSimilarity === void 0 || typeof candidate.semanticSimilarity === "number" && Number.isFinite(candidate.semanticSimilarity) && candidate.semanticSimilarity >= -1 && candidate.semanticSimilarity <= 1; } function isSemanticProvenance(candidate) { - if (!isRecord8(candidate)) + if (!isRecord9(candidate)) return false; return typeof candidate.id === "string" && candidate.id.trim().length > 0 && typeof candidate.version === "string" && candidate.version.trim().length > 0 && typeof candidate.model === "string" && candidate.model.trim().length > 0 && typeof candidate.artifactHash === "string" && /^[a-f0-9]{64}$/.test(candidate.artifactHash) && typeof candidate.runtime === "string" && candidate.runtime.trim().length > 0 && Number.isSafeInteger(candidate.dimensions) && Number(candidate.dimensions) > 0 && (candidate.normalization === "l2" || candidate.normalization === "none") && typeof candidate.local === "boolean" && typeof candidate.cacheKey === "string" && candidate.cacheKey.trim().length > 0 && Number.isSafeInteger(candidate.indexedFiles) && Number(candidate.indexedFiles) >= 0 && Number.isSafeInteger(candidate.truncatedFiles) && Number(candidate.truncatedFiles) >= 0; } @@ -9447,7 +9714,7 @@ var CAPABILITY_ID = /^[a-z0-9][a-z0-9._-]{0,63}$/; var MAX_CAPABILITIES = 256; var MAX_ANCHORS2 = 64; function validateCapabilityStore(candidate) { - if (!isRecord9(candidate) || candidate.capabilityStoreVersion !== 1 || typeof candidate.workspace !== "string" || typeof candidate.repository !== "string" || !Array.isArray(candidate.capabilities)) { + if (!isRecord10(candidate) || candidate.capabilityStoreVersion !== 1 || typeof candidate.workspace !== "string" || typeof candidate.repository !== "string" || !Array.isArray(candidate.capabilities)) { throw new Error("Capability store must be a version-1 object with workspace, repository, and capabilities fields."); } assertOnlyKeys(candidate, ["capabilityStoreVersion", "workspace", "repository", "capabilities"], "capability store"); @@ -9512,7 +9779,7 @@ function buildCapabilityMap(repo, input) { }; } function validateDefinition(candidate, index) { - if (!isRecord9(candidate)) + if (!isRecord10(candidate)) throw new Error(`Capability at index ${index} must be an object.`); assertOnlyKeys(candidate, ["id", "name", "anchors", "traversal"], `capability at index ${index}`); if (typeof candidate.id !== "string" || !CAPABILITY_ID.test(candidate.id)) { @@ -9541,7 +9808,7 @@ function validateDefinition(candidate, index) { }; } function validateAnchor(candidate, capability, index) { - if (!isRecord9(candidate)) + if (!isRecord10(candidate)) throw new Error(`Capability ${capability} anchor at index ${index} must be an object.`); assertOnlyKeys(candidate, ["operation", "path"], `capability ${capability} anchor at index ${index}`); if (candidate.operation !== "touch" && candidate.operation !== "add") { @@ -9553,7 +9820,7 @@ function validateAnchor(candidate, capability, index) { return { operation: candidate.operation, path }; } function validateTraversal(candidate, capability) { - if (!isRecord9(candidate)) + if (!isRecord10(candidate)) throw new Error(`Capability ${capability} traversal must be an object.`); assertOnlyKeys(candidate, ["direction", "maxDepth", "maxNodes"], `capability ${capability} traversal`); const direction = candidate.direction; @@ -9592,208 +9859,10 @@ function assertOnlyKeys(record3, allowed, label) { if (unknown.length > 0) throw new Error(`${label} has unknown field${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}.`); } -function isRecord9(candidate) { +function isRecord10(candidate) { return typeof candidate === "object" && candidate !== null && !Array.isArray(candidate); } -// packages/core/dist/architecture-history.js -import { execFile as execFile3, spawn as spawn2 } from "node:child_process"; -import { extname as extname2, resolve as resolve4 } from "node:path"; -import { promisify as promisify3 } from "node:util"; -var exec3 = promisify3(execFile3); -var MAX_REF_LENGTH = 500; -var MAX_TREE_BYTES = 32 * 1024 * 1024; -var MAX_FILES = 25e3; -var MAX_TEXT_SAMPLE_BYTES2 = 64e3; -var MAX_BATCH_BYTES = 64 * 1024 * 1024; -var MAX_BATCH_OUTPUT_BYTES = MAX_BATCH_BYTES + 2 * 1024 * 1024; -async function scanRepoAtRef(input) { - const repoRoot = resolve4(input.repoRoot); - const requestedRef = validateRef(input.ref); - const commit = await resolveCommit(repoRoot, requestedRef); - const { stdout } = await exec3("git", ["ls-tree", "-r", "-z", "-l", "--full-tree", commit, "--"], { - cwd: repoRoot, - encoding: "utf8", - maxBuffer: MAX_TREE_BYTES - }); - const allEntries = parseTree(stdout).filter((entry2) => entry2.mode !== "120000"); - const entries = allEntries.slice(0, MAX_FILES); - const diagnostics = []; - if (allEntries.length > entries.length) - diagnostics.push({ - code: "scan-limit-reached", - severity: "warning", - message: `Historical scan stopped after ${MAX_FILES.toLocaleString()} files at ${commit}.` - }); - const readable = []; - let scheduledBytes = 0; - for (const entry2 of entries) { - if (!isSourcePath(entry2.path) || entry2.size > MAX_TEXT_SAMPLE_BYTES2) - continue; - if (scheduledBytes + entry2.size > MAX_BATCH_BYTES) - continue; - readable.push(entry2); - scheduledBytes += entry2.size; - } - const content = await readBlobs(repoRoot, readable); - const files = entries.map((entry2) => buildRepoFile(entry2, content.get(entry2.oid))); - return { - requestedRef, - commit, - repo: { - root: repoRoot, - files, - trackedFiles: entries.map((entry2) => entry2.path), - packageScripts: [], - changedFiles: [], - diffText: "", - packageManager: inferPackageManager(entries), - diagnostics - } - }; -} -function validateRef(value) { - const ref = value.trim(); - if (!ref || ref.length > MAX_REF_LENGTH || /[\0\r\n]/.test(ref)) - throw new Error("Git ref must be a bounded single-line value."); - return ref; -} -async function resolveCommit(repoRoot, ref) { - try { - const { stdout } = await exec3("git", ["rev-parse", "--verify", "--end-of-options", `${ref}^{commit}`], { - cwd: repoRoot, - encoding: "utf8", - maxBuffer: 1024 * 1024 - }); - const commit = stdout.trim(); - if (!/^[a-f0-9]{40,64}$/i.test(commit)) - throw new Error("Git returned an invalid commit identity."); - return commit.toLowerCase(); - } catch (error) { - throw new Error(`Could not resolve Git ref ${JSON.stringify(ref)}: ${error instanceof Error ? error.message : String(error)}`); - } -} -function parseTree(value) { - return value.split("\0").flatMap((record3) => { - if (!record3) - return []; - const tab = record3.indexOf(" "); - const header = tab === -1 ? "" : record3.slice(0, tab); - const path = tab === -1 ? "" : record3.slice(tab + 1).replace(/\\/g, "/"); - const match = /^(\d+) blob ([a-f0-9]{40,64})\s+(\d+)$/.exec(header); - if (!match || !safePath2(path)) - return []; - return [{ mode: match[1], oid: match[2].toLowerCase(), size: Number(match[3]), path }]; - }); -} -async function readBlobs(repoRoot, entries) { - if (entries.length === 0) - return /* @__PURE__ */ new Map(); - const uniqueOids = [...new Set(entries.map((entry2) => entry2.oid))]; - const child = spawn2("git", ["cat-file", "--batch"], { cwd: repoRoot, stdio: ["pipe", "pipe", "pipe"], windowsHide: true }); - const stdout = []; - const stderr = []; - let outputBytes = 0; - child.stdout.on("data", (chunk) => { - outputBytes += chunk.length; - if (outputBytes > MAX_BATCH_OUTPUT_BYTES) - child.kill(); - else - stdout.push(chunk); - }); - child.stderr.on("data", (chunk) => stderr.push(chunk)); - child.stdin.end(`${uniqueOids.join("\n")} -`); - const exitCode = await new Promise((resolveExit, reject) => { - child.once("error", reject); - child.once("close", resolveExit); - }); - if (exitCode !== 0 || outputBytes > MAX_BATCH_OUTPUT_BYTES) { - throw new Error(`git cat-file failed while reading historical sources: ${Buffer.concat(stderr).toString("utf8").trim() || `exit ${exitCode}`}`); - } - return parseBatch(Buffer.concat(stdout), uniqueOids); -} -function parseBatch(output, oids) { - const result = /* @__PURE__ */ new Map(); - let offset = 0; - for (const expected of oids) { - const newline = output.indexOf(10, offset); - if (newline === -1) - throw new Error("git cat-file returned a truncated header."); - const header = output.subarray(offset, newline).toString("ascii"); - const match = /^([a-f0-9]{40,64}) blob (\d+)$/.exec(header); - if (!match || match[1].toLowerCase() !== expected) - throw new Error("git cat-file returned an unexpected object."); - const size = Number(match[2]); - const start = newline + 1; - const end = start + size; - if (!Number.isSafeInteger(size) || end >= output.length || output[end] !== 10) { - throw new Error("git cat-file returned a truncated object."); - } - result.set(expected, output.subarray(start, end)); - offset = end + 1; - } - if (offset !== output.length) - throw new Error("git cat-file returned trailing output."); - return result; -} -function buildRepoFile(entry2, bytes) { - const extension = extname2(entry2.path).toLowerCase(); - const isSource = isSourcePath(entry2.path); - let textSample = ""; - let textSampleComplete; - let textSampleSkipReason; - if (isSource) { - if (!bytes) { - textSampleComplete = false; - textSampleSkipReason = "too-large"; - } else { - try { - textSample = new TextDecoder("utf-8", { fatal: true }).decode(bytes); - textSampleComplete = true; - } catch { - textSampleComplete = false; - textSampleSkipReason = "not-text"; - } - } - } - return { - path: entry2.path, - contentFingerprint: `git:${entry2.oid}`, - extension, - sizeBytes: entry2.size, - isTest: isLanguageTestPath(entry2.path, extension) || /(?:^|\/)(?:__tests__|tests?|spec)(?:\/|$)/i.test(entry2.path), - isSource, - kind: classify(entry2.path, extension), - textSample, - ...textSampleComplete !== void 0 ? { textSampleComplete } : {}, - ...textSampleSkipReason ? { textSampleSkipReason } : {} - }; -} -function isSourcePath(path) { - return SOURCE_FILE_EXTENSIONS.has(extname2(path).toLowerCase()) || /(?:^|\/)(?:dockerfile|makefile|pom\.xml|pyproject\.toml)$/i.test(path); -} -function classify(path, extension) { - if (/\.(?:md|mdx)$/i.test(extension) || /(?:^|\/)docs?\//i.test(path)) - return "documentation"; - if (/\.(?:json|ya?ml|toml)$/i.test(extension) || /(?:^|\/)(?:dockerfile|makefile|pom\.xml)$/i.test(path)) - return "config"; - return isSourcePath(path) ? "code" : "other"; -} -function inferPackageManager(entries) { - const names = new Set(entries.map((entry2) => entry2.path.split("/").at(-1)?.toLowerCase())); - if (names.has("pnpm-lock.yaml")) - return "pnpm"; - if (names.has("yarn.lock")) - return "yarn"; - if (names.has("bun.lock") || names.has("bun.lockb")) - return "bun"; - return "npm"; -} -function safePath2(path) { - return Boolean(path) && !path.includes("\0") && !path.includes("\uFFFD") && !/^[\/]/.test(path) && path.split("/").every((part) => part && part !== "." && part !== ".."); -} - // packages/core/dist/capability-history.js async function compareCapabilityRefs(input) { if (!Number.isFinite(Date.parse(input.asOf))) @@ -9958,8 +10027,8 @@ async function runAnnotationAction(input, repoRoot, allowWrite) { if ("path" in annotation.scope && annotation.scope.path) { const root = await realpath3(repoRoot); const target = await realpath3(resolve5(root, annotation.scope.path)); - const inside = relative2(root, target); - if (!inside || isAbsolute2(inside) || inside === ".." || inside.startsWith("../") || inside.startsWith("..\\") || !(await stat3(target)).isFile()) { + const inside = relative3(root, target); + if (!inside || isAbsolute3(inside) || inside === ".." || inside.startsWith("../") || inside.startsWith("..\\") || !(await stat3(target)).isFile()) { throw new Error("Annotation target must be an existing file inside the checkout."); } } diff --git a/packages/action/package.json b/packages/action/package.json index 15851312..e947280b 100644 --- a/packages/action/package.json +++ b/packages/action/package.json @@ -1,6 +1,6 @@ { "name": "@fixmap/action", - "version": "0.9.4", + "version": "0.9.5", "description": "GitHub Action wrapper for FixMap pull request reports.", "private": true, "license": "MIT", @@ -11,6 +11,6 @@ "typecheck": "tsc -p tsconfig.json --noEmit" }, "dependencies": { - "@aryam/fixmap-core": "0.9.4" + "@aryam/fixmap-core": "0.9.5" } } diff --git a/packages/cli/package.json b/packages/cli/package.json index 90089ae1..2905c1a2 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@aryam/fixmap", - "version": "0.9.4", + "version": "0.9.5", "mcpName": "io.github.aryamthecodebreaker/fixmap", "description": "Local-first CLI and MCP server mapping tasks and diffs to ranked context, likely impact, tests, and risks.", "license": "MIT", @@ -46,7 +46,7 @@ "typecheck": "tsc -p tsconfig.json --noEmit" }, "dependencies": { - "@aryam/fixmap-core": "0.9.4", + "@aryam/fixmap-core": "0.9.5", "@modelcontextprotocol/sdk": "1.32.0" }, "engines": { diff --git a/packages/core/package.json b/packages/core/package.json index c89bdacb..0b272f34 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@aryam/fixmap-core", - "version": "0.9.4", + "version": "0.9.5", "description": "Deterministic local-first repository scanner, context ranker, Impact Graph, and report renderer for coding agents.", "license": "MIT", "repository": { diff --git a/server.json b/server.json index f140d6d5..ffa88c0e 100644 --- a/server.json +++ b/server.json @@ -6,12 +6,12 @@ "url": "https://github.com/aryamthecodebreaker/FixMap", "source": "github" }, - "version": "0.9.4", + "version": "0.9.5", "packages": [ { "registryType": "npm", "identifier": "@aryam/fixmap", - "version": "0.9.4", + "version": "0.9.5", "transport": { "type": "stdio" },