diff --git a/packages/action/dist/index.mjs b/packages/action/dist/index.mjs index ea848e6..2600aab 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 e204725..4020b9a 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 66feda9..41cae3b 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 862779d..5466479 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 70326eb..738874c 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 ab8f47f..674fba4 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 7920fb2..45185a9 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 0000000..c95ab7b --- /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 8c444a5..7d4ddac 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 2fa9726..a913cb1 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 d524cae..b4033d6 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 ce047a5..e72aa98 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 afdea7f..c74e859 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 a7cd0cd..0b76e01 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 9195d7d..25e8849 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 3ddbd9a..04597d8 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 5277b26..d2821b8 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 0000000..1ef65d9 --- /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(); + }); +});