diff --git a/packages/action/dist/index.mjs b/packages/action/dist/index.mjs index fc2ef17..d7d9bed 100644 --- a/packages/action/dist/index.mjs +++ b/packages/action/dist/index.mjs @@ -1244,7 +1244,7 @@ function isVagueTaskText(issueText) { return residual.size <= MAX_RESIDUAL_TOKENS_FOR_VAGUE; } function removeIdentifiers(text, identifiers) { - return identifiers.reduce((current, identifier) => current.replace(new RegExp(escapeRegExp(identifier), "g"), " "), text); + return identifiers.reduce((current2, identifier) => current2.replace(new RegExp(escapeRegExp(identifier), "g"), " "), text); } function escapeRegExp(value) { return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); @@ -1309,11 +1309,11 @@ function composerDependencyClosure(projects, projectPath) { const reachable = /* @__PURE__ */ new Set(); const pending = [projectPath]; while (pending.length > 0) { - const current = pending.shift(); - if (reachable.has(current)) + const current2 = pending.shift(); + if (reachable.has(current2)) continue; - reachable.add(current); - for (const dependency of byPath.get(current)?.pathDependencies ?? []) { + reachable.add(current2); + for (const dependency of byPath.get(current2)?.pathDependencies ?? []) { if (!reachable.has(dependency.projectPath)) pending.push(dependency.projectPath); } @@ -1580,11 +1580,11 @@ function dotnetReferenceClosure(projects, projectPath) { const reachable = /* @__PURE__ */ new Set(); const pending = [projectPath]; while (pending.length > 0) { - const current = pending.shift(); - if (reachable.has(current)) + const current2 = pending.shift(); + if (reachable.has(current2)) continue; - reachable.add(current); - for (const reference of byPath.get(current)?.references ?? []) { + reachable.add(current2); + for (const reference of byPath.get(current2)?.references ?? []) { if (!reachable.has(reference)) pending.push(reference); } @@ -2874,11 +2874,11 @@ function dotnetReferenceClosureFromIndex(projectsByPath, projectPath) { const reachable = /* @__PURE__ */ new Set(); const pending = [projectPath]; while (pending.length > 0) { - const current = pending.shift(); - if (reachable.has(current)) + const current2 = pending.shift(); + if (reachable.has(current2)) continue; - reachable.add(current); - for (const reference of projectsByPath.get(current)?.references ?? []) { + reachable.add(current2); + for (const reference of projectsByPath.get(current2)?.references ?? []) { if (!reachable.has(reference)) pending.push(reference); } @@ -3075,6 +3075,11 @@ function fixMapArtifactKind(file) { } if (candidate.capabilityListVersion === 1 && Array.isArray(candidate.capabilities)) return "capability-list-json"; + if (candidate.contractListVersion === 1 && isRecord2(candidate.inventory)) + return "contract-list-json"; + if (candidate.contractDiffVersion === 1 && isRecord2(candidate.from) && isRecord2(candidate.to) && isRecord2(candidate.comparison)) { + return "contract-diff-json"; + } if ((candidate.reportVersion === void 0 || candidate.reportVersion === 1) && typeof candidate.summary === "string" && Array.isArray(candidate.contextFiles) && Array.isArray(candidate.testRoutes) && Array.isArray(candidate.risks) && Array.isArray(candidate.changedFiles) && Array.isArray(candidate.diagnostics)) return "report-json"; if (candidate.contextVersion === 1 && typeof candidate.task === "string" && typeof candidate.budgetTokens === "number" && candidate.tokenEstimate === "utf8-bytes-divided-by-4" && Array.isArray(candidate.snippets) && Array.isArray(candidate.omitted)) @@ -3102,12 +3107,12 @@ function buildImpactMap(repo, requestedSeeds, testRoutes = [], limit = DEFAULT_I const addEvidence = (path, score, evidence) => { if (seedSet.has(path) || !repositoryPaths.has(path) || isGeneratedPath(path) || isBackupPath(path)) return; - const current = candidates.get(path) ?? { path, score: 0, evidence: [] }; - if (!current.evidence.some((entry2) => entry2.kind === evidence.kind && entry2.seed === evidence.seed)) { - current.evidence.push(evidence); - current.score += score; + const current2 = candidates.get(path) ?? { path, score: 0, evidence: [] }; + if (!current2.evidence.some((entry2) => entry2.kind === evidence.kind && entry2.seed === evidence.seed)) { + current2.evidence.push(evidence); + current2.score += score; } - candidates.set(path, current); + candidates.set(path, current2); }; const graph = buildImportGraph(repo.files, languageContext); const primarySet = new Set(primaryPaths.filter((path) => repositoryPaths.has(path))); @@ -6464,10 +6469,10 @@ function reportEscapedLinks(diagnostics, paths) { paths: unique.slice(0, 8) }); } -async function walkFiles(root, current, diagnostics, state, internalCacheRoot, internalPaths, languageRegistry) { +async function walkFiles(root, current2, diagnostics, state, internalCacheRoot, internalPaths, languageRegistry) { let entries; try { - entries = await readdir(current, { withFileTypes: true }); + entries = await readdir(current2, { withFileTypes: true }); } catch { return []; } @@ -6481,14 +6486,14 @@ async function walkFiles(root, current, diagnostics, state, internalCacheRoot, i break; } if (entry2.isSymbolicLink()) { - state.linkedPaths.push(normalizePath3(relative(root, join(current, entry2.name)))); + state.linkedPaths.push(normalizePath3(relative(root, join(current2, entry2.name)))); continue; } if (entry2.isDirectory()) { if (WALK_IGNORED_DIRS.has(entry2.name)) { continue; } - const directory = join(current, entry2.name); + const directory = join(current2, entry2.name); if (internalCacheRoot && sameFilesystemPath(directory, internalCacheRoot)) continue; results.push(...await walkFiles(root, directory, diagnostics, state, internalCacheRoot, internalPaths, languageRegistry)); @@ -6497,7 +6502,7 @@ async function walkFiles(root, current, diagnostics, state, internalCacheRoot, i if (!entry2.isFile()) { continue; } - const absolutePath = join(current, entry2.name); + const absolutePath = join(current2, entry2.name); const relativePath = normalizePath3(relative(root, absolutePath)); if (hasInternalPath(internalPaths, relativePath) || isInternalCachePath(root, relativePath, internalCacheRoot)) continue; @@ -6680,19 +6685,19 @@ function sampleDiffText(diffText, diagnostics) { if (diffText.length <= MAX_DIFF_TEXT_CHARS) return diffText; const groups = []; - let current; + let current2; for (const line of diffText.split(/\r?\n/)) { if (line.startsWith("diff --git ")) { - current = []; - groups.push(current); + current2 = []; + groups.push(current2); continue; } if (line.startsWith("+") && !line.startsWith("+++")) { - if (!current) { - current = []; - groups.push(current); + if (!current2) { + current2 = []; + groups.push(current2); } - current.push(line); + current2.push(line); } } const queues = groups.filter((group) => group.length > 0); @@ -8125,6 +8130,435 @@ function encodePart(value) { return value.split("/").map(encodeURIComponent).join("/"); } +// packages/core/dist/yaml-subset.js +var YamlSubsetError = class extends Error { +}; +var MAX_DEPTH = 64; +function parseYamlSubset(content) { + const lines = toLines(content); + if (lines.length === 0) + return null; + const state = { lines, index: 0 }; + const value = parseNode(state, lines[0].indent, 0); + if (state.index < lines.length) + fail(lines[state.index], "unexpected content after the document"); + return value; +} +function toLines(content) { + const rawLines = content.replace(/^\uFEFF/, "").split(/\r?\n/); + const lines = []; + let started = false; + for (let index = 0; index < rawLines.length; index += 1) { + const raw = rawLines[index]; + if (/^%/.test(raw) && !started) + continue; + if (/^---(?:\s|$)/.test(raw)) { + if (started || lines.length > 0) + throw new YamlSubsetError(`line ${index + 1}: multiple YAML documents are not supported`); + started = true; + if (raw.slice(3).trim() && !raw.slice(3).trim().startsWith("#")) { + throw new YamlSubsetError(`line ${index + 1}: content on the document marker is not supported`); + } + continue; + } + if (/^\.\.\.(?:\s|$)/.test(raw)) { + if (rawLines.slice(index + 1).some((rest) => rest.trim() && !rest.trim().startsWith("#"))) { + throw new YamlSubsetError(`line ${index + 1}: multiple YAML documents are not supported`); + } + break; + } + const leading = /^[ \t]*/.exec(raw)[0]; + const text = stripComment(raw.slice(leading.length)).trimEnd(); + if (!text) { + lines.push({ number: index + 1, indent: -1, text: "", raw }); + continue; + } + if (leading.includes(" ")) + throw new YamlSubsetError(`line ${index + 1}: tab indentation is not supported`); + lines.push({ number: index + 1, indent: leading.length, text, raw }); + } + return lines; +} +function stripComment(text) { + if (text.startsWith("#")) + return ""; + let quote; + for (let index = 0; index < text.length; index += 1) { + const char = text[index]; + if (quote) { + if (quote === '"' && char === "\\") + index += 1; + else if (char === quote) + quote = void 0; + continue; + } + if ((char === '"' || char === "'") && (index === 0 || /[\s:\[\]{},-]/.test(text[index - 1]))) + quote = char; + else if (char === "#" && /\s/.test(text[index - 1] ?? "")) + return text.slice(0, index); + } + return text; +} +function current(state) { + while (state.index < state.lines.length && state.lines[state.index].indent < 0) + state.index += 1; + return state.lines[state.index]; +} +function parseNode(state, indent, depth5) { + if (depth5 > MAX_DEPTH) + throw new YamlSubsetError("YAML nesting is deeper than FixMap reads"); + const line = current(state); + if (!line || line.indent < indent) + return null; + if (isSequenceItem(line.text)) + return parseSequence(state, line.indent, depth5); + if (splitKey(line.text)) + return parseMapping(state, line.indent, depth5); + state.index += 1; + return parseInlineValue(line, line.text, state, line.indent, depth5); +} +function isSequenceItem(text) { + return text === "-" || text.startsWith("- "); +} +function parseSequence(state, indent, depth5) { + const values = []; + for (let line = current(state); line && line.indent === indent && isSequenceItem(line.text); line = current(state)) { + const rest = line.text.slice(1).trimStart(); + if (!rest) { + state.index += 1; + const next = current(state); + values.push(next && next.indent > indent ? parseNode(state, next.indent, depth5 + 1) : null); + continue; + } + const column = indent + (line.text.length - rest.length); + state.lines[state.index] = { ...line, indent: column, text: rest }; + if (isSequenceItem(rest) || splitKey(rest)) + values.push(parseNode(state, column, depth5 + 1)); + else { + state.index += 1; + values.push(parseInlineValue(line, rest, state, indent, depth5)); + } + } + const after = current(state); + if (after && after.indent > indent) + fail(after, "unexpected indentation in a sequence"); + return values; +} +function parseMapping(state, indent, depth5) { + const result = {}; + for (let line = current(state); line && line.indent === indent; line = current(state)) { + const split = splitKey(line.text); + if (!split) + fail(line, "expected a mapping key"); + const key = parseKey(line, split.key); + if (key === "<<") + fail(line, "merge keys are not supported"); + if (Object.prototype.hasOwnProperty.call(result, key)) + fail(line, `duplicate key ${JSON.stringify(key)}`); + state.index += 1; + if (!split.value) { + const next = current(state); + if (next && (next.indent > indent || next.indent === indent && isSequenceItem(next.text))) { + result[key] = parseNode(state, next.indent, depth5 + 1); + } else { + result[key] = null; + } + } else { + result[key] = parseInlineValue(line, split.value, state, indent, depth5); + } + } + const after = current(state); + if (after && after.indent > indent) + fail(after, "unexpected indentation in a mapping"); + return result; +} +function splitKey(text) { + if (isSequenceItem(text) || text.startsWith("{") || text.startsWith("[")) + return void 0; + let index = 0; + if (text.startsWith('"') || text.startsWith("'")) { + const end = closingQuote(text, 0); + if (end === -1) + return void 0; + index = end + 1; + const rest = text.slice(index); + const match = /^\s*:(?:\s|$)/.exec(rest); + if (!match) + return void 0; + return { key: text.slice(0, index), value: rest.slice(match[0].length).trim() }; + } + for (; index < text.length; index += 1) { + if (text[index] === ":" && (index + 1 === text.length || /\s/.test(text[index + 1]))) { + return { key: text.slice(0, index).trimEnd(), value: text.slice(index + 1).trim() }; + } + } + return void 0; +} +function parseKey(line, raw) { + if (raw.startsWith("? ")) + fail(line, "complex mapping keys are not supported"); + if (raw.startsWith('"') || raw.startsWith("'")) + return parseQuoted(line, raw); + if (/^[&*!]/.test(raw)) + fail(line, "anchors, aliases, and tags are not supported"); + return raw; +} +function parseInlineValue(line, value, state, parentIndent, depth5) { + if (/^[&*!]/.test(value)) + fail(line, "anchors, aliases, and tags are not supported"); + if (/^[|>]/.test(value)) + return parseBlockScalar(line, value, state, parentIndent); + if (value.startsWith("{") || value.startsWith("[")) { + let text2 = value; + while (!flowBalanced(text2)) { + const next = current(state); + if (!next || next.indent <= parentIndent) + fail(line, "unterminated flow collection"); + text2 += ` ${next.text}`; + state.index += 1; + } + const parser = { text: text2, index: 0, line }; + const result = parseFlowValue(parser, depth5); + skipSpace(parser); + if (parser.index !== text2.length) + fail(line, "unexpected content after a flow collection"); + return result; + } + if (value.startsWith('"') || value.startsWith("'")) { + let text2 = value; + while (closingQuote(text2, 0) === -1) { + const next = current(state); + if (!next) + fail(line, "unterminated quoted scalar"); + text2 += ` ${next.raw.trim()}`; + state.index += 1; + } + const end = closingQuote(text2, 0); + if (text2.slice(end + 1).trim()) + fail(line, "unexpected content after a quoted scalar"); + return parseQuoted(line, text2); + } + let text = value; + for (let next = current(state); next && next.indent > parentIndent; next = current(state)) { + if (splitKey(next.text) || isSequenceItem(next.text)) + fail(next, "a scalar value cannot also open a nested block"); + text += ` ${next.text}`; + state.index += 1; + } + return resolvePlain(text); +} +function parseBlockScalar(line, header, state, parentIndent) { + const match = /^([|>])([+-]?)(\d?)([+-]?)$/.exec(header.trim()); + if (!match) + fail(line, "unsupported block scalar header"); + const folded = match[1] === ">"; + const chomping = match[2] || match[4]; + const explicit = match[3] ? Number(match[3]) : void 0; + const collected = []; + let contentIndent = explicit !== void 0 ? parentIndent + explicit : void 0; + while (state.index < state.lines.length) { + const next = state.lines[state.index]; + const blank = next.raw.trim() === ""; + const leading = /^ */.exec(next.raw)[0].length; + if (!blank && leading <= parentIndent) + break; + if (!blank) { + contentIndent ??= leading; + if (leading < contentIndent) + fail(next, "block scalar line is less indented than its first line"); + } + collected.push(blank ? "" : next.raw.slice(contentIndent)); + state.index += 1; + } + while (collected.length > 0 && collected.at(-1) === "" && chomping !== "+") + collected.pop(); + let text = folded ? foldLines(collected) : collected.join("\n"); + if (chomping !== "-" && collected.length > 0) + text += "\n"; + return text; +} +function foldLines(lines) { + let result = ""; + for (let index = 0; index < lines.length; index += 1) { + const line = lines[index]; + if (index === 0) { + result = line; + continue; + } + const previous = lines[index - 1]; + if (line === "") + result += "\n"; + else if (previous === "" || /^\s/.test(line) || /^\s/.test(previous)) + result += (previous === "" ? "" : "\n") + line; + else + result += ` ${line}`; + } + return result; +} +function resolvePlain(text) { + const value = text.trim(); + if (value === "" || value === "~" || /^(?:null|Null|NULL)$/.test(value)) + return null; + if (/^(?:true|True|TRUE)$/.test(value)) + return true; + if (/^(?:false|False|FALSE)$/.test(value)) + return false; + if (/^[-+]?(?:0|[1-9][0-9]*)$/.test(value)) { + const numeric = Number(value); + return Number.isSafeInteger(numeric) ? numeric : value; + } + if (/^[-+]?(?:[0-9]+\.[0-9]*|\.[0-9]+)(?:[eE][-+]?[0-9]+)?$/.test(value) || /^[-+]?[0-9]+[eE][-+]?[0-9]+$/.test(value)) + return Number(value); + return value; +} +function closingQuote(text, start) { + const quote = text[start]; + for (let index = start + 1; index < text.length; index += 1) { + if (quote === '"' && text[index] === "\\") { + index += 1; + continue; + } + if (text[index] === quote) { + if (quote === "'" && text[index + 1] === "'") { + index += 1; + continue; + } + return index; + } + } + return -1; +} +function parseQuoted(line, text) { + const end = closingQuote(text, 0); + if (end === -1) + fail(line, "unterminated quoted scalar"); + const body = text.slice(1, end); + if (text[0] === "'") + return body.replace(/''/g, "'"); + return body.replace(/\\(u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|.)/g, (_, escape) => { + if (escape.length > 1) + return String.fromCharCode(parseInt(escape.slice(1), 16)); + const simple = { n: "\n", t: " ", r: "\r", "0": "\0", '"': '"', "\\": "\\", "/": "/", " ": " ", b: "\b", f: "\f" }; + if (!(escape in simple)) + fail(line, `unsupported escape \\${escape}`); + return simple[escape]; + }); +} +function flowBalanced(text) { + let depth5 = 0; + let quote; + for (let index = 0; index < text.length; index += 1) { + const char = text[index]; + if (quote) { + if (quote === '"' && char === "\\") + index += 1; + else if (char === quote) + quote = void 0; + } else if (char === '"' || char === "'") + quote = char; + else if (char === "{" || char === "[") + depth5 += 1; + else if (char === "}" || char === "]") + depth5 -= 1; + } + return depth5 <= 0 && !quote; +} +function skipSpace(parser) { + while (parser.index < parser.text.length && /\s/.test(parser.text[parser.index])) + parser.index += 1; +} +function parseFlowValue(parser, depth5) { + if (depth5 > MAX_DEPTH) + throw new YamlSubsetError("YAML nesting is deeper than FixMap reads"); + skipSpace(parser); + const char = parser.text[parser.index]; + if (char === "{") + return parseFlowMapping(parser, depth5 + 1); + if (char === "[") + return parseFlowSequence(parser, depth5 + 1); + if (char === '"' || char === "'") { + const end = closingQuote(parser.text, parser.index); + if (end === -1) + fail(parser.line, "unterminated quoted scalar"); + const value = parseQuoted(parser.line, parser.text.slice(parser.index, end + 1)); + parser.index = end + 1; + return value; + } + if (char !== void 0 && /[&*!]/.test(char)) + fail(parser.line, "anchors, aliases, and tags are not supported"); + const start = parser.index; + while (parser.index < parser.text.length && !/[,\]}]/.test(parser.text[parser.index]) && !(parser.text[parser.index] === ":" && /[\s,\]}]/.test(parser.text[parser.index + 1] ?? " "))) + parser.index += 1; + return resolvePlain(parser.text.slice(start, parser.index)); +} +function parseFlowSequence(parser, depth5) { + parser.index += 1; + const values = []; + skipSpace(parser); + if (parser.text[parser.index] === "]") { + parser.index += 1; + return values; + } + for (; ; ) { + values.push(parseFlowValue(parser, depth5)); + skipSpace(parser); + const char = parser.text[parser.index]; + parser.index += 1; + if (char === "]") + return values; + if (char !== ",") + fail(parser.line, "expected , or ] in a flow sequence"); + skipSpace(parser); + if (parser.text[parser.index] === "]") { + parser.index += 1; + return values; + } + } +} +function parseFlowMapping(parser, depth5) { + parser.index += 1; + const result = {}; + skipSpace(parser); + if (parser.text[parser.index] === "}") { + parser.index += 1; + return result; + } + for (; ; ) { + const keyValue = parseFlowValue(parser, depth5); + if (keyValue !== null && typeof keyValue === "object") + fail(parser.line, "complex mapping keys are not supported"); + const key = keyValue === null ? "" : String(keyValue); + if (key === "<<") + fail(parser.line, "merge keys are not supported"); + if (Object.prototype.hasOwnProperty.call(result, key)) + fail(parser.line, `duplicate key ${JSON.stringify(key)}`); + skipSpace(parser); + if (parser.text[parser.index] === ":") { + parser.index += 1; + skipSpace(parser); + const next = parser.text[parser.index]; + result[key] = next === "," || next === "}" ? null : parseFlowValue(parser, depth5); + } else { + result[key] = null; + } + skipSpace(parser); + const char = parser.text[parser.index]; + parser.index += 1; + if (char === "}") + return result; + if (char !== ",") + fail(parser.line, "expected , or } in a flow mapping"); + skipSpace(parser); + if (parser.text[parser.index] === "}") { + parser.index += 1; + return result; + } + } +} +function fail(line, message2) { + throw new YamlSubsetError(`line ${line.number}: ${message2}`); +} + // packages/core/dist/contracts.js var HTTP_METHODS = /* @__PURE__ */ new Set(["get", "put", "post", "delete", "options", "head", "patch", "trace"]); var CONTRACT_PATH = /(?:^|\/)(?:openapi|swagger|asyncapi)(?:\.[^/]+)?\.(?:json|ya?ml)$|\.(?:graphql|gql|proto)$|(?:^|\/)migrations?\/.*\.sql$|\.schema\.json$/i; @@ -8132,7 +8566,7 @@ function contractSourcesFromRepo(repo) { const sources = []; const diagnostics = []; for (const file of repo.files.filter((candidate) => isContractCandidate(candidate.path, candidate.textSample))) { - if (file.textSampleComplete === false || !file.contentFingerprint) { + if (file.textSampleComplete === false || !file.contentFingerprint || !file.isSource) { diagnostics.push({ code: "contract-source-incomplete", severity: "warning", @@ -8175,23 +8609,38 @@ function parseContract(source) { } return parsed(source, "graphql", graphql); } - if (lower.endsWith(".proto")) - return parsed(source, "protobuf", parseProtobuf(source.content)); + if (lower.endsWith(".proto")) { + const syntax = /^\s*(?:syntax|edition)\s*=\s*["']([^"']+)["']/m.exec(source.content.replace(/\/\/[^\r\n]*/g, ""))?.[1]; + return parsed(source, "protobuf", { ...parseProtobuf(source.content), ...syntax ? { version: syntax } : {} }); + } if (/(?:^|\/)migrations?\/.*\.sql$/i.test(source.path)) return parsed(source, "migration", parseMigration(source.content)); const json = parseJson(source.content); - if (json) { - if (typeof json.openapi === "string" || typeof json.swagger === "string") - return parsed(source, "openapi", parseOpenApiJson(json)); - if (typeof json.asyncapi === "string") - return parsed(source, "asyncapi", parseAsyncApiJson(json)); - if (typeof json.$schema === "string" || isRecord7(json.properties)) - return parsed(source, "json-schema", parseJsonSchema(json)); - } - if (/^\s*(?:openapi|swagger)\s*:/m.test(source.content)) - return parsed(source, "openapi", parseOpenApiYaml(source.content)); - if (/^\s*asyncapi\s*:/m.test(source.content)) - return parsed(source, "asyncapi", parseAsyncApiYaml(source.content)); + if (json) + return parsedStructured(source, json); + const yamlLike = /\.ya?ml$/i.test(source.path) || /^\s*(?:openapi|swagger|asyncapi)\s*:/m.test(source.content); + if (yamlLike) { + let document; + try { + document = parseYamlSubset(source.content); + } catch (error) { + if (!(error instanceof YamlSubsetError)) + throw error; + return parseFailed(source, `YAML ${error.message}.`); + } + if (isRecord7(document)) { + for (const key of ["openapi", "swagger", "asyncapi"]) { + if (typeof document[key] !== "number") + continue; + const written = new RegExp(`^${key}\\s*:\\s*([^\\s#]+)`, "m").exec(source.content)?.[1]; + if (written) + document[key] = written; + } + const structured = parsedStructured(source, document); + if (structured.surface || structured.diagnostic) + return structured; + } + } if (CONTRACT_PATH.test(source.path)) { return { diagnostic: { @@ -8204,6 +8653,31 @@ function parseContract(source) { } return {}; } +function parsedStructured(source, document) { + const openapi = specVersion(document.openapi) ?? specVersion(document.swagger); + if (openapi) + return parsed(source, "openapi", { ...parseOpenApiJson(document), version: openapi }); + const asyncapi = specVersion(document.asyncapi); + if (asyncapi) + return parsed(source, "asyncapi", { ...parseAsyncApiJson(document), version: asyncapi }); + if (typeof document.$schema === "string" || isRecord7(document.properties)) { + return parsed(source, "json-schema", { + ...parseJsonSchema(document), + ...typeof document.$schema === "string" ? { version: document.$schema } : {} + }); + } + if (CONTRACT_PATH.test(source.path)) { + return parseFailed(source, "the document has no openapi, swagger, asyncapi, $schema, or properties marker."); + } + return {}; +} +function specVersion(value) { + if (typeof value === "string" && value.trim()) + return value.trim(); + if (typeof value === "number" && Number.isFinite(value)) + return String(value); + return void 0; +} function parseFailed(source, detail) { return { diagnostic: { @@ -8221,6 +8695,7 @@ function parsed(source, kind, parsedSurface) { kind, path: source.path.replace(/\\/g, "/"), name: parsedSurface.name ?? source.path.split(/[\\/]/).at(-1) ?? source.path, + ...parsedSurface.version ? { version: parsedSurface.version } : {}, sourceFingerprint: source.fingerprint, entries: normalizeEntries(parsedSurface.entries) } @@ -8356,50 +8831,6 @@ function parseMigration(content) { } return { entries }; } -function parseOpenApiYaml(content) { - return parseChannelYaml(content, "paths", HTTP_METHODS); -} -function parseAsyncApiYaml(content) { - return parseChannelYaml(content, "channels", /* @__PURE__ */ new Set(["publish", "subscribe"])); -} -function parseChannelYaml(content, sectionName, operations) { - const entries = []; - const lines = content.split(/\r?\n/); - let inSection = false; - let sectionIndent = -1; - let currentPath; - let pathIndent = -1; - for (const raw of lines) { - const withoutComment = raw.replace(/\s+#.*$/, ""); - const trimmed = withoutComment.trim(); - if (!trimmed) - continue; - const indent = withoutComment.length - withoutComment.trimStart().length; - if (!inSection && trimmed === `${sectionName}:`) { - inSection = true; - sectionIndent = indent; - continue; - } - if (!inSection) - continue; - if (indent <= sectionIndent) - break; - const key = /^([^:]+):\s*$/.exec(trimmed)?.[1]?.trim(); - if (!key) - continue; - if (indent > sectionIndent && (currentPath === void 0 || indent <= pathIndent)) { - currentPath = unquote2(key); - pathIndent = indent; - continue; - } - if (currentPath && indent > pathIndent && operations.has(key.toLowerCase())) { - const operation = sectionName === "paths" ? `${key.toUpperCase()} ${currentPath}` : `${key.toLowerCase()} ${currentPath}`; - entries.push(entry(`operation:${sectionName === "paths" ? operation : `${key.toLowerCase()}:${currentPath}`}`, "operation", operation)); - } - } - const title = content.match(/^\s*title\s*:\s*["']?([^\r\n"']+)/m)?.[1]?.trim(); - return { ...title ? { name: title } : {}, entries }; -} function entry(key, role, signature, required = false) { return { key, role, signature: signature.trim(), required }; } @@ -8451,9 +8882,6 @@ function parseJson(content) { function isRecord7(value) { return typeof value === "object" && value !== null && !Array.isArray(value); } -function unquote2(value) { - return value.replace(/^["']|["']$/g, ""); -} function stableHash3(value) { let hash = 0xcbf29ce484222325n; for (const byte of new TextEncoder().encode(value)) { @@ -8465,7 +8893,7 @@ function stableHash3(value) { // packages/core/dist/change-scope.js var MAX_ANCHORS = 64; -var MAX_DEPTH = 8; +var MAX_DEPTH2 = 8; var MAX_NODES = 2e3; function buildChangeScope(repo, input) { if (!Number.isFinite(Date.parse(input.asOf))) @@ -8527,13 +8955,13 @@ function buildChangeScope(repo, input) { const visited = new Set(selectedPaths.keys()); const queue = [...selectedPaths.keys()].map((path) => ({ path, distance: 0 })); while (queue.length > 0) { - const current = queue.shift(); - if (current.distance >= traversal.maxDepth) + const current2 = queue.shift(); + if (current2.distance >= traversal.maxDepth) continue; - for (const neighbor of scopeNeighbors(graph, current.path, traversal.direction)) { + for (const neighbor of scopeNeighbors(graph, current2.path, traversal.direction)) { if (visited.has(neighbor.path)) { const existing = affected.get(neighbor.path); - if (existing && current.distance + 1 <= existing.distance && !existing.evidence.some((entry2) => evidenceKey2(entry2) === evidenceKey2(neighbor.evidence))) { + if (existing && current2.distance + 1 <= existing.distance && !existing.evidence.some((entry2) => evidenceKey2(entry2) === evidenceKey2(neighbor.evidence))) { existing.evidence.push(neighbor.evidence); existing.evidence.sort((left, right) => left.kind.localeCompare(right.kind) || left.reason.localeCompare(right.reason)); } @@ -8544,7 +8972,7 @@ function buildChangeScope(repo, input) { continue; } visited.add(neighbor.path); - const distance = current.distance + 1; + const distance = current2.distance + 1; affected.set(neighbor.path, { distance, evidence: [neighbor.evidence] }); queue.push({ path: neighbor.path, distance }); } @@ -8635,8 +9063,8 @@ function normalizeTraversal(input) { } const maxDepth = input.maxDepth ?? 2; const maxNodes = input.maxNodes ?? 200; - if (!Number.isSafeInteger(maxDepth) || maxDepth < 0 || maxDepth > MAX_DEPTH) { - throw new Error(`Change-scope maxDepth must be an integer from 0 to ${MAX_DEPTH}.`); + if (!Number.isSafeInteger(maxDepth) || maxDepth < 0 || maxDepth > MAX_DEPTH2) { + throw new Error(`Change-scope maxDepth must be an integer from 0 to ${MAX_DEPTH2}.`); } if (!Number.isSafeInteger(maxNodes) || maxNodes < 1 || maxNodes > MAX_NODES) { throw new Error(`Change-scope maxNodes must be an integer from 1 to ${MAX_NODES}.`); @@ -9427,21 +9855,21 @@ function capabilitySnapshot(historical, id, asOf) { testAssociations }; } -function comparePaths(previous, current) { - return compareMaps(new Map(previous.map((entry2) => [entry2.path, entry2.sourceFingerprint ?? "unknown"])), new Map(current.map((entry2) => [entry2.path, entry2.sourceFingerprint ?? "unknown"]))); +function comparePaths(previous, current2) { + return compareMaps(new Map(previous.map((entry2) => [entry2.path, entry2.sourceFingerprint ?? "unknown"])), new Map(current2.map((entry2) => [entry2.path, entry2.sourceFingerprint ?? "unknown"]))); } -function compareEntities(previous, current) { - return compareMaps(new Map(previous.map((entry2) => [entry2.id, entry2.fingerprint])), new Map(current.map((entry2) => [entry2.id, entry2.fingerprint]))); +function compareEntities(previous, current2) { + return compareMaps(new Map(previous.map((entry2) => [entry2.id, entry2.fingerprint])), new Map(current2.map((entry2) => [entry2.id, entry2.fingerprint]))); } -function compareMaps(previous, current) { - const keys = [.../* @__PURE__ */ new Set([...previous.keys(), ...current.keys()])].sort(); +function compareMaps(previous, current2) { + const keys = [.../* @__PURE__ */ new Set([...previous.keys(), ...current2.keys()])].sort(); const result = { added: [], removed: [], modified: [], unchanged: [] }; for (const key of keys) { if (!previous.has(key)) result.added.push(key); - else if (!current.has(key)) + else if (!current2.has(key)) result.removed.push(key); - else if (previous.get(key) !== current.get(key)) + else if (previous.get(key) !== current2.get(key)) result.modified.push(key); else result.unchanged.push(key); @@ -9469,6 +9897,14 @@ function canonicalize2(value) { return JSON.stringify(value); } +// packages/core/dist/contracts-repository.js +import { execFile as execFile4 } from "node:child_process"; +import { promisify as promisify4 } from "node:util"; +var exec4 = promisify4(execFile4); +var MAX_CONTRACT_BYTES = 2 * 1024 * 1024; +var MAX_TREE_BYTES2 = 32 * 1024 * 1024; +var MAX_TOTAL_BYTES = 64 * 1024 * 1024; + // packages/action/src/annotations.ts async function runAnnotationAction(input, repoRoot, allowWrite) { if (Buffer.byteLength(input, "utf8") > 32768) throw new Error("annotation-request exceeds 32 KiB."); @@ -10271,19 +10707,19 @@ function trimToBoundary(text) { } function splitExcludeInput(raw) { const patterns2 = []; - let current = ""; + let current2 = ""; let depth5 = 0; for (const character of raw) { if (character === "{") depth5 += 1; else if (character === "}") depth5 = Math.max(0, depth5 - 1); if (character === "\n" || character === "\r" || character === "," && depth5 === 0) { - patterns2.push(current); - current = ""; + patterns2.push(current2); + current2 = ""; continue; } - current += character; + current2 += character; } - patterns2.push(current); + patterns2.push(current2); return patterns2.map((pattern) => pattern.trim()).filter(Boolean); } function fitStepSummary(markdown, limitBytes = STEP_SUMMARY_LIMIT_BYTES) { diff --git a/packages/cli/src/cli-runner.ts b/packages/cli/src/cli-runner.ts index 66feda9..19d9cfb 100644 --- a/packages/cli/src/cli-runner.ts +++ b/packages/cli/src/cli-runner.ts @@ -113,6 +113,7 @@ Usage: fixmap migrate --input migration.json --format markdown fixmap reverse-docs --input reverse-docs.json --format markdown fixmap history --repo . --from v0.9.0 --to HEAD + fixmap contracts diff v0.9.0..HEAD fixmap supply-chain --input supply-chain.json fixmap runtime --input runtime.json fixmap sandbox --request sandbox.json --execute-declared-command @@ -139,6 +140,7 @@ Commands: migrate Preview: Build a dependency-ordered, review-only migration plan reverse-docs Preview: Draft review-only documentation from exact structural evidence history Preview: Compare architecture at two committed Git refs without checkout + contracts Preview: List API/schema contracts or diff them across Git refs without checkout supply-chain Preview: Import normalized external scanner and SBOM evidence runtime Preview: Map redaction-reviewed runtime evidence to exact files sandbox Preview: Run one explicitly consented command in an isolated container @@ -548,6 +550,15 @@ export async function runCli(args: string[], dependencies: CliDependencies = {}) }); } + if (args[0] === "contracts") { + const { runContractsCommand } = await import("./contracts-command.js"); + return runContractsCommand(args.slice(1), { + stdout, + stderr, + ...(dependencies.writeReport ? { writeOutput: dependencies.writeReport } : {}) + }); + } + if (args[0] === "supply-chain") { const { runSupplyChainCommand } = await import("./supply-chain-command.js"); return runSupplyChainCommand(args.slice(1), { diff --git a/packages/cli/src/contracts-command.ts b/packages/cli/src/contracts-command.ts new file mode 100644 index 0000000..93d48ac --- /dev/null +++ b/packages/cli/src/contracts-command.ts @@ -0,0 +1,254 @@ +import { lstat, readFile, realpath, stat, writeFile } from "node:fs/promises"; +import { homedir } from "node:os"; +import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path"; +import { + compareContractRefs, + inventoryWorkingTreeContracts, + isFixMapArtifact, + scanRepo, + type ContractChange, + type ContractDiagnostic, + type ContractInventory, + type ContractRefComparison +} from "@aryam/fixmap-core"; + +export const CONTRACTS_USAGE = `Usage: + fixmap contracts [--repo ] [--format markdown|json] [--output ] [--no-cache] + fixmap contracts diff .. [--repo ] [--format markdown|json] [--output ] + +Lists OpenAPI, AsyncAPI, GraphQL, Protobuf, JSON Schema, and SQL migration contracts in the +working tree, or compares them at two exact Git refs through Git objects without checking out +either ref or changing the worktree. Changes are classified as breaking, unknown, or compatible +with before/after fingerprints. Unreadable or unparseable contracts are reported, never skipped. +`; + +type Format = "markdown" | "json"; +type CommandIO = { + stdout?: (text: string) => void; + stderr?: (text: string) => void; + writeOutput?: (path: string, contents: string) => Promise; +}; + +export type ContractList = { contractListVersion: 1; inventory: ContractInventory }; + +export async function runContractsCommand(args: string[], io: CommandIO = {}): Promise { + const stdout = io.stdout ?? ((text: string) => process.stdout.write(text)); + const stderr = io.stderr ?? ((text: string) => process.stderr.write(text)); + if (args.includes("--help") || args.includes("-h")) { + stdout(CONTRACTS_USAGE); + return 0; + } + const isDiff = args[0] === "diff"; + let options: Options; + try { + options = parseOptions(isDiff ? args.slice(1) : args, isDiff); + } catch (error) { + stderr(`${message(error)}\n\n${CONTRACTS_USAGE}`); + return 1; + } + try { + const repoRoot = await repositoryRoot(options.repo); + if (options.output) await assertOutputSafe(repoRoot, options.output); + let rendered: string; + if (options.range) { + const result = await compareContractRefs({ repoRoot, fromRef: options.range.from, toRef: options.range.to }); + rendered = options.format === "json" ? `${JSON.stringify(result, null, 2)}\n` : renderContractDiffMarkdown(result); + } else { + const repo = await scanRepo({ repoRoot, useCache: !options.noCache }); + const scanError = repo.diagnostics.find((diagnostic) => diagnostic.severity === "error"); + if (scanError) throw new Error(scanError.message); + const list: ContractList = { contractListVersion: 1, inventory: await inventoryWorkingTreeContracts(repo) }; + rendered = options.format === "json" ? `${JSON.stringify(list, null, 2)}\n` : renderContractListMarkdown(list); + } + if (options.output) await (io.writeOutput ?? ((path, contents) => writeFile(path, contents, "utf8")))(options.output, rendered); + else stdout(rendered); + return 0; + } catch (error) { + stderr(`${contractsError(options.repo, error)}\n`); + return 1; + } +} + +export function renderContractListMarkdown(list: ContractList): string { + const { surfaces, diagnostics } = list.inventory; + const lines = [ + "# FixMap Contracts", + "", + surfaces.length === 0 + ? "No supported contract surfaces were found in the working tree." + : `${surfaces.length} contract surface${surfaces.length === 1 ? "" : "s"} in the working tree.`, + "", + "## Surfaces", + "" + ]; + if (surfaces.length === 0) lines.push("- None found."); + else { + lines.push("| Path | Kind | Name | Version | Entries | Fingerprint |", "| --- | --- | --- | --- | --- | --- |"); + for (const surface of surfaces) { + lines.push(`| ${cell(surface.path)} | ${surface.kind} | ${cell(surface.name)} | ${surface.version ? cell(surface.version) : "-"} | ${surface.entries.length} | ${cell(surface.sourceFingerprint)} |`); + } + } + lines.push("", ...diagnosticLines(diagnostics)); + lines.push("> Read-only inventory. FixMap parsed contract text locally and did not execute repository code."); + return `${lines.join("\n")}\n`; +} + +export function renderContractDiffMarkdown(result: ContractRefComparison): string { + const { comparison } = result; + const lines = [ + "# FixMap Contract Diff", + "", + `From: \`${result.from.requestedRef}\` at \`${result.from.commit}\``, + `To: \`${result.to.requestedRef}\` at \`${result.to.commit}\``, + "", + comparison.summary, + "" + ]; + for (const compatibility of ["breaking", "unknown", "compatible"] as const) { + const changes = comparison.changes.filter((change) => change.compatibility === compatibility); + lines.push(`## ${compatibility[0]!.toUpperCase()}${compatibility.slice(1)}`, ""); + if (changes.length === 0) lines.push("- None."); + for (const change of changes) lines.push(changeLine(change)); + lines.push(""); + } + lines.push(...diagnosticLines(comparison.diagnostics)); + lines.push("> Read-only historical comparison. FixMap read committed Git objects and did not checkout a ref or change the worktree."); + return `${lines.join("\n")}\n`; +} + +function changeLine(change: ContractChange): string { + const before = change.evidence.beforeFingerprint ? `\`${change.evidence.beforeFingerprint}\`` : "absent"; + const after = change.evidence.afterFingerprint ? `\`${change.evidence.afterFingerprint}\`` : "absent"; + return `- \`${change.path}\` (${change.contractKind}): ${change.reason} Fingerprints: ${before} -> ${after}.`; +} + +function diagnosticLines(diagnostics: readonly ContractDiagnostic[]): string[] { + if (diagnostics.length === 0) return []; + return ["## Diagnostics", "", ...diagnostics.map((diagnostic) => `- \`${diagnostic.path}\` (${diagnostic.code}): ${diagnostic.message}`), ""]; +} + +function cell(value: string): string { + return `\`${value.replace(/[|`\r\n]/g, " ")}\``; +} + +type Options = { + repo: string; + format: Format; + noCache: boolean; + output?: string; + range?: { from: string; to: string }; +}; + +function parseOptions(args: string[], isDiff: boolean): Options { + const rest = [...args]; + let rangeText: string | undefined; + if (isDiff) { + if (!rest[0] || rest[0].startsWith("--")) throw new Error("contracts diff requires ..."); + rangeText = rest.shift(); + } + const values = new Map(); + let noCache = false; + for (let index = 0; index < rest.length; index += 1) { + const raw = rest[index]!; + if (raw === "--no-cache") { + if (isDiff) throw new Error("--no-cache does not apply to immutable Git-ref contract diffs."); + if (noCache) throw new Error("Pass --no-cache only once."); + noCache = true; + continue; + } + const equals = /^(--[a-z-]+)=(.*)$/s.exec(raw); + const flag = equals?.[1] ?? raw; + if (!["--repo", "--format", "--output"].includes(flag)) throw new Error(`Unknown contracts option: ${raw}`); + if (values.has(flag)) throw new Error(`Pass ${flag} only once.`); + const value = equals?.[2] ?? rest[++index]; + if (typeof value !== "string" || !value.trim() || (!equals && value.startsWith("--"))) throw new Error(`${flag} requires a value.`); + if (/[\0\r\n]/.test(value)) throw new Error(`${flag} must be a single-line value.`); + values.set(flag, value.trim()); + } + const format = (values.get("--format") ?? "markdown").toLowerCase(); + if (format !== "markdown" && format !== "json") throw new Error("--format must be markdown or json."); + const repo = expandHome(values.get("--repo") ?? process.cwd()); + if (/^[a-z][a-z0-9+.-]*:\/\//i.test(repo)) throw new Error("contracts requires a local checkout, not a remote URL."); + const output = values.get("--output"); + return { + repo, + format, + noCache, + ...(output ? { output: expandHome(output) } : {}), + ...(rangeText !== undefined ? { range: parseRange(rangeText) } : {}) + }; +} + +function parseRange(value: string): { from: string; to: string } { + const index = value.indexOf(".."); + if (value.includes("...")) throw new Error("contracts diff compares two exact refs; use .., not a three-dot merge-base range."); + if (index <= 0 || index + 2 >= value.length || value.indexOf("..", index + 2) !== -1) throw new Error("contracts diff range must be ..."); + const from = value.slice(0, index).trim(); + const to = value.slice(index + 2).trim(); + if (!from || !to || from.length > 500 || to.length > 500 || /[\0\r\n]/.test(value)) { + throw new Error("contracts diff refs must be bounded single-line values."); + } + if (from.startsWith("-") || to.startsWith("-")) throw new Error("contracts diff refs cannot start with '-'."); + return { from, to }; +} + +async function repositoryRoot(input: string): Promise { + const root = resolve(input); + const info = await stat(root).catch(() => undefined); + if (!info?.isDirectory()) throw new Error("not-directory"); + return realpath(root); +} + +/** Refuses to overwrite a repository file unless it is a prior FixMap artifact. */ +async function assertOutputSafe(repoRoot: string, output: string): Promise { + // repoRoot is a real path, so the output must be too: otherwise an alias such as macOS + // /var -> /private/var, a symlinked directory, or a Windows junction looks "outside". + // Only the directory is resolved, so a symlinked output file itself is still refused below. + const requested = resolve(output); + const absolute = resolve(await realOutputPath(dirname(requested)), basename(requested)); + const outputRelative = relative(repoRoot, absolute); + if (!outputRelative || outputRelative === ".." || outputRelative.startsWith(`..${sep}`) || isAbsolute(outputRelative)) return; + const info = await lstat(absolute).catch(() => undefined); + if (!info) return; + const path = outputRelative.replace(/\\/g, "/"); + if (!info.isFile() || info.isSymbolicLink() || info.nlink > 1 || info.size > 4 * 1024 * 1024 || + !isFixMapArtifact({ path, textSample: await readFile(absolute, "utf8"), textSampleComplete: true })) { + throw new Error(`--output refuses to overwrite repository file ${path}; choose a new path or a prior FixMap contracts artifact.`); + } +} + +/** Resolves the nearest existing ancestor through realpath and keeps the not-yet-existing tail. */ +async function realOutputPath(absolute: string): Promise { + const tail: string[] = []; + let current = absolute; + for (;;) { + try { + return resolve(await realpath(current), ...tail.reverse()); + } catch { + const parent = dirname(current); + if (parent === current) return absolute; + tail.push(basename(current)); + current = parent; + } + } +} + +function contractsError(repo: string, error: unknown): string { + const text = message(error); + if (text === "not-directory") return `Contracts repository "${repo}" does not exist or is not a directory.`; + if (text.includes("Could not resolve Git ref")) { + return `Could not resolve one of the requested Git refs in "${repo}". Confirm both refs exist and the path is a Git checkout.`; + } + if (text.startsWith("--output refuses")) return text; + return `Could not read contracts in "${repo}": ${text.replace(/Command failed:[\s\S]*/i, "Git could not read the requested committed state.")}`; +} + +function message(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +function expandHome(value: string): string { + if (value === "~") return homedir(); + if (value.startsWith("~/") || value.startsWith("~\\")) return resolve(homedir(), value.slice(2)); + return value; +} diff --git a/packages/cli/src/mcp.ts b/packages/cli/src/mcp.ts index 70326eb..8f4b235 100644 --- a/packages/cli/src/mcp.ts +++ b/packages/cli/src/mcp.ts @@ -49,6 +49,7 @@ import { parseRuntimeInput, renderRuntimeMarkdown } from "./runtime-command.js"; import { runWorkspaceCommand } from "./workspace-command.js"; import { runChangeScopeCommand } from "./change-scope-command.js"; import { runCapabilitiesCommand, runCapabilityCommand } from "./capability-command.js"; +import { runContractsCommand } from "./contracts-command.js"; import { buildReportForRepository, isSafeGitRefName, @@ -407,6 +408,27 @@ const HISTORY_TOOL = { } }; +const CONTRACTS_TOOL = { + name: "fixmap_contracts", + title: "FixMap contracts", + description: + "Preview (may change before v0.10.0): List OpenAPI, AsyncAPI, GraphQL, Protobuf, JSON Schema, and SQL migration contracts in the working tree (action list), " + + "or compare them at two exact Git refs through Git objects without checking out either ref or changing the worktree (action diff). " + + "Each change is breaking, unknown, or compatible with before/after fingerprints; unparseable contracts are reported as diagnostics.", + annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }, + inputSchema: { + type: "object" as const, + properties: { + action: { type: "string", enum: ["list", "diff"], description: "list (default) inventories the working tree; diff compares from..to" }, + from: { type: "string", description: "Earlier exact Git ref; required for diff" }, + to: { type: "string", description: "Later exact Git ref; required for diff" }, + repo: { type: "string", description: "Local checkout path (defaults to the MCP server repository)" }, + format: { type: "string", description: "Output format: markdown (default) or json, case-insensitive" } + }, + additionalProperties: false + } +}; + const SUPPLY_CHAIN_TOOL = { name: "fixmap_supply_chain", title: "FixMap supply chain", @@ -516,7 +538,7 @@ export function createFixMapMcpServer( const server = new Server({ name: "fixmap", version: readVersion() }, { capabilities: { tools: {} } }); server.setRequestHandler(ListToolsRequestSchema, async () => ({ - tools: [PLAN_TOOL, CONTEXT_TOOL, GRAPH_TOOL, CHANGE_SCOPE_TOOL, CAPABILITY_TOOL, WORKSPACE_TOOL, ASK_TOOL, MIGRATION_TOOL, REVERSE_DOCS_TOOL, HISTORY_TOOL, SUPPLY_CHAIN_TOOL, RUNTIME_TOOL, VERIFY_TOOL, EXPLAIN_TOOL, COMPARE_TOOL, DOCTOR_TOOL, ANNOTATION_TOOL] + tools: [PLAN_TOOL, CONTEXT_TOOL, GRAPH_TOOL, CHANGE_SCOPE_TOOL, CAPABILITY_TOOL, WORKSPACE_TOOL, ASK_TOOL, MIGRATION_TOOL, REVERSE_DOCS_TOOL, HISTORY_TOOL, CONTRACTS_TOOL, SUPPLY_CHAIN_TOOL, RUNTIME_TOOL, VERIFY_TOOL, EXPLAIN_TOOL, COMPARE_TOOL, DOCTOR_TOOL, ANNOTATION_TOOL] })); server.setRequestHandler(CallToolRequestSchema, async (request) => { @@ -785,6 +807,37 @@ export function createFixMapMcpServer( : `Could not compare historical architecture in "${repoRoot}".` }] }; } } + if (request.params.name === CONTRACTS_TOOL.name) { + const record = (request.params.arguments ?? {}) as Record; + const invalid = (text: string) => ({ isError: true, content: [{ type: "text", text: `Invalid arguments: ${text}` }] }); + const unknown = Object.keys(record).filter((key) => !["action", "from", "to", "repo", "format"].includes(key)); + if (unknown.length > 0) return invalid(`unknown argument${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}.`); + if (record.action !== undefined && record.action !== "list" && record.action !== "diff") return invalid('"action" must be "list" or "diff".'); + const action = record.action ?? "list"; + for (const key of ["from", "to"] as const) { + const value = record[key]; + if (value !== undefined && (typeof value !== "string" || !value.trim() || value.length > 500 || /[\0\r\n]/.test(value) || value.includes("..") || value.trim().startsWith("-"))) { + return invalid(`"${key}" must be a bounded single-line Git ref.`); + } + } + if (action === "diff" && (record.from === undefined || record.to === undefined)) return invalid('action "diff" requires both "from" and "to".'); + if (action === "list" && (record.from !== undefined || record.to !== undefined)) return invalid('"from" and "to" apply only to action "diff".'); + if (record.repo !== undefined && (typeof record.repo !== "string" || !record.repo.trim() || /[\0\r\n]/.test(record.repo))) { + return invalid('"repo" must be a non-empty local path.'); + } + if (typeof record.repo === "string" && /^[a-z][a-z0-9+.-]*:\/\//i.test(record.repo.trim())) return invalid('"repo" must be a local checkout.'); + const format = normalizeFormat(record.format); + if (!format.success) return invalid(format.message); + const commandArgs = [ + ...(action === "diff" ? ["diff", `${String(record.from).trim()}..${String(record.to).trim()}`] : []), + "--repo", typeof record.repo === "string" ? record.repo.trim() : defaultRepo, + "--format", format.value ?? "markdown" + ]; + const stdout: string[] = []; + const stderr: string[] = []; + const exitCode = await runContractsCommand(commandArgs, { stdout: (value) => stdout.push(value), stderr: (value) => stderr.push(value) }); + return { ...(exitCode === 0 ? {} : { isError: true }), content: [{ type: "text", text: exitCode === 0 ? stdout.join("") : stderr.join("").trim() }] }; + } if (request.params.name === SUPPLY_CHAIN_TOOL.name) { const record = request.params.arguments as Record | undefined; const unknown = Object.keys(record ?? {}).filter((key) => !["input", "format"].includes(key)); diff --git a/packages/cli/test/cli-runner.test.ts b/packages/cli/test/cli-runner.test.ts index 7920fb2..9a959b6 100644 --- a/packages/cli/test/cli-runner.test.ts +++ b/packages/cli/test/cli-runner.test.ts @@ -200,7 +200,7 @@ describe("CLI argument handling", () => { const features = (JSON.parse(catalog.stdout.join("")) as { features: Array<{ name: string; preview?: true }> }).features; expect(features.filter((feature) => feature.preview).map((feature) => feature.name)).toEqual([ "Change scope", "Product capabilities", "Cross-repository workspace", "Repository Q&A", "Migration planning", - "Reverse documentation", "Architecture history", "Supply-chain evidence", "Runtime evidence", "Evidence import", "Execution sandbox", + "Reverse documentation", "Architecture history", "Contract Guardian", "Supply-chain evidence", "Runtime evidence", "Evidence import", "Execution sandbox", "Local hybrid retrieval" ]); expect(features.find((feature) => feature.name === "Plan")?.preview).toBeUndefined(); @@ -208,7 +208,7 @@ describe("CLI argument handling", () => { const help = capture(); expect(await runCli(["--help"], help.dependencies)).toBe(0); const commands = help.stdout.join("").split("Commands:")[1]?.split("Options:")[0] ?? ""; - for (const command of ["change-scope", "editor", "capability", "capabilities", "workspace", "ask", "migrate", "reverse-docs", "history", "supply-chain", "runtime", "sandbox"]) { + for (const command of ["change-scope", "editor", "capability", "capabilities", "workspace", "ask", "migrate", "reverse-docs", "history", "contracts", "supply-chain", "runtime", "sandbox"]) { expect(commands).toMatch(new RegExp(`\\n ${command} +Preview: `)); } for (const command of ["plan", "verify", "context", "graph", "annotate", "watch"]) { diff --git a/packages/cli/test/contracts-command.test.ts b/packages/cli/test/contracts-command.test.ts new file mode 100644 index 0000000..92b47ff --- /dev/null +++ b/packages/cli/test/contracts-command.test.ts @@ -0,0 +1,359 @@ +import { execFile } from "node:child_process"; +import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { promisify } from "node:util"; +import { afterEach, describe, expect, it } from "vitest"; +import { runCli } from "../src/cli-runner.js"; + +const exec = promisify(execFile); +const GIT_TEST_TIMEOUT = process.platform === "win32" ? 60_000 : 20_000; +const roots: string[] = []; + +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }))); +}); + +async function git(root: string, ...args: string[]): Promise { + return (await exec("git", args, { cwd: root })).stdout; +} + +async function write(root: string, files: Record): Promise { + for (const [path, content] of Object.entries(files)) { + await mkdir(dirname(join(root, path)), { recursive: true }); + await writeFile(join(root, path), content, "utf8"); + } +} + +async function repository(): Promise { + const root = await mkdtemp(join(tmpdir(), "fixmap-contracts-cli-")); + roots.push(root); + await git(root, "init", "--quiet"); + await git(root, "config", "user.email", "fixmap@example.test"); + await git(root, "config", "user.name", "FixMap Test"); + await git(root, "config", "core.autocrlf", "false"); + return root; +} + +async function commit(root: string, files: Record, message: string, remove: string[] = []): Promise { + await write(root, files); + for (const path of remove) await git(root, "rm", "--quiet", path); + await git(root, "add", "-A"); + await git(root, "commit", "--quiet", "--allow-empty", "-m", message); + return (await git(root, "rev-parse", "HEAD")).trim(); +} + +function capture() { + const stdout: string[] = []; + const stderr: string[] = []; + return { + stdout, + stderr, + dependencies: { stdout: (text: string) => stdout.push(text), stderr: (text: string) => stderr.push(text) } + }; +} + +async function contractsJson(args: string[]) { + const io = capture(); + const exitCode = await runCli(["contracts", ...args, "--format", "json"], io.dependencies); + expect(io.stderr.join("")).toBe(""); + expect(exitCode).toBe(0); + return JSON.parse(io.stdout.join("")); +} + +const OPENAPI_V1 = { + openapi: "3.1.0", + info: { title: "Users" }, + paths: { "/users": { get: {}, post: { parameters: [{ name: "trace", in: "header", required: false, schema: { type: "string" } }] } } }, + components: { schemas: { User: { type: "object", properties: { id: { type: "string" } } } } } +}; +const OPENAPI_YAML_V1 = `openapi: 3.1.0 +info: + title: Users +paths: + /users: + get: {} + post: + parameters: + - name: trace + in: header + required: false + schema: + type: string +components: + schemas: + User: + type: object + properties: + id: { type: string } +`; +const OPENAPI_V2 = { + openapi: "3.1.0", + info: { title: "Users" }, + paths: { "/users": { post: { parameters: [ + { name: "trace", in: "header", required: false, schema: { type: "string" } }, + { name: "tenant", in: "header", required: true, schema: { type: "string" } } + ] } } }, + components: { schemas: { User: { type: "object", properties: { id: { type: "string" }, nickname: { type: "string" } } } } } +}; +const OPENAPI_YAML_V2 = `openapi: 3.1.0 +info: + title: Users +paths: + /users: + post: + parameters: + - name: trace + in: header + required: false + schema: + type: string + - name: tenant + in: header + required: true + schema: { type: string } +components: + schemas: + User: + type: object + properties: + id: { type: string } + nickname: + type: string +`; + +describe("contracts command", () => { + it("lists every supported working-tree contract with kind, version, and exact fingerprint", async () => { + const root = await repository(); + await commit(root, { + "api/openapi.yaml": OPENAPI_YAML_V1, + "events/asyncapi.json": JSON.stringify({ asyncapi: "2.6.0", info: { title: "Events" }, channels: { "user.created": { publish: {} } } }), + "schema/schema.graphql": "type Query { user(id: ID!): User }\ntype User { id: ID! }\n", + "proto/user.proto": "syntax = \"proto3\";\nmessage User { string id = 1; }\n", + "schemas/user.schema.json": JSON.stringify({ $schema: "https://json-schema.org/draft/2020-12/schema", title: "User", properties: { id: { type: "string" } } }), + "db/migrations/001_users.sql": "CREATE TABLE users (id text);\n", + "src/index.ts": "export const ok = true;\n" + }, "contracts"); + + const list = await contractsJson(["--repo", root, "--no-cache"]); + expect(list.contractListVersion).toBe(1); + expect(list.inventory.diagnostics).toEqual([]); + expect(list.inventory.surfaces.map((surface: { kind: string; path: string; version?: string }) => [surface.kind, surface.path, surface.version])).toEqual([ + ["asyncapi", "events/asyncapi.json", "2.6.0"], + ["graphql", "schema/schema.graphql", undefined], + ["json-schema", "schemas/user.schema.json", "https://json-schema.org/draft/2020-12/schema"], + ["migration", "db/migrations/001_users.sql", undefined], + ["openapi", "api/openapi.yaml", "3.1.0"], + ["protobuf", "proto/user.proto", "proto3"] + ]); + for (const surface of list.inventory.surfaces) { + expect(surface.sourceFingerprint).toMatch(/^worktree:[a-f0-9]{64}$/); + // GraphQL, Protobuf, and SQL are read in full rather than reported as empty surfaces. + expect(surface.entries.length).toBeGreaterThan(0); + } + + const markdown = capture(); + expect(await runCli(["contracts", "--repo", root], markdown.dependencies)).toBe(0); + const text = markdown.stdout.join(""); + expect(text).toMatch(/^# FixMap Contracts\n/); + expect(text).toContain("6 contract surfaces in the working tree."); + expect(text).toContain("| `api/openapi.yaml` | openapi | `Users` | `3.1.0` |"); + }, GIT_TEST_TIMEOUT); + + it("reports a repository with no contracts without failing", async () => { + const root = await repository(); + await commit(root, { "src/index.ts": "export const ok = true;\n", "package.json": "{\"name\":\"plain\"}\n" }, "plain"); + const list = await contractsJson(["--repo", root]); + expect(list.inventory).toEqual({ inventoryVersion: 1, surfaces: [], diagnostics: [] }); + const io = capture(); + expect(await runCli(["contracts", "--repo", root], io.dependencies)).toBe(0); + expect(io.stdout.join("")).toContain("No supported contract surfaces were found in the working tree."); + }, GIT_TEST_TIMEOUT); + + it("reports malformed specs as diagnostics instead of skipping them", async () => { + const root = await repository(); + await commit(root, { + "openapi.yaml": "openapi: 3.1.0\npaths:\n /a: &shared\n get: {}\n /b: *shared\n", + "api/openapi.json": "{ \"openapi\": \"3.1.0\", ", + "schema.graphql": "this is not GraphQL SDL\n" + }, "broken"); + const list = await contractsJson(["--repo", root]); + expect(list.inventory.surfaces).toEqual([]); + expect(list.inventory.diagnostics.map((diagnostic: { path: string; code: string }) => [diagnostic.path, diagnostic.code])).toEqual([ + ["api/openapi.json", "contract-parse-failed"], + ["openapi.yaml", "contract-parse-failed"], + ["schema.graphql", "contract-parse-failed"] + ]); + expect(list.inventory.diagnostics[1].message).toContain("anchors, aliases, and tags are not supported"); + }, GIT_TEST_TIMEOUT); + + it("diffs exact refs into breaking, unknown, and compatible changes without changing HEAD or git status", async () => { + const root = await repository(); + const before = await commit(root, { + "api/openapi.json": JSON.stringify(OPENAPI_V1, null, 2), + "schema.graphql": "type Query { ok: Boolean }\n", + "db/migrations/001.sql": "CREATE TABLE users (id text);\n" + }, "before"); + const after = await commit(root, { + "api/openapi.json": JSON.stringify(OPENAPI_V2, null, 2), + "schema.graphql": "this is not GraphQL SDL\n", + "db/migrations/001.sql": "CREATE TABLE users (id text, nickname text);\n", + "proto/new.proto": "message Added { string id = 1; }\n" + }, "after"); + // Uncommitted edits must survive and must not leak into the committed comparison. + await writeFile(join(root, "api/openapi.json"), "{ \"dirty\": true }", "utf8"); + const headBefore = await git(root, "rev-parse", "HEAD"); + const statusBefore = await git(root, "status", "--porcelain=v1"); + + const diff = await contractsJson(["diff", `${before}..${after}`, "--repo", root]); + expect(diff.contractDiffVersion).toBe(1); + expect(diff.from).toEqual({ requestedRef: before, commit: before }); + expect(diff.to).toEqual({ requestedRef: after, commit: after }); + const changes = diff.comparison.changes as Array & { evidence: Record }>; + expect(changes).toEqual(expect.arrayContaining([ + expect.objectContaining({ path: "api/openapi.json", entry: "operation:GET /users", compatibility: "breaking" }), + expect.objectContaining({ path: "api/openapi.json", entry: "argument:POST /users:header:tenant", compatibility: "breaking" }), + expect.objectContaining({ path: "api/openapi.json", entry: "field:User.nickname", compatibility: "compatible" }), + expect.objectContaining({ path: "schema.graphql", change: "contract-unavailable", compatibility: "unknown" }), + expect.objectContaining({ path: "db/migrations/001.sql", change: "entry-removed", compatibility: "unknown" }), + expect.objectContaining({ path: "proto/new.proto", change: "contract-added", compatibility: "compatible" }) + ])); + const severity = { breaking: 0, unknown: 1, compatible: 2 } as Record; + expect(changes.map((change) => severity[change.compatibility as string])).toEqual( + [...changes.map((change) => severity[change.compatibility as string])].sort((a, b) => a! - b!) + ); + const tenant = changes.find((change) => change.entry === "argument:POST /users:header:tenant")!; + expect(tenant.evidence.beforeFingerprint).toMatch(/^git:[a-f0-9]{40}$/); + expect(tenant.evidence.afterFingerprint).toMatch(/^git:[a-f0-9]{40}$/); + expect(tenant.evidence.beforeFingerprint).not.toBe(tenant.evidence.afterFingerprint); + expect(diff.comparison.diagnostics).toContainEqual(expect.objectContaining({ path: "schema.graphql", code: "contract-parse-failed" })); + + const markdown = capture(); + expect(await runCli(["contracts", "diff", `${before}..${after}`, "--repo", root], markdown.dependencies)).toBe(0); + const text = markdown.stdout.join(""); + expect(text).toContain(`From: \`${before}\` at \`${before}\``); + expect(text).toMatch(/## Breaking\n\n- `api\/openapi\.json` \(openapi\): .* Fingerprints: `git:[a-f0-9]{40}` -> `git:[a-f0-9]{40}`\./); + expect(text).toContain("## Unknown"); + expect(text).toContain("## Compatible"); + expect(text).toContain("did not checkout a ref or change the worktree"); + + expect(await git(root, "rev-parse", "HEAD")).toBe(headBefore); + expect(await git(root, "status", "--porcelain=v1")).toBe(statusBefore); + expect(await readFile(join(root, "api/openapi.json"), "utf8")).toBe("{ \"dirty\": true }"); + }, GIT_TEST_TIMEOUT); + + it("produces the same deltas for YAML and JSON spellings of one OpenAPI change", async () => { + const root = await repository(); + const before = await commit(root, { "json/openapi.json": JSON.stringify(OPENAPI_V1), "yaml/openapi.yaml": OPENAPI_YAML_V1 }, "before"); + const after = await commit(root, { "json/openapi.json": JSON.stringify(OPENAPI_V2), "yaml/openapi.yaml": OPENAPI_YAML_V2 }, "after"); + const diff = await contractsJson(["diff", `${before}..${after}`, "--repo", root]); + const shape = (prefix: string) => (diff.comparison.changes as Array>) + .filter((change) => String(change.path).startsWith(prefix)) + .map(({ change, compatibility, entry, before: was, after: now, reason }) => ({ change, compatibility, entry, was, now, reason })); + expect(shape("json/").map((change) => [change.entry, change.compatibility])).toEqual([ + ["argument:POST /users:header:tenant", "breaking"], + ["operation:GET /users", "breaking"], + ["field:User.nickname", "compatible"] + ]); + expect(shape("yaml/")).toEqual(shape("json/")); + expect(diff.comparison.diagnostics).toEqual([]); + }, GIT_TEST_TIMEOUT); + + it("reports a contract removed between refs as breaking and an identical range as unchanged", async () => { + const root = await repository(); + const before = await commit(root, { "schema.graphql": "type Query { ok: Boolean }\n", "README.md": "x\n" }, "before"); + const after = await commit(root, {}, "after", ["schema.graphql"]); + const removed = await contractsJson(["diff", `${before}..${after}`, "--repo", root]); + expect(removed.comparison.changes).toEqual([expect.objectContaining({ change: "contract-removed", compatibility: "breaking" })]); + const same = await contractsJson(["diff", `${after}..HEAD`, "--repo", root]); + expect(same.comparison).toMatchObject({ summary: "No supported contract surface changed.", changes: [] }); + }, GIT_TEST_TIMEOUT); + + it("fails clearly on refs that do not exist and on non-Git directories", async () => { + const root = await repository(); + await commit(root, { "schema.graphql": "type Query { ok: Boolean }\n" }, "only"); + const missing = capture(); + expect(await runCli(["contracts", "diff", "HEAD..does-not-exist", "--repo", root], missing.dependencies)).toBe(1); + expect(missing.stderr.join("")).toContain("Could not resolve one of the requested Git refs"); + expect(missing.stdout).toEqual([]); + + const plain = await mkdtemp(join(tmpdir(), "fixmap-contracts-plain-")); + roots.push(plain); + const notGit = capture(); + expect(await runCli(["contracts", "diff", "HEAD~1..HEAD", "--repo", plain], notGit.dependencies)).toBe(1); + expect(notGit.stderr.join("")).toContain("Could not resolve one of the requested Git refs"); + + const absent = capture(); + expect(await runCli(["contracts", "--repo", join(plain, "missing")], absent.dependencies)).toBe(1); + expect(absent.stderr.join("")).toContain("does not exist or is not a directory"); + }, GIT_TEST_TIMEOUT); + + it("validates arguments strictly", async () => { + const cases: Array<[string[], string]> = [ + [["diff"], "contracts diff requires ..."], + [["diff", "main"], "contracts diff range must be ..."], + [["diff", "main...HEAD"], "not a three-dot merge-base range"], + [["diff", "..HEAD"], "contracts diff range must be ..."], + [["diff", "a..b..c"], "contracts diff range must be ..."], + [["diff", "--upload-pack=x..HEAD"], "contracts diff requires ..."], + [["diff", "-x..HEAD"], "cannot start with '-'"], + [["diff", "a..b", "--no-cache"], "--no-cache does not apply"], + [["--format", "xml"], "--format must be markdown or json."], + [["--bogus"], "Unknown contracts option: --bogus"], + [["--repo", "https://example.com/repo.git"], "local checkout"], + [["--repo", "a", "--repo", "b"], "Pass --repo only once."], + [["--output"], "--output requires a value."] + ]; + for (const [args, expected] of cases) { + const io = capture(); + expect(await runCli(["contracts", ...args], io.dependencies)).toBe(1); + expect(io.stderr.join("")).toContain(expected); + } + const help = capture(); + expect(await runCli(["contracts", "--help"], help.dependencies)).toBe(0); + expect(help.stdout.join("")).toContain("fixmap contracts diff .."); + }); + + it("refuses to overwrite a repository file but replaces its own prior artifact", async () => { + const root = await repository(); + await commit(root, { "schema.graphql": "type Query { ok: Boolean }\n", "notes.md": "keep me\n" }, "only"); + const refused = capture(); + expect(await runCli(["contracts", "--repo", root, "--output", join(root, "notes.md")], refused.dependencies)).toBe(1); + expect(refused.stderr.join("")).toContain("--output refuses to overwrite repository file notes.md"); + expect(await readFile(join(root, "notes.md"), "utf8")).toBe("keep me\n"); + + const target = join(root, "contracts.json"); + for (let run = 0; run < 2; run += 1) { + const io = capture(); + expect(await runCli(["contracts", "--repo", root, "--format", "json", "--output", target], io.dependencies)).toBe(0); + } + expect(JSON.parse(await readFile(target, "utf8")).contractListVersion).toBe(1); + }, GIT_TEST_TIMEOUT); + + it("refuses repository overwrites through a realpath-aliased directory", async () => { + // macOS tmpdir is /var/... while realpath is /private/var/...; a directory link reproduces + // that alias on every platform (a junction on Windows needs no extra privilege). + const root = await repository(); + await commit(root, { "schema.graphql": "type Query { ok: Boolean }\n", "docs/notes.md": "keep me\n" }, "only"); + const aliasParent = await mkdtemp(join(tmpdir(), "fixmap-contracts-alias-")); + roots.push(aliasParent); + const alias = join(aliasParent, "repo-alias"); + await symlink(root, alias, process.platform === "win32" ? "junction" : "dir"); + + for (const [repoArg, outputArg] of [ + [root, join(alias, "docs", "notes.md")], + [alias, join(root, "docs", "notes.md")], + [alias, join(alias, "docs", "notes.md")] + ] as const) { + const io = capture(); + expect(await runCli(["contracts", "--repo", repoArg, "--output", outputArg], io.dependencies)).toBe(1); + expect(io.stderr.join("")).toContain("--output refuses to overwrite repository file docs/notes.md"); + } + expect(await readFile(join(root, "docs", "notes.md"), "utf8")).toBe("keep me\n"); + + // A new file under a not-yet-existing directory inside the aliased repository is allowed. + const fresh = capture(); + expect(await runCli(["contracts", "--repo", root, "--output", join(alias, "out", "contracts.md")], { ...fresh.dependencies, writeReport: async () => {} })).toBe(0); + expect(fresh.stderr).toEqual([]); + }, GIT_TEST_TIMEOUT); +}); diff --git a/packages/cli/test/mcp.test.ts b/packages/cli/test/mcp.test.ts index 8c444a5..74199cd 100644 --- a/packages/cli/test/mcp.test.ts +++ b/packages/cli/test/mcp.test.ts @@ -195,7 +195,7 @@ describe("fixmap mcp server", () => { const { tools } = await client.listTools(); const preview = tools.filter((tool) => tool.description?.startsWith("Preview (may change before v0.10.0): ")).map((tool) => tool.name).sort(); expect(preview).toEqual([ - "fixmap_ask", "fixmap_capability", "fixmap_change_scope", "fixmap_history", "fixmap_migrate", + "fixmap_ask", "fixmap_capability", "fixmap_change_scope", "fixmap_contracts", "fixmap_history", "fixmap_migrate", "fixmap_reverse_docs", "fixmap_runtime", "fixmap_supply_chain", "fixmap_workspace" ]); for (const finished of ["fixmap_plan", "fixmap_context", "fixmap_graph", "fixmap_verify", "fixmap_explain", "fixmap_compare", "fixmap_doctor"]) { @@ -393,7 +393,7 @@ describe("fixmap mcp server", () => { const tools = await client.listTools(); expect(tools.tools.map((tool) => tool.name)).toEqual([ - "fixmap_plan", "fixmap_context", "fixmap_graph", "fixmap_change_scope", "fixmap_capability", "fixmap_workspace", "fixmap_ask", "fixmap_migrate", "fixmap_reverse_docs", "fixmap_history", "fixmap_supply_chain", "fixmap_runtime", "fixmap_verify", "fixmap_explain", "fixmap_compare", "fixmap_doctor", "fixmap_annotate" + "fixmap_plan", "fixmap_context", "fixmap_graph", "fixmap_change_scope", "fixmap_capability", "fixmap_workspace", "fixmap_ask", "fixmap_migrate", "fixmap_reverse_docs", "fixmap_history", "fixmap_contracts", "fixmap_supply_chain", "fixmap_runtime", "fixmap_verify", "fixmap_explain", "fixmap_compare", "fixmap_doctor", "fixmap_annotate" ]); const plan = tools.tools.find((tool) => tool.name === "fixmap_plan"); const verify = tools.tools.find((tool) => tool.name === "fixmap_verify"); @@ -653,6 +653,73 @@ describe("fixmap mcp server", () => { expect(comparison.drift.addedEdges).toContainEqual({ from: "a.ts", to: "b.ts" }); }, 20_000); + it("lists and diffs contracts through a read-only MCP tool without checkout", async () => { + const root = await mkdtemp(join(tmpdir(), "fixmap-mcp-contracts-")); + const git = async (...args: string[]) => (await promisify(execFile)("git", args, { cwd: root })).stdout; + try { + await git("init", "--quiet"); + await git("config", "user.email", "fixmap@example.test"); + await git("config", "user.name", "FixMap Test"); + await writeFile(join(root, "openapi.yaml"), "openapi: 3.1.0\npaths:\n /users:\n get: {}\n post: {}\n", "utf8"); + await git("add", "-A"); + await git("commit", "--quiet", "-m", "before"); + const before = (await git("rev-parse", "HEAD")).trim(); + await writeFile(join(root, "openapi.yaml"), "openapi: 3.1.0\npaths:\n /users:\n post: {}\n /health:\n get: {}\n", "utf8"); + await git("add", "-A"); + await git("commit", "--quiet", "-m", "after"); + const after = (await git("rev-parse", "HEAD")).trim(); + const statusBefore = await git("status", "--porcelain=v1"); + + const client = await connectClient(); + const tool = (await client.listTools()).tools.find((candidate) => candidate.name === "fixmap_contracts"); + expect(tool?.annotations).toMatchObject({ readOnlyHint: true, destructiveHint: false }); + expect(Object.keys(tool?.inputSchema.properties ?? {}).sort()).toEqual(["action", "format", "from", "repo", "to"]); + expect(tool?.inputSchema.additionalProperties).toBe(false); + + const listed = await client.callTool({ name: "fixmap_contracts", arguments: { repo: root, format: "JSON" } }); + expect(listed.isError).toBeFalsy(); + const list = JSON.parse((listed.content as Array<{ text: string }>)[0]!.text); + expect(list.inventory.surfaces).toEqual([expect.objectContaining({ kind: "openapi", path: "openapi.yaml", version: "3.1.0" })]); + + const diffed = await client.callTool({ name: "fixmap_contracts", arguments: { action: "diff", repo: root, from: before, to: after, format: "json" } }); + expect(diffed.isError).toBeFalsy(); + const diff = JSON.parse((diffed.content as Array<{ text: string }>)[0]!.text); + expect(diff.from.commit).toBe(before); + expect(diff.comparison.changes).toEqual([ + expect.objectContaining({ entry: "operation:GET /users", compatibility: "breaking" }), + expect.objectContaining({ entry: "operation:GET /health", compatibility: "compatible" }) + ]); + const markdown = await client.callTool({ name: "fixmap_contracts", arguments: { action: "diff", repo: root, from: before, to: after } }); + expect((markdown.content as Array<{ text: string }>)[0]!.text).toMatch(/^# FixMap Contract Diff\n/); + expect(await git("status", "--porcelain=v1")).toBe(statusBefore); + expect((await git("rev-parse", "HEAD")).trim()).toBe(after); + + const missing = await client.callTool({ name: "fixmap_contracts", arguments: { action: "diff", repo: root, from: before, to: "no-such-ref" } }); + expect(missing.isError).toBe(true); + expect((missing.content as Array<{ text: string }>)[0]!.text).toContain("Could not resolve one of the requested Git refs"); + + const invalid: Array<[Record, string]> = [ + [{ action: "remove" }, '"action" must be "list" or "diff"'], + [{ action: "diff", from: before }, 'requires both "from" and "to"'], + [{ from: before, to: after }, 'apply only to action "diff"'], + [{ action: "diff", from: "a..b", to: after }, '"from" must be a bounded single-line Git ref'], + [{ action: "diff", from: "--output=x", to: after }, '"from" must be a bounded single-line Git ref'], + [{ action: "diff", from: before, to: 7 }, '"to" must be a bounded single-line Git ref'], + [{ repo: "https://example.com/repo.git" }, '"repo" must be a local checkout'], + [{ repo: "" }, '"repo" must be a non-empty local path'], + [{ format: "xml" }, '"format" must be either'], + [{ noCache: true }, "unknown argument: noCache"] + ]; + for (const [args, expected] of invalid) { + const result = await client.callTool({ name: "fixmap_contracts", arguments: args }); + expect(result.isError).toBe(true); + expect((result.content as Array<{ text: string }>)[0]!.text).toContain(expected); + } + } finally { + await rm(root, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }); + } + }, 30_000); + it("imports normalized supply-chain evidence through MCP", async () => { const client = await connectClient(); const result = await client.callTool({ diff --git a/packages/core/src/architecture-history.ts b/packages/core/src/architecture-history.ts index 2fa9726..d9fbb6e 100644 --- a/packages/core/src/architecture-history.ts +++ b/packages/core/src/architecture-history.ts @@ -15,7 +15,7 @@ const MAX_TEXT_SAMPLE_BYTES = 64_000; const MAX_BATCH_BYTES = 64 * 1024 * 1024; const MAX_BATCH_OUTPUT_BYTES = MAX_BATCH_BYTES + 2 * 1024 * 1024; -type TreeEntry = { mode: string; oid: string; size: number; path: string }; +export type TreeEntry = { mode: string; oid: string; size: number; path: string }; export type HistoricalRepoMap = { requestedRef: string; @@ -120,13 +120,13 @@ export async function compareArchitectureRefs(input: { }; } -function validateRef(value: string): string { +export function validateRef(value: string): string { const ref = value.trim(); if (!ref || ref.length > MAX_REF_LENGTH || /[\0\r\n]/.test(ref)) throw new Error("Git ref must be a bounded single-line value."); return ref; } -async function resolveCommit(repoRoot: string, ref: string): Promise { +export async function resolveCommit(repoRoot: string, ref: string): Promise { try { const { stdout } = await exec("git", ["rev-parse", "--verify", "--end-of-options", `${ref}^{commit}`], { cwd: repoRoot, @@ -141,7 +141,7 @@ async function resolveCommit(repoRoot: string, ref: string): Promise { } } -function parseTree(value: string): TreeEntry[] { +export function parseTree(value: string): TreeEntry[] { return value.split("\0").flatMap((record): TreeEntry[] => { if (!record) return []; const tab = record.indexOf("\t"); @@ -153,7 +153,7 @@ function parseTree(value: string): TreeEntry[] { }); } -async function readBlobs(repoRoot: string, entries: readonly TreeEntry[]): Promise> { +export async function readBlobs(repoRoot: string, entries: readonly TreeEntry[]): Promise> { if (entries.length === 0) return new Map(); const uniqueOids = [...new Set(entries.map((entry) => entry.oid))]; const child = spawn("git", ["cat-file", "--batch"], { cwd: repoRoot, stdio: ["pipe", "pipe", "pipe"], windowsHide: true }); diff --git a/packages/core/src/artifacts.ts b/packages/core/src/artifacts.ts index 9b20a60..1df5aec 100644 --- a/packages/core/src/artifacts.ts +++ b/packages/core/src/artifacts.ts @@ -11,6 +11,10 @@ export type FixMapArtifactKind = | "change-scope-json" | "change-scope-markdown" | "context-json" + | "contract-diff-json" + | "contract-diff-markdown" + | "contract-list-json" + | "contract-list-markdown" | "context-markdown" | "report-json" | "report-markdown" @@ -60,6 +64,10 @@ export function fixMapArtifactKind(file: Pick { + const root = await realpath(resolve(repo.root)); + const sources: ContractSource[] = []; + const diagnostics: ContractDiagnostic[] = []; + let totalBytes = 0; + for (const file of repo.files) { + const byPath = CONTRACT_PATH.test(file.path); + if (!byPath && !(STRUCTURED_EXTENSION.test(file.path) && isContractCandidate(file.path, file.textSample))) continue; + const absolute = resolve(root, file.path); + const inside = relative(root, absolute); + if (!inside || inside.startsWith(`..${sep}`) || inside === "..") continue; + let bytes: Buffer | undefined; + try { + const info = await lstat(absolute); + if (info.isFile() && info.size <= MAX_CONTRACT_BYTES && totalBytes + info.size <= MAX_TOTAL_BYTES) { + bytes = await readFile(absolute); + totalBytes += bytes.length; + } + } catch { + bytes = undefined; + } + const decoded = bytes ? decodeUtf8(bytes) : undefined; + if (bytes === undefined || decoded === undefined || bytes.length > MAX_CONTRACT_BYTES) { + diagnostics.push(unread(file.path)); + continue; + } + if (!byPath && !isContractCandidate(file.path, decoded)) continue; + sources.push({ path: file.path, content: decoded, fingerprint: `worktree:${createHash("sha256").update(bytes).digest("hex")}` }); + } + return inventoryContracts(sources, diagnostics); +} + +/** Inventories contracts at one exact commit through Git objects, without checkout. */ +export async function inventoryContractsAtRef(input: { repoRoot: string; ref: string }): Promise { + const repoRoot = resolve(input.repoRoot); + const requestedRef = validateRef(input.ref); + const commit = await resolveCommit(repoRoot, requestedRef); + const { stdout } = await exec("git", ["ls-tree", "-r", "-z", "-l", "--full-tree", commit, "--"], { + cwd: repoRoot, + encoding: "utf8", + maxBuffer: MAX_TREE_BYTES + }); + const candidates = parseTree(stdout) + .filter((entry) => entry.mode !== "120000" && entry.mode !== "160000") + .filter((entry) => CONTRACT_PATH.test(entry.path) || STRUCTURED_EXTENSION.test(entry.path)); + const diagnostics: ContractDiagnostic[] = []; + const readable: TreeEntry[] = []; + let totalBytes = 0; + for (const entry of candidates) { + if (entry.size <= MAX_CONTRACT_BYTES && totalBytes + entry.size <= MAX_TOTAL_BYTES) { + readable.push(entry); + totalBytes += entry.size; + } else if (CONTRACT_PATH.test(entry.path)) { + diagnostics.push(unread(entry.path)); + } + } + const blobs = await readBlobs(repoRoot, readable); + const sources: ContractSource[] = []; + for (const entry of readable) { + const byPath = CONTRACT_PATH.test(entry.path); + const content = decodeUtf8(blobs.get(entry.oid)); + if (content === undefined) { + if (byPath) diagnostics.push(unread(entry.path)); + continue; + } + if (!byPath && !isContractCandidate(entry.path, content)) continue; + sources.push({ path: entry.path, content, fingerprint: `git:${entry.oid}` }); + } + return { requestedRef, commit, inventory: inventoryContracts(sources, diagnostics) }; +} + +/** Compares contract surfaces at two exact commits. Neither ref is checked out. */ +export async function compareContractRefs(input: { repoRoot: string; fromRef: string; toRef: string }): Promise { + const [from, to] = await Promise.all([ + inventoryContractsAtRef({ repoRoot: input.repoRoot, ref: input.fromRef }), + inventoryContractsAtRef({ repoRoot: input.repoRoot, ref: input.toRef }) + ]); + return { + contractDiffVersion: 1, + from: { requestedRef: from.requestedRef, commit: from.commit }, + to: { requestedRef: to.requestedRef, commit: to.commit }, + comparison: compareContractInventories(from.inventory, to.inventory) + }; +} + +function decodeUtf8(bytes: Buffer | undefined): string | undefined { + if (!bytes) return undefined; + try { + return new TextDecoder("utf-8", { fatal: true }).decode(bytes); + } catch { + return undefined; + } +} + +function unread(path: string): ContractDiagnostic { + return { + code: "contract-source-incomplete", + severity: "warning", + path, + message: `${path} looks like a contract, but it is larger than ${MAX_CONTRACT_BYTES / 1024 / 1024} MB, not UTF-8 text, or unreadable, so FixMap did not parse it.` + }; +} diff --git a/packages/core/src/contracts.ts b/packages/core/src/contracts.ts index ad35e06..91c8e7b 100644 --- a/packages/core/src/contracts.ts +++ b/packages/core/src/contracts.ts @@ -2,6 +2,7 @@ import type { RepoMap } from "./types.js"; import { createGraphIdentity } from "./identity-graph.js"; import type { IdentityGraphNode } from "./identity-graph.js"; import { markdownCode } from "./markdown.js"; +import { parseYamlSubset, YamlSubsetError } from "./yaml-subset.js"; export type ContractKind = "openapi" | "asyncapi" | "graphql" | "protobuf" | "json-schema" | "migration"; export type ContractEntryRole = "operation" | "type" | "field" | "argument" | "required-field" | "migration"; @@ -24,6 +25,8 @@ export type ContractSurface = { kind: ContractKind; path: string; name: string; + /** Declared specification or syntax version (for example OpenAPI 3.1.0 or proto3), when the source states one. */ + version?: string; sourceFingerprint: string; entries: ContractEntry[]; }; @@ -48,7 +51,7 @@ export type ContractChange = { contractId: string; contractKind: ContractKind; path: string; - change: "contract-added" | "contract-removed" | "entry-added" | "entry-removed" | "entry-changed"; + change: "contract-added" | "contract-removed" | "contract-unavailable" | "entry-added" | "entry-removed" | "entry-changed"; compatibility: ContractCompatibility; reason: string; entry?: string; @@ -75,14 +78,16 @@ export type ContractGraphOptions = { }; const HTTP_METHODS = new Set(["get", "put", "post", "delete", "options", "head", "patch", "trace"]); -const CONTRACT_PATH = /(?:^|\/)(?:openapi|swagger|asyncapi)(?:\.[^/]+)?\.(?:json|ya?ml)$|\.(?:graphql|gql|proto)$|(?:^|\/)migrations?\/.*\.sql$|\.schema\.json$/i; +export const CONTRACT_PATH = /(?:^|\/)(?:openapi|swagger|asyncapi)(?:\.[^/]+)?\.(?:json|ya?ml)$|\.(?:graphql|gql|proto)$|(?:^|\/)migrations?\/.*\.sql$|\.schema\.json$/i; /** Converts a scanned repository into bounded contract sources without pretending omitted content was parsed. */ export function contractSourcesFromRepo(repo: RepoMap): { sources: ContractSource[]; diagnostics: ContractDiagnostic[] } { const sources: ContractSource[] = []; const diagnostics: ContractDiagnostic[] = []; for (const file of repo.files.filter((candidate) => isContractCandidate(candidate.path, candidate.textSample))) { - if (file.textSampleComplete === false || !file.contentFingerprint) { + // Files outside the scanner's text extensions (GraphQL, Protobuf, SQL) carry an empty + // sample; parsing that would report an empty surface instead of an unread one. + if (file.textSampleComplete === false || !file.contentFingerprint || !file.isSource) { diagnostics.push({ code: "contract-source-incomplete", severity: "warning", @@ -135,7 +140,11 @@ export function compareContractInventories( for (const [id, before] of beforeById) { const after = afterById.get(id); if (!after) { - if (unavailableAfter.has(before.path)) continue; + if (unavailableAfter.has(before.path)) { + changes.push(contractChange(before, undefined, "contract-unavailable", "unknown", + `${before.kind} contract ${before.name} could not be read on the later side, so its compatibility is unknown.`)); + continue; + } changes.push(contractChange(before, undefined, "contract-removed", "breaking", `Removed ${before.kind} contract ${before.name}.`)); continue; } @@ -143,7 +152,11 @@ export function compareContractInventories( } for (const [id, after] of afterById) { if (!beforeById.has(id)) { - if (unavailableBefore.has(after.path)) continue; + if (unavailableBefore.has(after.path)) { + changes.push(contractChange(undefined, after, "contract-unavailable", "unknown", + `${after.kind} contract ${after.name} could not be read on the earlier side, so its compatibility is unknown.`)); + continue; + } changes.push(contractChange(undefined, after, "contract-added", "compatible", `Added ${after.kind} contract ${after.name}.`)); } } @@ -298,17 +311,34 @@ function parseContract(source: ContractSource): { surface?: ContractSurface; dia } return parsed(source, "graphql", graphql); } - if (lower.endsWith(".proto")) return parsed(source, "protobuf", parseProtobuf(source.content)); + if (lower.endsWith(".proto")) { + const syntax = /^\s*(?:syntax|edition)\s*=\s*["']([^"']+)["']/m.exec(source.content.replace(/\/\/[^\r\n]*/g, ""))?.[1]; + return parsed(source, "protobuf", { ...parseProtobuf(source.content), ...(syntax ? { version: syntax } : {}) }); + } if (/(?:^|\/)migrations?\/.*\.sql$/i.test(source.path)) return parsed(source, "migration", parseMigration(source.content)); const json = parseJson(source.content); - if (json) { - if (typeof json.openapi === "string" || typeof json.swagger === "string") return parsed(source, "openapi", parseOpenApiJson(json)); - if (typeof json.asyncapi === "string") return parsed(source, "asyncapi", parseAsyncApiJson(json)); - if (typeof json.$schema === "string" || isRecord(json.properties)) return parsed(source, "json-schema", parseJsonSchema(json)); + if (json) return parsedStructured(source, json); + const yamlLike = /\.ya?ml$/i.test(source.path) || /^\s*(?:openapi|swagger|asyncapi)\s*:/m.test(source.content); + if (yamlLike) { + let document: unknown; + try { + document = parseYamlSubset(source.content); + } catch (error) { + if (!(error instanceof YamlSubsetError)) throw error; + return parseFailed(source, `YAML ${error.message}.`); + } + if (isRecord(document)) { + // YAML reads an unquoted "3.0" as a number; keep the version text the author wrote. + for (const key of ["openapi", "swagger", "asyncapi"]) { + if (typeof document[key] !== "number") continue; + const written = new RegExp(`^${key}\\s*:\\s*([^\\s#]+)`, "m").exec(source.content)?.[1]; + if (written) document[key] = written; + } + const structured = parsedStructured(source, document); + if (structured.surface || structured.diagnostic) return structured; + } } - if (/^\s*(?:openapi|swagger)\s*:/m.test(source.content)) return parsed(source, "openapi", parseOpenApiYaml(source.content)); - if (/^\s*asyncapi\s*:/m.test(source.content)) return parsed(source, "asyncapi", parseAsyncApiYaml(source.content)); if (CONTRACT_PATH.test(source.path)) { return { diagnostic: { @@ -322,6 +352,30 @@ function parseContract(source: ContractSource): { surface?: ContractSurface; dia return {}; } +/** JSON and YAML documents share one decoder, so both spellings produce identical surfaces. */ +function parsedStructured(source: ContractSource, document: Record): { surface?: ContractSurface; diagnostic?: ContractDiagnostic } { + const openapi = specVersion(document.openapi) ?? specVersion(document.swagger); + if (openapi) return parsed(source, "openapi", { ...parseOpenApiJson(document), version: openapi }); + const asyncapi = specVersion(document.asyncapi); + if (asyncapi) return parsed(source, "asyncapi", { ...parseAsyncApiJson(document), version: asyncapi }); + if (typeof document.$schema === "string" || isRecord(document.properties)) { + return parsed(source, "json-schema", { + ...parseJsonSchema(document), + ...(typeof document.$schema === "string" ? { version: document.$schema } : {}) + }); + } + if (CONTRACT_PATH.test(source.path)) { + return parseFailed(source, "the document has no openapi, swagger, asyncapi, $schema, or properties marker."); + } + return {}; +} + +function specVersion(value: unknown): string | undefined { + if (typeof value === "string" && value.trim()) return value.trim(); + if (typeof value === "number" && Number.isFinite(value)) return String(value); + return undefined; +} + function parseFailed(source: ContractSource, detail: string): { diagnostic: ContractDiagnostic } { return { diagnostic: { @@ -333,13 +387,14 @@ function parseFailed(source: ContractSource, detail: string): { diagnostic: Cont }; } -function parsed(source: ContractSource, kind: ContractKind, parsedSurface: { name?: string; entries: ContractEntry[] }): { surface: ContractSurface } { +function parsed(source: ContractSource, kind: ContractKind, parsedSurface: { name?: string; version?: string; entries: ContractEntry[] }): { surface: ContractSurface } { return { surface: { id: `contract:${kind}:${source.path.replace(/\\/g, "/")}`, kind, path: source.path.replace(/\\/g, "/"), name: parsedSurface.name ?? source.path.split(/[\\/]/).at(-1) ?? source.path, + ...(parsedSurface.version ? { version: parsedSurface.version } : {}), sourceFingerprint: source.fingerprint, entries: normalizeEntries(parsedSurface.entries) } @@ -480,49 +535,6 @@ function parseMigration(content: string): { entries: ContractEntry[] } { return { entries }; } -function parseOpenApiYaml(content: string): { name?: string; entries: ContractEntry[] } { - return parseChannelYaml(content, "paths", HTTP_METHODS); -} - -function parseAsyncApiYaml(content: string): { name?: string; entries: ContractEntry[] } { - return parseChannelYaml(content, "channels", new Set(["publish", "subscribe"])); -} - -function parseChannelYaml(content: string, sectionName: string, operations: Set): { name?: string; entries: ContractEntry[] } { - const entries: ContractEntry[] = []; - const lines = content.split(/\r?\n/); - let inSection = false; - let sectionIndent = -1; - let currentPath: string | undefined; - let pathIndent = -1; - for (const raw of lines) { - const withoutComment = raw.replace(/\s+#.*$/, ""); - const trimmed = withoutComment.trim(); - if (!trimmed) continue; - const indent = withoutComment.length - withoutComment.trimStart().length; - if (!inSection && trimmed === `${sectionName}:`) { - inSection = true; - sectionIndent = indent; - continue; - } - if (!inSection) continue; - if (indent <= sectionIndent) break; - const key = /^([^:]+):\s*$/.exec(trimmed)?.[1]?.trim(); - if (!key) continue; - if (indent > sectionIndent && (currentPath === undefined || indent <= pathIndent)) { - currentPath = unquote(key); - pathIndent = indent; - continue; - } - if (currentPath && indent > pathIndent && operations.has(key.toLowerCase())) { - const operation = sectionName === "paths" ? `${key.toUpperCase()} ${currentPath}` : `${key.toLowerCase()} ${currentPath}`; - entries.push(entry(`operation:${sectionName === "paths" ? operation : `${key.toLowerCase()}:${currentPath}`}`, "operation", operation)); - } - } - const title = content.match(/^\s*title\s*:\s*["']?([^\r\n"']+)/m)?.[1]?.trim(); - return { ...(title ? { name: title } : {}), entries }; -} - function entry(key: string, role: ContractEntryRole, signature: string, required = false): ContractEntry { return { key, role, signature: signature.trim(), required }; } @@ -572,7 +584,7 @@ function validateContractSource(source: ContractSource): void { } } -function isContractCandidate(path: string, content: string): boolean { +export function isContractCandidate(path: string, content: string): boolean { return CONTRACT_PATH.test(path.replace(/\\/g, "/")) || /^\s*(?:openapi|swagger|asyncapi)\s*:/m.test(content) || /^\s*\{[\s\S]*?"(?:openapi|swagger|asyncapi|\$schema)"\s*:/m.test(content); @@ -608,10 +620,6 @@ function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } -function unquote(value: string): string { - return value.replace(/^["']|["']$/g, ""); -} - function severityOrder(value: ContractCompatibility): number { return value === "breaking" ? 0 : value === "unknown" ? 1 : 2; } diff --git a/packages/core/src/feature-catalog.ts b/packages/core/src/feature-catalog.ts index afdea7f..b4a9b87 100644 --- a/packages/core/src/feature-catalog.ts +++ b/packages/core/src/feature-catalog.ts @@ -22,6 +22,7 @@ export const FIXMAP_FEATURES: readonly FixMapFeature[] = [ { name: "Migration planning", preview: true, command: "fixmap migrate --input ", detail: "Validate an exact identity graph and explicit steps, then order compatibility windows, tests, rollback points, and blast radius without applying changes." }, { name: "Reverse documentation", preview: true, command: "fixmap reverse-docs --input ", detail: "Draft review-only module or architecture Markdown from exact file fingerprints, structural edges, and authored decisions without writing repository files." }, { name: "Architecture history", preview: true, command: "fixmap history --repo . --from --to ", detail: "Compare exact committed architecture snapshots without checking out either ref or changing the worktree." }, + { name: "Contract Guardian", preview: true, command: "fixmap contracts diff ..", detail: "List OpenAPI, AsyncAPI, GraphQL, Protobuf, JSON Schema, and SQL migration contracts, or classify their changes between two exact Git refs as breaking, unknown, or compatible with before/after fingerprints, without checkout." }, { name: "Supply-chain evidence", preview: true, command: "fixmap supply-chain --input ", detail: "Validate normalized external scanner or SBOM evidence with exact tool, database, document, advisory, version, and license provenance." }, { name: "Runtime evidence", preview: true, command: "fixmap runtime --input ", detail: "Map redaction-reviewed OpenTelemetry, APM, Speedscope, or pprof observations only through exact repository paths and file fingerprints." }, { name: "Evidence import", preview: true, command: "fixmap plan --evidence ", detail: "Attach findings from other tools (scanners, CI, runtime monitors) to the files in a plan from a version-1 data-only bundle; claims are shown as supplied and never executed." }, @@ -31,7 +32,7 @@ export const FIXMAP_FEATURES: readonly FixMapFeature[] = [ { name: "Verify", command: "fixmap verify --report ", detail: "Compare the completed diff or working tree with the saved plan; add --fail-on warning for a strict CI gate." }, { name: "Validate", command: "fixmap validate ", detail: "Check a saved report against FixMap's structural compatibility contract." }, { name: "Doctor", command: "fixmap doctor", detail: "Diagnose stale local, global, PATH, and npx install shadows." }, - { name: "MCP", command: "fixmap mcp", detail: "Expose Plan, Context, Graph, Change Scope, Capability maps, Workspace, Ask, Migrate, Reverse Docs, History, Supply Chain, Runtime, Explain, Compare, Verify, and Doctor over local stdio." }, + { name: "MCP", command: "fixmap mcp", detail: "Expose Plan, Context, Graph, Change Scope, Capability maps, Workspace, Ask, Migrate, Reverse Docs, History, Contracts, Supply Chain, Runtime, Explain, Compare, Verify, and Doctor over local stdio." }, { name: "Public tasks", command: "fixmap owner/repository#123", detail: "Fetch public GitHub issue or pull-request text anonymously and scan its repository in an isolated checkout." }, { name: "Repository sources", command: "--repo --ref ", detail: "Map a local checkout, file URL, directory archive, or a named branch or tag from a public GitHub repository." }, { name: "Task files", command: "--issue-file ", detail: "Read long task text from UTF-8, UTF-16, or stdin, including BOM-less UTF-16 from common Windows tools." }, diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index a7cd0cd..43fd941 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -270,6 +270,8 @@ export type { ContractSource, ContractSurface } from "./contracts.js"; +export { compareContractRefs, inventoryContractsAtRef, inventoryWorkingTreeContracts } from "./contracts-repository.js"; +export type { ContractInventoryAtRef, ContractRefComparison } from "./contracts-repository.js"; export type { FixMapInput, FixMapReport, diff --git a/packages/core/src/yaml-subset.ts b/packages/core/src/yaml-subset.ts new file mode 100644 index 0000000..6537b25 --- /dev/null +++ b/packages/core/src/yaml-subset.ts @@ -0,0 +1,381 @@ +/** + * A bounded reader for the block-YAML subset that OpenAPI and AsyncAPI documents use: + * mappings, sequences, plain/quoted scalars, literal and folded block scalars, and simple + * flow collections. Anchors, aliases, tags, merge keys, and multiple documents are refused + * rather than guessed, so callers can report the document as unparseable instead of + * producing a surface that silently differs from the author's intent. + */ + +export type YamlValue = string | number | boolean | null | YamlValue[] | { [key: string]: YamlValue }; + +export class YamlSubsetError extends Error {} + +type Line = { number: number; indent: number; text: string; raw: string }; + +const MAX_DEPTH = 64; + +export function parseYamlSubset(content: string): YamlValue { + const lines = toLines(content); + if (lines.length === 0) return null; + const state = { lines, index: 0 }; + const value = parseNode(state, lines[0]!.indent, 0); + if (state.index < lines.length) fail(lines[state.index]!, "unexpected content after the document"); + return value; +} + +function toLines(content: string): Line[] { + const rawLines = content.replace(/^\uFEFF/, "").split(/\r?\n/); + const lines: Line[] = []; + let started = false; + for (let index = 0; index < rawLines.length; index += 1) { + const raw = rawLines[index]!; + if (/^%/.test(raw) && !started) continue; + if (/^---(?:\s|$)/.test(raw)) { + if (started || lines.length > 0) throw new YamlSubsetError(`line ${index + 1}: multiple YAML documents are not supported`); + started = true; + if (raw.slice(3).trim() && !raw.slice(3).trim().startsWith("#")) { + throw new YamlSubsetError(`line ${index + 1}: content on the document marker is not supported`); + } + continue; + } + if (/^\.\.\.(?:\s|$)/.test(raw)) { + if (rawLines.slice(index + 1).some((rest) => rest.trim() && !rest.trim().startsWith("#"))) { + throw new YamlSubsetError(`line ${index + 1}: multiple YAML documents are not supported`); + } + break; + } + const leading = /^[ \t]*/.exec(raw)![0]; + const text = stripComment(raw.slice(leading.length)).trimEnd(); + if (!text) { + lines.push({ number: index + 1, indent: -1, text: "", raw }); + continue; + } + if (leading.includes("\t")) throw new YamlSubsetError(`line ${index + 1}: tab indentation is not supported`); + lines.push({ number: index + 1, indent: leading.length, text, raw }); + } + return lines; +} + +function stripComment(text: string): string { + if (text.startsWith("#")) return ""; + let quote: string | undefined; + for (let index = 0; index < text.length; index += 1) { + const char = text[index]!; + if (quote) { + if (quote === "\"" && char === "\\") index += 1; + else if (char === quote) quote = undefined; + continue; + } + if ((char === "\"" || char === "'") && (index === 0 || /[\s:\[\]{},-]/.test(text[index - 1]!))) quote = char; + else if (char === "#" && /\s/.test(text[index - 1] ?? "")) return text.slice(0, index); + } + return text; +} + +type State = { lines: Line[]; index: number }; + +function current(state: State): Line | undefined { + while (state.index < state.lines.length && state.lines[state.index]!.indent < 0) state.index += 1; + return state.lines[state.index]; +} + +function parseNode(state: State, indent: number, depth: number): YamlValue { + if (depth > MAX_DEPTH) throw new YamlSubsetError("YAML nesting is deeper than FixMap reads"); + const line = current(state); + if (!line || line.indent < indent) return null; + if (isSequenceItem(line.text)) return parseSequence(state, line.indent, depth); + if (splitKey(line.text)) return parseMapping(state, line.indent, depth); + state.index += 1; + return parseInlineValue(line, line.text, state, line.indent, depth); +} + +function isSequenceItem(text: string): boolean { + return text === "-" || text.startsWith("- "); +} + +function parseSequence(state: State, indent: number, depth: number): YamlValue[] { + const values: YamlValue[] = []; + for (let line = current(state); line && line.indent === indent && isSequenceItem(line.text); line = current(state)) { + const rest = line.text.slice(1).trimStart(); + if (!rest) { + state.index += 1; + const next = current(state); + values.push(next && next.indent > indent ? parseNode(state, next.indent, depth + 1) : null); + continue; + } + // "- key: value" opens a mapping whose items align with the first key. + const column = indent + (line.text.length - rest.length); + state.lines[state.index] = { ...line, indent: column, text: rest }; + if (isSequenceItem(rest) || splitKey(rest)) values.push(parseNode(state, column, depth + 1)); + else { + state.index += 1; + values.push(parseInlineValue(line, rest, state, indent, depth)); + } + } + const after = current(state); + if (after && after.indent > indent) fail(after, "unexpected indentation in a sequence"); + return values; +} + +function parseMapping(state: State, indent: number, depth: number): { [key: string]: YamlValue } { + const result: { [key: string]: YamlValue } = {}; + for (let line = current(state); line && line.indent === indent; line = current(state)) { + const split = splitKey(line.text); + if (!split) fail(line, "expected a mapping key"); + const key = parseKey(line, split.key); + if (key === "<<") fail(line, "merge keys are not supported"); + if (Object.prototype.hasOwnProperty.call(result, key)) fail(line, `duplicate key ${JSON.stringify(key)}`); + state.index += 1; + if (!split.value) { + const next = current(state); + if (next && (next.indent > indent || (next.indent === indent && isSequenceItem(next.text)))) { + result[key] = parseNode(state, next.indent, depth + 1); + } else { + result[key] = null; + } + } else { + result[key] = parseInlineValue(line, split.value, state, indent, depth); + } + } + const after = current(state); + if (after && after.indent > indent) fail(after, "unexpected indentation in a mapping"); + return result; +} + +/** Finds the key/value separator: a colon followed by whitespace or end of line, outside quotes and flow. */ +function splitKey(text: string): { key: string; value: string } | undefined { + if (isSequenceItem(text) || text.startsWith("{") || text.startsWith("[")) return undefined; + let index = 0; + if (text.startsWith("\"") || text.startsWith("'")) { + const end = closingQuote(text, 0); + if (end === -1) return undefined; + index = end + 1; + const rest = text.slice(index); + const match = /^\s*:(?:\s|$)/.exec(rest); + if (!match) return undefined; + return { key: text.slice(0, index), value: rest.slice(match[0].length).trim() }; + } + for (; index < text.length; index += 1) { + if (text[index] === ":" && (index + 1 === text.length || /\s/.test(text[index + 1]!))) { + return { key: text.slice(0, index).trimEnd(), value: text.slice(index + 1).trim() }; + } + } + return undefined; +} + +function parseKey(line: Line, raw: string): string { + if (raw.startsWith("? ")) fail(line, "complex mapping keys are not supported"); + if (raw.startsWith("\"") || raw.startsWith("'")) return parseQuoted(line, raw); + if (/^[&*!]/.test(raw)) fail(line, "anchors, aliases, and tags are not supported"); + return raw; +} + +function parseInlineValue(line: Line, value: string, state: State, parentIndent: number, depth: number): YamlValue { + if (/^[&*!]/.test(value)) fail(line, "anchors, aliases, and tags are not supported"); + if (/^[|>]/.test(value)) return parseBlockScalar(line, value, state, parentIndent); + if (value.startsWith("{") || value.startsWith("[")) { + let text = value; + // A flow collection may wrap onto more-indented lines. + while (!flowBalanced(text)) { + const next = current(state); + if (!next || next.indent <= parentIndent) fail(line, "unterminated flow collection"); + text += ` ${next.text}`; + state.index += 1; + } + const parser = { text, index: 0, line }; + const result = parseFlowValue(parser, depth); + skipSpace(parser); + if (parser.index !== text.length) fail(line, "unexpected content after a flow collection"); + return result; + } + if (value.startsWith("\"") || value.startsWith("'")) { + let text = value; + while (closingQuote(text, 0) === -1) { + const next = current(state); + if (!next) fail(line, "unterminated quoted scalar"); + text += ` ${next.raw.trim()}`; + state.index += 1; + } + const end = closingQuote(text, 0); + if (text.slice(end + 1).trim()) fail(line, "unexpected content after a quoted scalar"); + return parseQuoted(line, text); + } + // Plain scalars may continue onto more-indented lines; YAML folds them with spaces. + let text = value; + for (let next = current(state); next && next.indent > parentIndent; next = current(state)) { + if (splitKey(next.text) || isSequenceItem(next.text)) fail(next, "a scalar value cannot also open a nested block"); + text += ` ${next.text}`; + state.index += 1; + } + return resolvePlain(text); +} + +function parseBlockScalar(line: Line, header: string, state: State, parentIndent: number): string { + const match = /^([|>])([+-]?)(\d?)([+-]?)$/.exec(header.trim()); + if (!match) fail(line, "unsupported block scalar header"); + const folded = match[1] === ">"; + const chomping = match[2] || match[4]; + const explicit = match[3] ? Number(match[3]) : undefined; + const collected: string[] = []; + let contentIndent = explicit !== undefined ? parentIndent + explicit : undefined; + while (state.index < state.lines.length) { + const next = state.lines[state.index]!; + // Block scalars keep "#" text, so read raw lines instead of comment-stripped ones. + const blank = next.raw.trim() === ""; + const leading = /^ */.exec(next.raw)![0].length; + if (!blank && leading <= parentIndent) break; + if (!blank) { + contentIndent ??= leading; + if (leading < contentIndent) fail(next, "block scalar line is less indented than its first line"); + } + collected.push(blank ? "" : next.raw.slice(contentIndent!)); + state.index += 1; + } + while (collected.length > 0 && collected.at(-1) === "" && chomping !== "+") collected.pop(); + let text = folded ? foldLines(collected) : collected.join("\n"); + if (chomping !== "-" && collected.length > 0) text += "\n"; + return text; +} + +function foldLines(lines: string[]): string { + let result = ""; + for (let index = 0; index < lines.length; index += 1) { + const line = lines[index]!; + if (index === 0) { result = line; continue; } + const previous = lines[index - 1]!; + if (line === "") result += "\n"; + else if (previous === "" || /^\s/.test(line) || /^\s/.test(previous)) result += (previous === "" ? "" : "\n") + line; + else result += ` ${line}`; + } + return result; +} + +function resolvePlain(text: string): YamlValue { + const value = text.trim(); + if (value === "" || value === "~" || /^(?:null|Null|NULL)$/.test(value)) return null; + if (/^(?:true|True|TRUE)$/.test(value)) return true; + if (/^(?:false|False|FALSE)$/.test(value)) return false; + if (/^[-+]?(?:0|[1-9][0-9]*)$/.test(value)) { + const numeric = Number(value); + return Number.isSafeInteger(numeric) ? numeric : value; + } + if (/^[-+]?(?:[0-9]+\.[0-9]*|\.[0-9]+)(?:[eE][-+]?[0-9]+)?$/.test(value) || /^[-+]?[0-9]+[eE][-+]?[0-9]+$/.test(value)) return Number(value); + return value; +} + +function closingQuote(text: string, start: number): number { + const quote = text[start]; + for (let index = start + 1; index < text.length; index += 1) { + if (quote === "\"" && text[index] === "\\") { index += 1; continue; } + if (text[index] === quote) { + if (quote === "'" && text[index + 1] === "'") { index += 1; continue; } + return index; + } + } + return -1; +} + +function parseQuoted(line: Line, text: string): string { + const end = closingQuote(text, 0); + if (end === -1) fail(line, "unterminated quoted scalar"); + const body = text.slice(1, end); + if (text[0] === "'") return body.replace(/''/g, "'"); + return body.replace(/\\(u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|.)/g, (_, escape: string) => { + if (escape.length > 1) return String.fromCharCode(parseInt(escape.slice(1), 16)); + const simple: Record = { n: "\n", t: "\t", r: "\r", "0": "\0", "\"": "\"", "\\": "\\", "/": "/", " ": " ", b: "\b", f: "\f" }; + if (!(escape in simple)) fail(line, `unsupported escape \\${escape}`); + return simple[escape]!; + }); +} + +type FlowParser = { text: string; index: number; line: Line }; + +function flowBalanced(text: string): boolean { + let depth = 0; + let quote: string | undefined; + for (let index = 0; index < text.length; index += 1) { + const char = text[index]!; + if (quote) { + if (quote === "\"" && char === "\\") index += 1; + else if (char === quote) quote = undefined; + } else if (char === "\"" || char === "'") quote = char; + else if (char === "{" || char === "[") depth += 1; + else if (char === "}" || char === "]") depth -= 1; + } + return depth <= 0 && !quote; +} + +function skipSpace(parser: FlowParser): void { + while (parser.index < parser.text.length && /\s/.test(parser.text[parser.index]!)) parser.index += 1; +} + +function parseFlowValue(parser: FlowParser, depth: number): YamlValue { + if (depth > MAX_DEPTH) throw new YamlSubsetError("YAML nesting is deeper than FixMap reads"); + skipSpace(parser); + const char = parser.text[parser.index]; + if (char === "{") return parseFlowMapping(parser, depth + 1); + if (char === "[") return parseFlowSequence(parser, depth + 1); + if (char === "\"" || char === "'") { + const end = closingQuote(parser.text, parser.index); + if (end === -1) fail(parser.line, "unterminated quoted scalar"); + const value = parseQuoted(parser.line, parser.text.slice(parser.index, end + 1)); + parser.index = end + 1; + return value; + } + if (char !== undefined && /[&*!]/.test(char)) fail(parser.line, "anchors, aliases, and tags are not supported"); + const start = parser.index; + while (parser.index < parser.text.length && !/[,\]}]/.test(parser.text[parser.index]!) && + !(parser.text[parser.index] === ":" && /[\s,\]}]/.test(parser.text[parser.index + 1] ?? " "))) parser.index += 1; + return resolvePlain(parser.text.slice(start, parser.index)); +} + +function parseFlowSequence(parser: FlowParser, depth: number): YamlValue[] { + parser.index += 1; + const values: YamlValue[] = []; + skipSpace(parser); + if (parser.text[parser.index] === "]") { parser.index += 1; return values; } + for (;;) { + values.push(parseFlowValue(parser, depth)); + skipSpace(parser); + const char = parser.text[parser.index]; + parser.index += 1; + if (char === "]") return values; + if (char !== ",") fail(parser.line, "expected , or ] in a flow sequence"); + skipSpace(parser); + if (parser.text[parser.index] === "]") { parser.index += 1; return values; } + } +} + +function parseFlowMapping(parser: FlowParser, depth: number): { [key: string]: YamlValue } { + parser.index += 1; + const result: { [key: string]: YamlValue } = {}; + skipSpace(parser); + if (parser.text[parser.index] === "}") { parser.index += 1; return result; } + for (;;) { + const keyValue = parseFlowValue(parser, depth); + if (keyValue !== null && typeof keyValue === "object") fail(parser.line, "complex mapping keys are not supported"); + const key = keyValue === null ? "" : String(keyValue); + if (key === "<<") fail(parser.line, "merge keys are not supported"); + if (Object.prototype.hasOwnProperty.call(result, key)) fail(parser.line, `duplicate key ${JSON.stringify(key)}`); + skipSpace(parser); + if (parser.text[parser.index] === ":") { + parser.index += 1; + skipSpace(parser); + const next = parser.text[parser.index]; + result[key] = next === "," || next === "}" ? null : parseFlowValue(parser, depth); + } else { + result[key] = null; + } + skipSpace(parser); + const char = parser.text[parser.index]; + parser.index += 1; + if (char === "}") return result; + if (char !== ",") fail(parser.line, "expected , or } in a flow mapping"); + skipSpace(parser); + if (parser.text[parser.index] === "}") { parser.index += 1; return result; } + } +} + +function fail(line: Line, message: string): never { + throw new YamlSubsetError(`line ${line.number}: ${message}`); +} diff --git a/packages/core/test/contracts-repository.test.ts b/packages/core/test/contracts-repository.test.ts new file mode 100644 index 0000000..9089ff2 --- /dev/null +++ b/packages/core/test/contracts-repository.test.ts @@ -0,0 +1,108 @@ +import { execFile } from "node:child_process"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { promisify } from "node:util"; +import { afterEach, describe, expect, it } from "vitest"; +import { contractSourcesFromRepo } from "../src/contracts.js"; +import { compareContractRefs, inventoryContractsAtRef, inventoryWorkingTreeContracts } from "../src/contracts-repository.js"; +import { scanRepo } from "../src/repo-scan.js"; +import { parseYamlSubset, YamlSubsetError } from "../src/yaml-subset.js"; + +const exec = promisify(execFile); +const GIT_TEST_TIMEOUT = process.platform === "win32" ? 60_000 : 20_000; +const roots: string[] = []; + +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }))); +}); + +async function repository(files: Record): Promise { + const root = await mkdtemp(join(tmpdir(), "fixmap-contracts-core-")); + roots.push(root); + await exec("git", ["init", "--quiet"], { cwd: root }); + await exec("git", ["config", "user.email", "fixmap@example.test"], { cwd: root }); + await exec("git", ["config", "user.name", "FixMap Test"], { cwd: root }); + for (const [path, content] of Object.entries(files)) { + await mkdir(dirname(join(root, path)), { recursive: true }); + await writeFile(join(root, path), content); + } + await exec("git", ["add", "-A"], { cwd: root }); + await exec("git", ["commit", "--quiet", "-m", "fixture"], { cwd: root }); + return root; +} + +describe("YAML subset reader", () => { + it("reads block, flow, quoted, and block-scalar values like JSON would", () => { + expect(parseYamlSubset([ + "---", + "a: 1", + "b: '2'", + "c: \"x\\ty\"", + "d: [1, two, {e: true}]", + "f:", + "- g: null", + " h: ~", + "- plain text", + "i: |-", + " line one", + " # kept", + "j: >", + " folded", + " text", + "k: it's fine # comment", + "l: 'it''s'", + "m: a", + " continued", + "" + ].join("\n"))).toEqual({ + a: 1, b: "2", c: "x\ty", d: [1, "two", { e: true }], + f: [{ g: null, h: null }, "plain text"], + i: "line one\n# kept", j: "folded text\n", k: "it's fine", l: "it's", m: "a continued" + }); + }); + + it("refuses constructs it cannot represent faithfully", () => { + for (const content of ["a: &x 1\nb: *x\n", "a: !!str 1\n", "<<: {a: 1}\n", "a: 1\na: 2\n", "a:\n\tb: 1\n", "a: [1, 2\n", "a: 1\n---\nb: 2\n"]) { + expect(() => parseYamlSubset(content)).toThrow(YamlSubsetError); + } + }); +}); + +describe("repository contract sources", () => { + it("reports scanner-unsampled contracts as incomplete instead of empty surfaces", async () => { + const root = await repository({ "schema.graphql": "type Query { ok: Boolean }\n", "user.proto": "message User { string id = 1; }\n" }); + const repo = await scanRepo({ repoRoot: root, useCache: false }); + const discovered = contractSourcesFromRepo(repo); + expect(discovered.sources).toEqual([]); + expect(discovered.diagnostics.map((diagnostic) => diagnostic.path)).toEqual(["schema.graphql", "user.proto"]); + + const inventory = await inventoryWorkingTreeContracts(repo); + expect(inventory.surfaces.map((surface) => [surface.path, surface.entries.length > 0])).toEqual([["schema.graphql", true], ["user.proto", true]]); + }, GIT_TEST_TIMEOUT); + + it("reports oversized or non-UTF-8 contracts as unread on both sides", async () => { + const root = await repository({ + "big.graphql": `type Query { ok: Boolean }\n${"# padding\n".repeat(260_000)}`, + "binary.proto": Buffer.from([0xff, 0xfe, 0x00, 0x01]), + "config.yaml": "name: not a contract\n" + }); + const working = await inventoryWorkingTreeContracts(await scanRepo({ repoRoot: root, useCache: false })); + const atRef = await inventoryContractsAtRef({ repoRoot: root, ref: "HEAD" }); + for (const inventory of [working, atRef.inventory]) { + expect(inventory.surfaces).toEqual([]); + expect(inventory.diagnostics.map((diagnostic) => [diagnostic.path, diagnostic.code])).toEqual([ + ["big.graphql", "contract-source-incomplete"], + ["binary.proto", "contract-source-incomplete"] + ]); + } + }, GIT_TEST_TIMEOUT); + + it("finds content-marked OpenAPI files at a ref and rejects unknown refs", async () => { + const root = await repository({ "specs/users-api.yml": "openapi: 3.0.3\npaths:\n /users:\n get: {}\n" }); + const atRef = await inventoryContractsAtRef({ repoRoot: root, ref: "HEAD" }); + expect(atRef.commit).toMatch(/^[a-f0-9]{40}$/); + expect(atRef.inventory.surfaces).toEqual([expect.objectContaining({ kind: "openapi", path: "specs/users-api.yml", version: "3.0.3" })]); + await expect(compareContractRefs({ repoRoot: root, fromRef: "HEAD", toRef: "missing-ref" })).rejects.toThrow("Could not resolve Git ref"); + }, GIT_TEST_TIMEOUT); +}); diff --git a/packages/core/test/contracts.test.ts b/packages/core/test/contracts.test.ts index 83299f4..2793b23 100644 --- a/packages/core/test/contracts.test.ts +++ b/packages/core/test/contracts.test.ts @@ -196,10 +196,149 @@ describe("Contract Guardian", () => { const previous = inventoryContracts([source("schema.graphql", "type Query { ok: Boolean }", "before")]); const current = inventoryContracts([source("schema.graphql", "this is not GraphQL SDL", "after")]); const result = compareContractInventories(previous, current); - expect(result.changes).toEqual([]); + expect(result.changes).toEqual([expect.objectContaining({ + change: "contract-unavailable", + compatibility: "unknown", + evidence: { beforeFingerprint: "content:before0000000000" } + })]); + expect(result.changes.some((change) => change.change === "contract-removed")).toBe(false); expect(result.diagnostics).toContainEqual(expect.objectContaining({ code: "contract-parse-failed" })); }); + it("produces identical surfaces and deltas for equivalent OpenAPI JSON and YAML", () => { + const beforeJson = { + openapi: "3.1.0", + info: { title: "Users" }, + paths: { + "/users/{id}": { + get: { parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }] }, + delete: {} + } + }, + components: { schemas: { User: { type: "object", required: ["id"], properties: { id: { type: "string" }, email: { type: "string", format: "email" } } } } } + }; + const afterJson = { + openapi: "3.1.0", + info: { title: "Users" }, + paths: { + "/users/{id}": { + get: { parameters: [ + { name: "id", in: "path", required: true, schema: { type: "integer" } }, + { name: "expand", in: "query", required: false, schema: { type: "string" } } + ] } + } + }, + components: { schemas: { User: { type: "object", required: ["id", "email"], properties: { id: { type: "string" }, email: { type: "string", format: "email" } } } } } + }; + const beforeYaml = [ + "# Users API", + "openapi: 3.1.0", + "info:", + " title: Users", + " description: |", + " Multi-line text with a # that is not a comment", + " and: a colon.", + "paths:", + " '/users/{id}':", + " get:", + " parameters:", + " - name: id", + " in: path", + " required: true", + " schema: { type: string }", + " delete: {}", + "components:", + " schemas:", + " User:", + " type: object", + " required: [id]", + " properties:", + " id:", + " type: string # inline comment", + " email:", + " type: string", + " format: email", + "" + ].join("\n"); + const afterYaml = [ + "openapi: \"3.1.0\"", + "info: { title: Users }", + "paths:", + " /users/{id}:", + " get:", + " parameters:", + " - name: id", + " in: path", + " required: true", + " schema:", + " type: integer", + " - {name: expand, in: query, required: false, schema: {type: string}}", + "components:", + " schemas:", + " User:", + " type: object", + " required:", + " - id", + " - email", + " properties:", + " id: { type: string }", + " email: { type: string, format: email }", + "" + ].join("\n"); + const jsonBefore = inventoryContracts([source("api/openapi.json", JSON.stringify(beforeJson), "before")]); + const yamlBefore = inventoryContracts([source("api/openapi.json", beforeYaml, "before")].map((value) => ({ ...value, path: "api/openapi.yaml" }))); + expect(yamlBefore.diagnostics).toEqual([]); + expect(yamlBefore.surfaces[0]).toMatchObject({ kind: "openapi", version: "3.1.0", name: "Users" }); + expect(yamlBefore.surfaces[0]!.entries).toEqual(jsonBefore.surfaces[0]!.entries); + + const strip = (comparison: ReturnType) => + comparison.changes.map(({ compatibility, change, entry, before, after, reason }) => ({ compatibility, change, entry, before, after, reason })); + const jsonDelta = compare("api/openapi.json", JSON.stringify(beforeJson), JSON.stringify(afterJson)); + const yamlDelta = compare("api/openapi.yaml", beforeYaml, afterYaml); + expect(strip(yamlDelta)).toEqual(strip(jsonDelta)); + expect(yamlDelta.changes).toEqual(expect.arrayContaining([ + expect.objectContaining({ entry: "operation:DELETE /users/{id}", compatibility: "breaking" }), + expect.objectContaining({ entry: "argument:GET /users/{id}:path:id", change: "entry-changed", compatibility: "breaking" }), + expect.objectContaining({ entry: "argument:GET /users/{id}:query:expand", compatibility: "compatible" }), + expect.objectContaining({ entry: "field:User.email", compatibility: "breaking" }) + ])); + }); + + it("produces identical AsyncAPI deltas for JSON and YAML", () => { + const before = { asyncapi: "2.6.0", info: { title: "Events" }, channels: { "user.created": { publish: { message: {} } }, "user.deleted": { subscribe: {} } } }; + const after = { asyncapi: "2.6.0", info: { title: "Events" }, channels: { "user.created": { publish: { message: {} } } } }; + const beforeYaml = "asyncapi: 2.6.0\ninfo:\n title: Events\nchannels:\n user.created:\n publish:\n message: {}\n user.deleted:\n subscribe: {}\n"; + const afterYaml = "asyncapi: 2.6.0\ninfo:\n title: Events\nchannels:\n user.created:\n publish:\n message: {}\n"; + const json = compare("asyncapi.json", JSON.stringify(before), JSON.stringify(after)); + const yaml = compare("asyncapi.yml", beforeYaml, afterYaml); + expect(yaml.changes.map((change) => [change.entry, change.compatibility])).toEqual(json.changes.map((change) => [change.entry, change.compatibility])); + expect(yaml.changes).toEqual([expect.objectContaining({ entry: "operation:subscribe:user.deleted", compatibility: "breaking" })]); + }); + + it("reports unsupported or malformed YAML as an unparseable contract instead of guessing", () => { + for (const content of [ + "openapi: 3.1.0\ncomponents:\n schemas:\n Base: &base\n type: object\n User: *base\n", + "openapi: 3.1.0\npaths:\n /a:\n get: {}\n /a:\n post: {}\n", + "openapi: 3.1.0\npaths: {unterminated\n", + "openapi: 3.1.0\n---\nopenapi: 3.0.0\n" + ]) { + const inventory = inventoryContracts([source("openapi.yaml", content, "bad")]); + expect(inventory.surfaces).toEqual([]); + expect(inventory.diagnostics).toEqual([expect.objectContaining({ code: "contract-parse-failed", path: "openapi.yaml" })]); + } + }); + + it("records declared specification versions", () => { + const inventory = inventoryContracts([ + source("a.proto", "syntax = \"proto3\";\nmessage A { string id = 1; }", "a"), + source("openapi.yaml", "openapi: 3.0\npaths: {}\n", "b"), + source("schema.graphql", "type Query { ok: Boolean }", "c") + ]); + expect(inventory.surfaces.map((surface) => [surface.kind, surface.version])).toEqual([ + ["graphql", undefined], ["openapi", "3.0"], ["protobuf", "proto3"] + ]); + }); + it("fails closed on duplicate paths and invalid source paths", () => { const valid = source("schema.graphql", "type Query { ok: Boolean }", "one"); expect(() => inventoryContracts([valid, valid])).toThrow("Duplicate contract source path");