diff --git a/packages/action/dist/index.mjs b/packages/action/dist/index.mjs index c4d2b3d..7270b12 100644 --- a/packages/action/dist/index.mjs +++ b/packages/action/dist/index.mjs @@ -107,6 +107,9 @@ function longestBacktickRun(value) { longest = Math.max(longest, match[0].length); return longest; } +function inlineProse(value) { + return value.replace(/\s+/g, " ").trim(); +} // packages/core/dist/language-adapters.js var IDENTIFIER = "[A-Za-z_$][A-Za-z0-9_$]*"; @@ -115,7 +118,7 @@ var CSHARP_CONTROL_WORDS = /* @__PURE__ */ new Set(["catch", "do", "else", "for" var javascriptAdapter = { id: "javascript-typescript", extensions: [".cjs", ".cts", ".js", ".jsx", ".mjs", ".mts", ".svelte", ".ts", ".tsx", ".vue"], - extractImports(text) { + extractImports(text2) { const patterns2 = [ /\bimport\s+[^'"()]*?from\s*["']([^"'\n]+)["']/g, /\bimport\s*["']([^"'\n]+)["']/g, @@ -123,12 +126,12 @@ var javascriptAdapter = { /\brequire\s*\(\s*["']([^"'\n]+)["']\s*\)/g, /\bimport\s*\(\s*["']([^"'\n]+)["']\s*\)/g ]; - return uniqueImports(patterns2.flatMap((pattern) => [...text.matchAll(pattern)].flatMap((match) => match[1] ? [{ adapter: "javascript-typescript", specifier: match[1], importedNames: [], wildcard: false }] : []))); + return uniqueImports(patterns2.flatMap((pattern) => [...text2.matchAll(pattern)].flatMap((match) => match[1] ? [{ adapter: "javascript-typescript", specifier: match[1], importedNames: [], wildcard: false }] : []))); }, - extractDefinitions(text) { + extractDefinitions(text2) { const definitions = []; const pattern = new RegExp(`(? { - if (text[index2] !== "\r" && text[index2] !== "\n") + if (text2[index2] !== "\r" && text2[index2] !== "\n") output[index2] = " "; }; let index = 0; - while (index < text.length) { - if (text[index] === "#") { - while (index < text.length && text[index] !== "\r" && text[index] !== "\n") + while (index < text2.length) { + if (text2[index] === "#") { + while (index < text2.length && text2[index] !== "\r" && text2[index] !== "\n") hide(index++); continue; } - const quote = text[index]; + const quote = text2[index]; if (quote !== "'" && quote !== '"') { index++; continue; } - const delimiter = text.startsWith(quote.repeat(3), index) ? quote.repeat(3) : quote; - for (let count = 0; count < delimiter.length; count++) + const delimiter = text2.startsWith(quote.repeat(3), index) ? quote.repeat(3) : quote; + for (let count2 = 0; count2 < delimiter.length; count2++) hide(index++); - while (index < text.length) { - if (text[index] === "\\") { + while (index < text2.length) { + if (text2[index] === "\\") { hide(index++); - if (index < text.length) { - const crlf = text[index] === "\r" && text[index + 1] === "\n"; + if (index < text2.length) { + const crlf = text2[index] === "\r" && text2[index + 1] === "\n"; hide(index++); if (crlf) hide(index++); } - } else if (text.startsWith(delimiter, index)) { - for (let count = 0; count < delimiter.length; count++) + } else if (text2.startsWith(delimiter, index)) { + for (let count2 = 0; count2 < delimiter.length; count2++) hide(index++); break; } else { @@ -186,9 +189,9 @@ function maskPythonNonCode(text) { var pythonAdapter = { id: "python", extensions: [".py", ".pyi"], - extractImports(text) { + extractImports(text2) { const imports = []; - const importText = maskPythonNonCode(text); + const importText = maskPythonNonCode(text2); for (const match of importText.matchAll(/^[\t ]*from[\t ]+([.A-Za-z_][.A-Za-z0-9_]*)[\t ]+import[\t ]+(\([^)]*\)|[^\r\n]+)/gm)) { const specifier = match[1]; if (!specifier) @@ -206,9 +209,9 @@ var pythonAdapter = { } return uniqueImports(imports); }, - extractDefinitions(text) { + extractDefinitions(text2) { const definitions = []; - const code = maskPythonNonCode(text); + const code = maskPythonNonCode(text2); for (const match of code.matchAll(/^[\t ]*(?:async[\t ]+)?def[\t ]+([A-Za-z_][A-Za-z0-9_]*)[\t ]*\(/gm)) { if (match[1]) definitions.push({ adapter: "python", name: match[1], kind: "function", offset: match.index }); @@ -226,9 +229,9 @@ var pythonAdapter = { var javaAdapter = { id: "java", extensions: [".java"], - extractImports(text) { + extractImports(text2) { const imports = []; - for (const match of text.matchAll(/^\s*import\s+(static\s+)?([A-Za-z_][A-Za-z0-9_.]*?)(\.\*)?\s*;/gm)) { + for (const match of text2.matchAll(/^\s*import\s+(static\s+)?([A-Za-z_][A-Za-z0-9_.]*?)(\.\*)?\s*;/gm)) { let specifier = match[2]; if (!specifier) continue; @@ -242,9 +245,9 @@ var javaAdapter = { } return uniqueImports(imports); }, - extractDefinitions(text) { + extractDefinitions(text2) { const definitions = []; - for (const match of text.matchAll(/\b(class|interface|enum|record)\s+([A-Za-z_$][A-Za-z0-9_$]*)/g)) { + for (const match of text2.matchAll(/\b(class|interface|enum|record)\s+([A-Za-z_$][A-Za-z0-9_$]*)/g)) { const name = match[2]; if (!name) continue; @@ -256,7 +259,7 @@ var javaAdapter = { }); } const methodPattern = /(?:^|[;{}]\s*)(?:(?:public|protected|private|static|final|abstract|synchronized|native|default|strictfp)\s+)*(?:<[A-Za-z0-9_?,.\s]+>\s*)?(?:[A-Za-z_$][A-Za-z0-9_$<>,.?\[\]]*\s+)?([A-Za-z_$][A-Za-z0-9_$]*)\s*\([^;{}]*\)\s*(?:throws\s+[^{]+)?\{/gm; - for (const match of text.matchAll(methodPattern)) { + for (const match of text2.matchAll(methodPattern)) { const name = match[1]; if (name && !JAVA_CONTROL_WORDS.has(name)) { definitions.push({ adapter: "java", name, kind: "method", offset: match.index }); @@ -271,13 +274,13 @@ var javaAdapter = { var goAdapter = { id: "go", extensions: [".go"], - extractImports(text) { + extractImports(text2) { const imports = []; - for (const match of text.matchAll(/^\s*import\s+(?:[A-Za-z_.][A-Za-z0-9_.]*\s+)?["`]([^"`\n]+)["`]/gm)) { + for (const match of text2.matchAll(/^\s*import\s+(?:[A-Za-z_.][A-Za-z0-9_.]*\s+)?["`]([^"`\n]+)["`]/gm)) { if (match[1]) imports.push({ adapter: "go", specifier: match[1], importedNames: [], wildcard: false }); } - for (const block of text.matchAll(/^\s*import\s*\(([\s\S]*?)^\s*\)/gm)) { + for (const block of text2.matchAll(/^\s*import\s*\(([\s\S]*?)^\s*\)/gm)) { for (const match of (block[1] ?? "").matchAll(/^\s*(?:[A-Za-z_.][A-Za-z0-9_.]*\s+)?["`]([^"`\n]+)["`]/gm)) { if (match[1]) imports.push({ adapter: "go", specifier: match[1], importedNames: [], wildcard: false }); @@ -285,8 +288,8 @@ var goAdapter = { } return uniqueImports(imports); }, - extractDefinitions(text) { - return definitionsFromPatterns("go", text, [ + extractDefinitions(text2) { + return definitionsFromPatterns("go", text2, [ { pattern: /^\s*func\s+(?:\([^)]*\)\s*)?([A-Za-z_][A-Za-z0-9_]*)\s*\(/gm, kind: "function" }, { pattern: /^\s*type\s+([A-Za-z_][A-Za-z0-9_]*)\s+(?:struct|interface)\b/gm, kind: "class" }, { pattern: /^\s*type\s+([A-Za-z_][A-Za-z0-9_]*)\s+(?!(?:struct|interface)\b)/gm, kind: "type" }, @@ -300,29 +303,29 @@ var goAdapter = { var rustAdapter = { id: "rust", extensions: [".rs"], - extractImports(text) { + extractImports(text2) { const imports = []; const pathModules = /* @__PURE__ */ new Set(); - for (const match of text.matchAll(/^\s*#\s*\[\s*path\s*=\s*["']([^"'\n]+)["']\s*\]\s*(?:pub(?:\([^)]*\))?\s+)?mod\s+([A-Za-z_][A-Za-z0-9_]*)\s*;/gm)) { + for (const match of text2.matchAll(/^\s*#\s*\[\s*path\s*=\s*["']([^"'\n]+)["']\s*\]\s*(?:pub(?:\([^)]*\))?\s+)?mod\s+([A-Za-z_][A-Za-z0-9_]*)\s*;/gm)) { if (match[1] && match[2]) { pathModules.add(match[2]); imports.push({ adapter: "rust", specifier: `file:${match[1]}`, importedNames: [], wildcard: false }); } } - for (const match of text.matchAll(/^\s*(?:pub(?:\([^)]*\))?\s+)?use\s+([^;\n]+)\s*;/gm)) { + for (const match of text2.matchAll(/^\s*(?:pub(?:\([^)]*\))?\s+)?use\s+([^;\n]+)\s*;/gm)) { const specifier = (match[1] ?? "").replace(/\s+/g, "").replace(/::\{.*$/, ""); if (specifier) imports.push({ adapter: "rust", specifier, importedNames: [], wildcard: specifier.endsWith("::*") }); } - for (const match of text.matchAll(/^\s*(?:pub(?:\([^)]*\))?\s+)?mod\s+([A-Za-z_][A-Za-z0-9_]*)\s*;/gm)) { + for (const match of text2.matchAll(/^\s*(?:pub(?:\([^)]*\))?\s+)?mod\s+([A-Za-z_][A-Za-z0-9_]*)\s*;/gm)) { if (match[1] && !pathModules.has(match[1])) imports.push({ adapter: "rust", specifier: `self::${match[1]}`, importedNames: [], wildcard: false }); } return uniqueImports(imports); }, - extractDefinitions(text) { + extractDefinitions(text2) { const visibility = "(?:pub(?:\\([^)]*\\))?\\s+)?"; - return definitionsFromPatterns("rust", text, [ + return definitionsFromPatterns("rust", text2, [ { pattern: new RegExp(`^\\s*${visibility}(?:async\\s+)?(?:unsafe\\s+)?fn\\s+([A-Za-z_][A-Za-z0-9_]*)\\b`, "gm"), kind: "function" }, { pattern: new RegExp(`^\\s*${visibility}(?:struct|enum)\\s+([A-Za-z_][A-Za-z0-9_]*)\\b`, "gm"), kind: "class" }, { pattern: new RegExp(`^\\s*${visibility}trait\\s+([A-Za-z_][A-Za-z0-9_]*)\\b`, "gm"), kind: "interface" }, @@ -337,16 +340,16 @@ var rustAdapter = { var rubyAdapter = { id: "ruby", extensions: [".rb", ".rake"], - extractImports(text) { + extractImports(text2) { const imports = []; - for (const match of text.matchAll(/^\s*(require_relative|require|load)\s*\(?\s*["']([^"'\n]+)["']/gm)) { + for (const match of text2.matchAll(/^\s*(require_relative|require|load)\s*\(?\s*["']([^"'\n]+)["']/gm)) { if (match[2]) imports.push({ adapter: "ruby", specifier: `${match[1] === "require_relative" ? "relative:" : "absolute:"}${match[2]}`, importedNames: [], wildcard: false }); } return uniqueImports(imports); }, - extractDefinitions(text) { - return definitionsFromPatterns("ruby", text, [ + extractDefinitions(text2) { + return definitionsFromPatterns("ruby", text2, [ { pattern: /^\s*(?:async\s+)?def\s+(?:self\.)?([A-Za-z_][A-Za-z0-9_!?=]*)\b/gm, kind: "method" }, { pattern: /^\s*class\s+(?:[A-Za-z_][A-Za-z0-9_]*::)*([A-Za-z_][A-Za-z0-9_]*)\b/gm, kind: "class" }, { pattern: /^\s*module\s+(?:[A-Za-z_][A-Za-z0-9_]*::)*([A-Za-z_][A-Za-z0-9_]*)\b/gm, kind: "type" } @@ -359,23 +362,23 @@ var rubyAdapter = { var phpAdapter = { id: "php", extensions: [".php", ".phtml"], - extractImports(text) { + extractImports(text2) { const imports = []; - for (const match of text.matchAll(/^\s*use\s+(?:function\s+|const\s+)?([^;\n]+)\s*;/gm)) { + for (const match of text2.matchAll(/^\s*use\s+(?:function\s+|const\s+)?([^;\n]+)\s*;/gm)) { for (const entry2 of (match[1] ?? "").split(",")) { const specifier = entry2.trim().replace(/^\\+/, "").split(/\s+as\s+/i)[0]?.trim(); if (specifier) imports.push({ adapter: "php", specifier, importedNames: [], wildcard: false }); } } - for (const match of text.matchAll(/\b(?:require|require_once|include|include_once)\s*(?:\(\s*)?["']([^"'\n]+)["']/g)) { + for (const match of text2.matchAll(/\b(?:require|require_once|include|include_once)\s*(?:\(\s*)?["']([^"'\n]+)["']/g)) { if (match[1]) imports.push({ adapter: "php", specifier: `file:${match[1]}`, importedNames: [], wildcard: false }); } return uniqueImports(imports); }, - extractDefinitions(text) { - return definitionsFromPatterns("php", text, [ + extractDefinitions(text2) { + return definitionsFromPatterns("php", text2, [ { pattern: /\b(?:final\s+|abstract\s+|readonly\s+)*(?:class|trait|enum)\s+([A-Za-z_][A-Za-z0-9_]*)\b/g, kind: "class" }, { pattern: /\binterface\s+([A-Za-z_][A-Za-z0-9_]*)\b/g, kind: "interface" }, { pattern: /\bfunction\s+&?\s*([A-Za-z_][A-Za-z0-9_]*)\s*\(/g, kind: "function" } @@ -388,22 +391,22 @@ var phpAdapter = { var dotnetAdapter = { id: "dotnet", extensions: [".cs", ".csx"], - extractImports(text) { + extractImports(text2) { const imports = []; - for (const match of text.matchAll(/^\s*(?:global\s+)?using\s+(?:static\s+)?(?:[A-Za-z_][A-Za-z0-9_]*\s*=\s*)?([A-Za-z_][A-Za-z0-9_.]*)\s*;/gm)) { + for (const match of text2.matchAll(/^\s*(?:global\s+)?using\s+(?:static\s+)?(?:[A-Za-z_][A-Za-z0-9_]*\s*=\s*)?([A-Za-z_][A-Za-z0-9_.]*)\s*;/gm)) { if (match[1]) imports.push({ adapter: "dotnet", specifier: match[1], importedNames: [], wildcard: false }); } return uniqueImports(imports); }, - extractDefinitions(text) { - const definitions = definitionsFromPatterns("dotnet", text, [ + extractDefinitions(text2) { + const definitions = definitionsFromPatterns("dotnet", text2, [ { pattern: /\b(?:class|record(?:\s+class)?|struct|enum)\s+([A-Za-z_][A-Za-z0-9_]*)\b/g, kind: "class" }, { pattern: /\binterface\s+([A-Za-z_][A-Za-z0-9_]*)\b/g, kind: "interface" }, { pattern: /\bdelegate\s+[^;({]+?\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(/g, kind: "type" } ]); const methodPattern = /(?:^|[;{}]\s*)(?:(?:public|protected|private|internal|static|virtual|override|abstract|sealed|async|extern|unsafe|new|partial)\s+)*(?:[A-Za-z_][A-Za-z0-9_<>,.?\[\]]*\s+)+([A-Za-z_][A-Za-z0-9_]*)\s*\([^;{}]*\)\s*(?:where\s+[^={]+)?(?:=>|\{)/gm; - for (const match of text.matchAll(methodPattern)) { + for (const match of text2.matchAll(methodPattern)) { if (match[1] && !CSHARP_CONTROL_WORDS.has(match[1])) definitions.push({ adapter: "dotnet", name: match[1], kind: "method", offset: match.index }); } @@ -434,20 +437,20 @@ function languageAdapterForFile(file) { } function extractLanguageImports(file) { const cached = IMPORT_CACHE.get(file); - const text = file.searchTextSample ?? file.textSample; + const text2 = file.searchTextSample ?? file.textSample; const extension = file.extension.toLowerCase(); - const imports = cached?.text === text && cached.extension === extension ? cached.facts : languageAdapterForFile(file)?.extractImports(text) ?? []; + const imports = cached?.text === text2 && cached.extension === extension ? cached.facts : languageAdapterForFile(file)?.extractImports(text2) ?? []; if (imports !== cached?.facts) - IMPORT_CACHE.set(file, { extension, text, facts: imports }); + IMPORT_CACHE.set(file, { extension, text: text2, facts: imports }); return imports.map((entry2) => ({ ...entry2, importedNames: [...entry2.importedNames] })); } function extractLanguageDefinitions(file) { const cached = DEFINITION_CACHE.get(file); - const text = file.searchTextSample ?? file.textSample; + const text2 = file.searchTextSample ?? file.textSample; const extension = file.extension.toLowerCase(); - const definitions = cached?.text === text && cached.extension === extension ? cached.facts : languageAdapterForFile(file)?.extractDefinitions(text) ?? []; + const definitions = cached?.text === text2 && cached.extension === extension ? cached.facts : languageAdapterForFile(file)?.extractDefinitions(text2) ?? []; if (definitions !== cached?.facts) - DEFINITION_CACHE.set(file, { extension, text, facts: definitions }); + DEFINITION_CACHE.set(file, { extension, text: text2, facts: definitions }); return definitions.map((entry2) => ({ ...entry2 })); } function isLanguageTestPath(path, extension) { @@ -462,27 +465,27 @@ function splitImportedNames(raw) { function uniqueImports(imports) { const seen = /* @__PURE__ */ new Set(); return imports.filter((entry2) => { - const key = `${entry2.adapter}\0${entry2.specifier}\0${entry2.importedNames.join(",")}\0${String(entry2.wildcard)}`; - if (seen.has(key)) + const key2 = `${entry2.adapter}\0${entry2.specifier}\0${entry2.importedNames.join(",")}\0${String(entry2.wildcard)}`; + if (seen.has(key2)) return false; - seen.add(key); + seen.add(key2); return true; }); } function uniqueDefinitions(definitions) { const seen = /* @__PURE__ */ new Set(); return definitions.filter((entry2) => { - const key = `${entry2.name}\0${entry2.kind}`; - if (seen.has(key)) + const key2 = `${entry2.name}\0${entry2.kind}`; + if (seen.has(key2)) return false; - seen.add(key); + seen.add(key2); return true; }); } -function definitionsFromPatterns(adapter, text, patterns2) { +function definitionsFromPatterns(adapter, text2, patterns2) { const definitions = []; for (const { pattern, kind } of patterns2) { - for (const match of text.matchAll(pattern)) { + for (const match of text2.matchAll(pattern)) { if (match[1]) definitions.push({ adapter, name: match[1], kind, offset: match.index }); } @@ -607,6 +610,13 @@ function isBackupPath(path) { const fileName = path.split("/").pop() ?? ""; return BACKUP_FILE_PATTERNS.some((pattern) => pattern.test(fileName)); } +function isRepositoryRelativePath(candidate) { + if (typeof candidate !== "string" || !candidate.trim() || candidate.includes("\0") || /^[\\/]/.test(candidate) || /^[A-Za-z]:/.test(candidate)) { + return false; + } + const segments = candidate.replace(/\\/g, "/").split("/"); + return segments.every((segment) => segment.length > 0 && segment !== "." && segment !== ".."); +} // packages/core/dist/signals.js var TOKEN_SPLIT = /[^\p{L}\p{N}]+/gu; @@ -795,22 +805,22 @@ function extractTaskSignals(input) { uncheckedChecklistLinesPreserved: prepared.preserved }; } -function prepareChecklistText(text) { +function prepareChecklistText(text2) { const unchecked = /^\s*[-*]\s*\[\s\]\s+/; - const lines = text.split(/\r?\n/); + const lines = text2.split(/\r?\n/); const removed = lines.filter((line) => unchecked.test(line)); if (removed.length === 0) - return { text, removed: 0, preserved: 0 }; + return { text: text2, removed: 0, preserved: 0 }; const retained = lines.filter((line) => !unchecked.test(line)); const hasSubstantiveRetainedText = retained.some((line) => { const trimmed = line.trim(); return trimmed.length > 0 && !/^#{1,6}\s+/.test(trimmed); }); - return hasSubstantiveRetainedText ? { text: retained.join("\n"), removed: removed.length, preserved: 0 } : { text, removed: 0, preserved: removed.length }; + return hasSubstantiveRetainedText ? { text: retained.join("\n"), removed: removed.length, preserved: 0 } : { text: text2, removed: 0, preserved: removed.length }; } -function extractExactFragments(text) { +function extractExactFragments(text2) { const fragments = /* @__PURE__ */ new Set(); - for (const quoted of scanQuotedFragments(text)) { + for (const quoted of scanQuotedFragments(text2)) { const fragment = quoted.value.trim(); if (isDistinctiveFragment(fragment)) { fragments.add(fragment); @@ -821,15 +831,15 @@ function extractExactFragments(text) { } return [...fragments]; } -function extractIdentifiers(text) { +function extractIdentifiers(text2) { const identifiers = /* @__PURE__ */ new Set(); - for (const match of text.matchAll(IDENTIFIER_PATTERN)) { + for (const match of text2.matchAll(IDENTIFIER_PATTERN)) { const identifier = match[0]; if (isDistinctiveIdentifier(identifier)) { addIdentifier(identifiers, identifier); } } - for (const quoted of scanQuotedFragments(text)) { + for (const quoted of scanQuotedFragments(text2)) { if (quoted.delimiter !== "`") { continue; } @@ -844,7 +854,7 @@ function extractIdentifiers(text) { addIdentifier(identifiers, match[0]); } } - for (const match of text.matchAll(/(? /[^\p{L}\p{N}$]/u.test(character)).length; return punctuationCount >= 1 && /[\p{L}\p{N}]/u.test(fragment); } -function redactSensitiveTaskText(text) { - return text.replace(/(https?:\/\/)[^/\s@]+@/gi, "$1").replace(/\b(?:ghp|gho|ghu|ghs|github_pat)_[A-Za-z0-9_]{8,}\b/g, "[redacted]").replace(/\bAKIA[0-9A-Z]{16}\b/g, "[redacted]").replace(/\bsk-[A-Za-z0-9_-]{16,}(?=$|[^A-Za-z0-9_])/g, "[redacted]"); +function redactSensitiveTaskText(text2) { + return text2.replace(/(https?:\/\/)[^/\s@]+@/gi, "$1").replace(/\b(?:ghp|gho|ghu|ghs|github_pat)_[A-Za-z0-9_]{8,}\b/g, "[redacted]").replace(/\bAKIA[0-9A-Z]{16}\b/g, "[redacted]").replace(/\bsk-[A-Za-z0-9_-]{16,}(?=$|[^A-Za-z0-9_])/g, "[redacted]"); } -function stripHttpUrls(text) { - return text.includes("://") ? text.replace(/https?:\/\/[^\s<>()\[\]{}]+/gi, " [url] ") : text; +function stripHttpUrls(text2) { + return text2.includes("://") ? text2.replace(/https?:\/\/[^\s<>()\[\]{}]+/gi, " [url] ") : text2; } -function stripHtmlComments(text) { - return text.includes("/g, " ") : text; +function stripHtmlComments(text2) { + return text2.includes("/g, " ") : text2; } -function scanQuotedFragments(text) { +function scanQuotedFragments(text2) { const fragments = []; - for (const line of text.split(/\r?\n/)) { + for (const line of text2.split(/\r?\n/)) { let cursor = 0; while (cursor < line.length) { const delimiter = line[cursor]; @@ -912,20 +922,20 @@ function scanQuotedFragments(text) { } return fragments; } -function isEscaped(text, index) { +function isEscaped(text2, index) { let backslashes = 0; - for (let cursor = index - 1; cursor >= 0 && text[cursor] === "\\"; cursor -= 1) { + for (let cursor = index - 1; cursor >= 0 && text2[cursor] === "\\"; cursor -= 1) { backslashes += 1; } return backslashes % 2 === 1; } -function extractFileMentions(text) { +function extractFileMentions(text2) { const mentions = /* @__PURE__ */ new Set(); - for (const match of text.matchAll(CONVENTIONAL_FILE_MENTION_PATTERN)) { + for (const match of text2.matchAll(CONVENTIONAL_FILE_MENTION_PATTERN)) { if (match[0]) mentions.add(match[0]); } - for (const match of text.matchAll( + for (const match of text2.matchAll( // blob, tree and blame all address a path in the repository; only the view differs, and // a tree or blame link is the same deliberate "the code is here" gesture as a blob one. // The ref is any branch, tag or sha — restricting to a hex sha kept only permalinks and @@ -944,7 +954,7 @@ function extractFileMentions(text) { if (file && file.length >= 4) mentions.add(file.replace(/\\/g, "/")); } - const withoutUrls = text.includes("://") ? text.replace(/https?:\/\/\S+/gi, " ") : text; + const withoutUrls = text2.includes("://") ? text2.replace(/https?:\/\/\S+/gi, " ") : text2; for (const match of withoutUrls.matchAll(FILE_MENTION_PATTERN)) { const cleaned = match[0].replace(/\\/g, "/").replace(/^\.\.?\//, ""); if (cleaned.length >= 4) { @@ -953,8 +963,8 @@ function extractFileMentions(text) { } return mentions; } -function extractMemberMentions(text) { - return new Set([...text.matchAll(MEMBER_MENTION_PATTERN)].map((match) => match[1]).filter((member) => typeof member === "string" && !FILE_EXTENSIONS.has(member.toLowerCase()))); +function extractMemberMentions(text2) { + return new Set([...text2.matchAll(MEMBER_MENTION_PATTERN)].map((match) => match[1]).filter((member) => typeof member === "string" && !FILE_EXTENSIONS.has(member.toLowerCase()))); } function extractDiffContentLines(diffText) { if (!diffText) { @@ -962,8 +972,8 @@ function extractDiffContentLines(diffText) { } return diffText.split(/\r?\n/).filter((line) => line.startsWith("+") && !line.startsWith("+++")).join("\n"); } -function tokenizeText(text) { - return new Set(text.replace(/\bhttp\s*\/\s*([123])\b/gi, "http h$1").replace(/https?:\/\/[^\s<>()\[\]{}]+/gi, " ").replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(TOKEN_SPLIT).map((token) => token.trim()).filter((token) => isSearchableToken(token) && !STOP_WORDS.has(token)).map((token) => normalizeToken(token)).filter((token) => isSearchableToken(token) && !STOP_WORDS.has(token))); +function tokenizeText(text2) { + return new Set(text2.replace(/\bhttp\s*\/\s*([123])\b/gi, "http h$1").replace(/https?:\/\/[^\s<>()\[\]{}]+/gi, " ").replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(TOKEN_SPLIT).map((token) => token.trim()).filter((token) => isSearchableToken(token) && !STOP_WORDS.has(token)).map((token) => normalizeToken(token)).filter((token) => isSearchableToken(token) && !STOP_WORDS.has(token))); } function tokenizeIdentifier(identifier) { return new Set(identifier.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(TOKEN_SPLIT).map((token) => normalizeToken(token.trim())).filter((token) => isSearchableToken(token))); @@ -1243,8 +1253,8 @@ function isVagueTaskText(issueText) { const residual = tokenizeText(issueText.replace(VAGUE_TASK_TERMS, " ")); return residual.size <= MAX_RESIDUAL_TOKENS_FOR_VAGUE; } -function removeIdentifiers(text, identifiers) { - return identifiers.reduce((current2, identifier) => current2.replace(new RegExp(escapeRegExp(identifier), "g"), " "), text); +function removeIdentifiers(text2, identifiers) { + return identifiers.reduce((current2, identifier) => current2.replace(new RegExp(escapeRegExp(identifier), "g"), " "), text2); } function escapeRegExp(value) { return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); @@ -1767,7 +1777,7 @@ function detectPrimaryLanguage(repo) { if (!leader || leader.count === 0) { return { language: "unknown", evidence: "no root manifest and no recognizable source files" }; } - const total = [...shares.values()].reduce((sum, count) => sum + count, 0); + const total = [...shares.values()].reduce((sum, count2) => sum + count2, 0); const share = Math.round(leader.count / total * 100); const manifest = manifests.get(leader.language); if (manifest) { @@ -2091,13 +2101,13 @@ function goReplacementForImport(module, specifier) { const equallySpecific = matching.filter((replacement) => replacement.module.length === longest); return equallySpecific.length === 1 ? equallySpecific[0] : void 0; } -function parseUsePaths(text) { +function parseUsePaths(text2) { const uses = []; - for (const match of text.matchAll(/^\s*use\s+([^\s(][^\s]*)\s*(?:\/\/.*)?$/gm)) { + for (const match of text2.matchAll(/^\s*use\s+([^\s(][^\s]*)\s*(?:\/\/.*)?$/gm)) { if (match[1]) uses.push(match[1]); } - for (const block of text.matchAll(/^\s*use\s*\(\s*$([\s\S]*?)^\s*\)\s*(?:\/\/.*)?$/gm)) { + for (const block of text2.matchAll(/^\s*use\s*\(\s*$([\s\S]*?)^\s*\)\s*(?:\/\/.*)?$/gm)) { for (const raw of (block[1] ?? "").split(/\r?\n/)) { const value = raw.replace(/\/\/.*$/, "").trim().split(/\s+/)[0]; if (value) @@ -2106,11 +2116,11 @@ function parseUsePaths(text) { } return uses; } -function parseReplaceClauses(text) { +function parseReplaceClauses(text2) { const clauses = []; let inBlock = false; let blockClauses = []; - for (const raw of text.split(/\r?\n/)) { + for (const raw of text2.split(/\r?\n/)) { const line = raw.replace(/\/\/.*$/, "").trim(); if (!line) continue; @@ -2827,10 +2837,10 @@ function composerReachableProjects(resolverIndex, project) { } return reachable; } -function rubyConstantIdentifiers(text) { +function rubyConstantIdentifiers(text2) { const identifiers = /* @__PURE__ */ new Set(); let heredocEnd; - for (const line of text.split(/\r?\n/)) { + for (const line of text2.split(/\r?\n/)) { if (heredocEnd) { if (line.trim() === heredocEnd) heredocEnd = void 0; @@ -2905,12 +2915,12 @@ function nearestManifestDirectory(fromPath, manifest, repoPaths) { } return void 0; } -function addIndexedPath(index, key, path) { - const existing = index.get(key); +function addIndexedPath(index, key2, path) { + const existing = index.get(key2); if (existing) existing.push(path); else - index.set(key, [path]); + index.set(key2, [path]); } function shortestPathFirst(left, right) { return left.split("/").length - right.split("/").length || left.localeCompare(right); @@ -3036,23 +3046,23 @@ var AGENT_COMMAND_PATHS = /* @__PURE__ */ new Set([ ]); var AGENT_COMMAND_MARKER = "You are the FixMap workflow assistant for this repository."; function fixMapArtifactKind(file) { - const text = file.textSample.trimStart(); - if (!text) + const text2 = file.textSample.trimStart(); + if (!text2) return void 0; - if (AGENT_COMMAND_PATHS.has(file.path.replace(/\\/g, "/").toLowerCase()) && text.includes(AGENT_COMMAND_MARKER)) { + if (AGENT_COMMAND_PATHS.has(file.path.replace(/\\/g, "/").toLowerCase()) && text2.includes(AGENT_COMMAND_MARKER)) { return "agent-command"; } - if (text.startsWith("# FixMap Report\n") && text.includes("\n## Context Files\n")) + if (text2.startsWith("# FixMap Report\n") && text2.includes("\n## Context Files\n")) return "report-markdown"; - if (text.startsWith("# FixMap Context\n") && text.includes("\n## Task\n")) + if (text2.startsWith("# FixMap Context\n") && text2.includes("\n## Task\n")) return "context-markdown"; - if (text.startsWith("# FixMap Change Scope\n") && text.includes("\n## Declared anchors\n")) + if (text2.startsWith("# FixMap Change Scope\n") && text2.includes("\n## Declared anchors\n")) return "change-scope-markdown"; - if (text.startsWith("# FixMap Capability:") && text.includes("\n## Declared anchors\n")) + if (text2.startsWith("# FixMap Capability:") && text2.includes("\n## Declared anchors\n")) return "capability-map-markdown"; - if (text.startsWith("# FixMap Capability Diff:") && text.includes("\n## Selected scope\n")) + if (text2.startsWith("# FixMap Capability Diff:") && text2.includes("\n## Selected scope\n")) return "capability-history-markdown"; - if (text.startsWith("# FixMap Capabilities\n")) + if (text2.startsWith("# FixMap Capabilities\n")) return "capability-list-markdown"; if (!file.path.toLowerCase().endsWith(".json") || file.textSampleComplete === false) return void 0; @@ -3218,9 +3228,9 @@ to too under until up very was we were what when where which while who whom why bug issue issues error errors expected actual behavior behaviour reproduce reproduction steps version versions node npm report repo repository description example code please thanks title type severity confidence location line lines following above below see also would should could may might must will can also using used use uses`.split(/\s+/)); -function retrievalTokens(text) { +function retrievalTokens(text2) { const tokens = []; - for (const raw of text.match(/[A-Za-z0-9_$]+/g) ?? []) { + for (const raw of text2.match(/[A-Za-z0-9_$]+/g) ?? []) { const lower = raw.toLowerCase(); if (lower.length >= 3) tokens.push(lower); @@ -3360,7 +3370,7 @@ function insertBoundedBm25(top, entry2, limit) { function compareBm25(left, right) { return right.score - left.score || left.id.localeCompare(right.id); } -function bm25DocumentStatistics(text, queryTerms) { +function bm25DocumentStatistics(text2, queryTerms) { const counts = /* @__PURE__ */ new Map(); let length = 0; const record3 = (token) => { @@ -3368,7 +3378,7 @@ function bm25DocumentStatistics(text, queryTerms) { if (queryTerms.has(token)) counts.set(token, (counts.get(token) ?? 0) + 1); }; - for (const match of text.matchAll(/[A-Za-z0-9_$]+/g)) { + for (const match of text2.matchAll(/[A-Za-z0-9_$]+/g)) { const raw = match[0]; const lower = raw.toLowerCase(); if (lower.length >= 3) @@ -3937,24 +3947,24 @@ function isPresentationSurfacePath(path) { const name = path.split("/").at(-1)?.toLowerCase() ?? ""; return /^(?:page|layout|demo)\.[cm]?[jt]sx?$/.test(name) || /\.(?:css|less|sass|scss)$/.test(name); } -function isInteractivePresentation(text) { - return /<(?:button|form|input|select|textarea)\b|\bon(?:Change|Click|Input|Submit)\s*=|\buseState\s*\(/.test(text); +function isInteractivePresentation(text2) { + return /<(?:button|form|input|select|textarea)\b|\bon(?:Change|Click|Input|Submit)\s*=|\buseState\s*\(/.test(text2); } -function tokenizeFileContent(text, regexTokens) { - const tokens = tokenizeText(text); +function tokenizeFileContent(text2, regexTokens) { + const tokens = tokenizeText(text2); for (const token of regexTokens) tokens.add(token); return tokens; } -function taskTokensInFile(text, taskTokens, regexTokens) { +function taskTokensInFile(text2, taskTokens, regexTokens) { const regexOverlap = [...regexTokens].some((token) => taskTokens.has(token)); - if (!regexOverlap && !mightContainTaskToken(text, taskTokens)) + if (!regexOverlap && !mightContainTaskToken(text2, taskTokens)) return /* @__PURE__ */ new Set(); - const tokens = tokenizeFileContent(text, regexTokens); + const tokens = tokenizeFileContent(text2, regexTokens); return new Set([...tokens].filter((token) => taskTokens.has(token))); } -function mightContainTaskToken(text, taskTokens) { - const lower = text.toLowerCase(); +function mightContainTaskToken(text2, taskTokens) { + const lower = text2.toLowerCase(); for (const token of taskTokens) { if (token === "css" && /\b(?:css|scss|sass|less)\b/.test(lower)) return true; @@ -3967,9 +3977,9 @@ function mightContainTaskToken(text, taskTokens) { } return false; } -function extractRegexTokens(text) { +function extractRegexTokens(text2) { const tokens = /* @__PURE__ */ new Set(); - for (const match of text.matchAll(/\b([A-Za-z])\{(\d+),(\d+)\}/g)) { + for (const match of text2.matchAll(/\b([A-Za-z])\{(\d+),(\d+)\}/g)) { const character = match[1]?.toLowerCase(); const minimum = Number(match[2]); const maximum = Math.min(Number(match[3]), 8); @@ -4035,16 +4045,16 @@ function findTaskMatchedDefinitions(file, taskTokens, custom) { } return matched; } -function hasExactFragmentAtDefinition(text, fragment, definedIdentifiers) { - let index = text.indexOf(fragment); +function hasExactFragmentAtDefinition(text2, fragment, definedIdentifiers) { + let index = text2.indexOf(fragment); while (index !== -1) { - const prefix = text.slice(Math.max(0, index - 240), index); + const prefix = text2.slice(Math.max(0, index - 240), index); const namesNearby = definedIdentifiers.some((identifier) => prefix.includes(identifier)); const assignmentNearby = /\b(?:const|let|var)\s+[$A-Za-z_][$A-Za-z0-9_]*(?:\s*:[^=\r\n]+)?\s*=\s*[/("'`]?\s*$/.test(prefix); if (namesNearby || assignmentNearby) { return true; } - index = text.indexOf(fragment, index + fragment.length); + index = text2.indexOf(fragment, index + fragment.length); } return false; } @@ -4054,11 +4064,11 @@ function previewFragment(fragment) { function escapeRegExp2(value) { return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } -function countOccurrences(text, value) { +function countOccurrences(text2, value) { if (!value) { return 0; } - return text.split(value).length - 1; + return text2.split(value).length - 1; } function findCommonTokens(contentTokensByPath) { const fileCount = contentTokensByPath.size; @@ -4072,7 +4082,7 @@ function findCommonTokens(contentTokensByPath) { frequency.set(token, (frequency.get(token) ?? 0) + 1); } } - return new Set([...frequency].filter(([, count]) => count >= threshold).map(([token]) => token)); + return new Set([...frequency].filter(([, count2]) => count2 >= threshold).map(([token]) => token)); } function isNearbyChangedFile(path, changedFiles) { const folder = path.split("/").slice(0, -1).join("/"); @@ -4187,6 +4197,429 @@ function extractEnvNames(textSample) { return [...names].sort((a, b) => a.localeCompare(b)); } +// packages/core/dist/sensitive-data.js +var MAX_ANALYZED_FILES = 5e3; +var MAX_RELATIONSHIPS = 1e4; +var SENSITIVE_DATA_PROVIDER_ID = "fixmap-sensitive-data"; +var SENSITIVE_DATA_PROVIDER_VERSION = "1.0.0"; +var PROVIDER_VERSION = SENSITIVE_DATA_PROVIDER_VERSION; +var SOURCE_RULES = [ + { id: "credential-password", category: "credential", pattern: /\b(?:password|passwd|credential|client[_-]?secret|api[_-]?key)\b/i }, + { id: "token-auth", category: "token", pattern: /\b(?:access[_-]?token|refresh[_-]?token|bearer|authorization|jwt)\b/i }, + { id: "pii-contact", category: "pii", pattern: /\b(?:email[_-]?address|phone[_-]?number|date[_-]?of[_-]?birth|social[_-]?security|ssn)\b/i }, + { id: "payment-card", category: "payment", pattern: /\b(?:card[_-]?number|payment[_-]?method|cvv|cvc|iban)\b/i } +]; +var SINK_RULES = [ + { id: "sink-log", category: "logging", pattern: /\b(?:console\.(?:log|info|warn|error)|logger\.(?:debug|info|warn|error)|logging\.(?:debug|info|warning|error))\s*\(/i }, + { id: "sink-network", category: "network", pattern: /\b(?:fetch|axios\.(?:get|post|put|patch)|requests\.(?:get|post|put|patch)|httpClient\.(?:get|post|put|patch)|sendRequest)\s*\(/i }, + { id: "sink-storage", category: "storage", pattern: /\b(?:writeFile|localStorage\.setItem|sessionStorage\.setItem|\.save|\.persist|INSERT\s+INTO|UPDATE\s+[^\s]+\s+SET)\b/i }, + { id: "sink-analytics", category: "analytics", pattern: /\b(?:analytics\.(?:track|identify)|telemetry\.(?:track|capture)|captureEvent|trackEvent)\s*\(/i } +]; +function collectSensitiveDataSignals(repo) { + const codeFiles = repo.files.filter((file) => file.kind === "code"); + const eligible = codeFiles.filter((file) => file.textSampleComplete !== false && file.contentFingerprint); + const selected = eligible.slice(0, MAX_ANALYZED_FILES); + const classified = selected.map(classifyFile).filter((entry2) => entry2.sources.length > 0 || entry2.sinks.length > 0); + const exact = classified; + const skippedFiles = codeFiles.length - selected.length; + const items = [scopeItem(repo.root, selected.length, skippedFiles)]; + const itemId = /* @__PURE__ */ new Map(); + for (const entry2 of exact) { + for (const category of entry2.sources) { + const id = stableId("source", category, entry2.file.path); + itemId.set(key(entry2.file.path, "source", category), id); + items.push(fileItem(id, entry2.file, "source", category)); + } + for (const category of entry2.sinks) { + const id = stableId("sink", category, entry2.file.path); + itemId.set(key(entry2.file.path, "sink", category), id); + items.push(fileItem(id, entry2.file, "sink", category)); + } + } + const relationships = []; + const relationshipIds = /* @__PURE__ */ new Set(); + for (const entry2 of exact) { + for (const source of entry2.sources) + for (const sink of entry2.sinks) { + pushRelationship(relationships, relationshipIds, { + from: itemId.get(key(entry2.file.path, "source", source)), + to: itemId.get(key(entry2.file.path, "sink", sink)), + relation: "same-file-sensitive-signal-and-sink", + reason: `${entry2.file.path} contains both ${source} vocabulary and a ${sink} call pattern; value flow was not verified.` + }); + } + } + const graph = buildImportGraph(repo.files); + const byPath = new Map(exact.map((entry2) => [entry2.file.path, entry2])); + for (const [fromPath, targets] of graph.imports) { + const from = byPath.get(fromPath); + if (!from) + continue; + for (const toPath of targets) { + const to = byPath.get(toPath); + if (!to) + continue; + connectAcrossImport(relationships, relationshipIds, itemId, from, to); + connectAcrossImport(relationships, relationshipIds, itemId, to, from); + } + } + return { + items: items.sort((a, b) => a.id.localeCompare(b.id)), + relationships: relationships.slice(0, MAX_RELATIONSHIPS).sort((a, b) => a.id.localeCompare(b.id)) + }; +} +function sensitiveSignalLine(text2, ruleIds) { + const rules = [...SOURCE_RULES, ...SINK_RULES].filter((rule) => ruleIds.includes(rule.id)); + if (rules.length === 0) + return void 0; + const lines = text2.split(/\r?\n/); + for (let index = 0; index < lines.length; index += 1) { + if (rules.some((rule) => rule.pattern.test(lines[index]))) + return index + 1; + } + return void 0; +} +function classifyFile(file) { + return { + file, + sources: categories(file.textSample, SOURCE_RULES), + sinks: categories(file.textSample, SINK_RULES) + }; +} +function categories(text2, rules) { + return [...new Set(rules.filter((rule) => rule.pattern.test(text2)).map((rule) => rule.category))].sort(); +} +function scopeItem(repository, scannedFiles, skippedFiles) { + return { + id: "scope", + kind: "security", + summary: "Approximate sensitive-data indicators from local lexical and import-structure analysis; this is not a complete security or taint-flow proof.", + confidence: "low", + subjects: [{ kind: "repository", repository }], + metadata: { + analysis: "lexical-signals-and-direct-import-structure", + completeness: "not-a-security-proof", + scannedFiles, + skippedFiles + } + }; +} +function fileItem(id, file, role, category) { + const rules = role === "source" ? SOURCE_RULES : SINK_RULES; + const matchedRuleIds = rules.filter((rule) => rule.category === category && rule.pattern.test(file.textSample)).map((rule) => rule.id).join(","); + return { + id, + kind: "security", + summary: `Possible sensitive-data ${role} indicator (${category}) in ${file.path}; lexical evidence only.`, + confidence: "low", + subjects: [{ kind: "file", path: file.path }], + metadata: { + role, + category, + matchedRuleIds, + sourceFingerprint: file.contentFingerprint, + detectorVersion: PROVIDER_VERSION, + completeness: "not-a-security-proof" + } + }; +} +function connectAcrossImport(relationships, relationshipIds, ids, sourceEntry, sinkEntry) { + for (const source of sourceEntry.sources) + for (const sink of sinkEntry.sinks) { + pushRelationship(relationships, relationshipIds, { + from: ids.get(key(sourceEntry.file.path, "source", source)), + to: ids.get(key(sinkEntry.file.path, "sink", sink)), + relation: "structurally-connected-sensitive-signal", + reason: `${sourceEntry.file.path} and ${sinkEntry.file.path} are directly import-connected; runtime data transfer was not verified.` + }); + } +} +function pushRelationship(relationships, relationshipIds, input) { + if (relationships.length >= MAX_RELATIONSHIPS) + return; + const id = stableId(input.relation, input.from, input.to); + if (relationshipIds.has(id)) + return; + relationshipIds.add(id); + relationships.push({ id, ...input, confidence: "low" }); +} +function key(path, role, category) { + return `${path}\0${role}\0${category}`; +} +function stableId(...values) { + let hash = 0xcbf29ce484222325n; + for (const byte of new TextEncoder().encode(values.join("\0"))) { + hash ^= BigInt(byte); + hash = BigInt.asUintN(64, hash * 0x100000001b3n); + } + return `signal-${hash.toString(16).padStart(16, "0")}`; +} + +// packages/core/dist/report-sensitive-data.js +var MAX_REPORT_SENSITIVE_DATA_FLOWS = 50; +var SOURCE_CATEGORIES = ["credential", "token", "pii", "payment"]; +var SINK_CATEGORIES = ["logging", "network", "storage", "analytics"]; +var RULE_ID = /^[a-z0-9-]{1,64}$/; +function buildReportSensitiveData(repo, focusPaths, options = {}) { + const after = flowsFrom(repo.root, repo.files); + let introducedCheck; + let before; + if (options.compareWithDiff) { + const previousFiles = filesBeforeDiff(repo); + introducedCheck = previousFiles ? "compared-with-diff" : "unavailable-diff-truncated"; + if (previousFiles) + before = new Set(flowsFrom(repo.root, previousFiles).flows.map(flowKey)); + } + const relevant = after.flows.filter((flow) => focusPaths.has(flow.source.path) || focusPaths.has(flow.sink.path)).map((flow) => before && !before.has(flowKey(flow)) ? { ...flow, introducedByDiff: true } : flow).sort((a, b) => Number(b.introducedByDiff === true) - Number(a.introducedByDiff === true) || a.relation.localeCompare(b.relation) || flowKey(a).localeCompare(flowKey(b))); + const textByPath = new Map(repo.files.map((file) => [file.path, file.textSample])); + const withLine = (end) => { + const line = sensitiveSignalLine(textByPath.get(end.path) ?? "", end.ruleIds); + return line === void 0 ? end : { ...end, line }; + }; + const flows = relevant.slice(0, MAX_REPORT_SENSITIVE_DATA_FLOWS).map((flow) => ({ ...flow, source: withLine(flow.source), sink: withLine(flow.sink) })); + return { + sensitiveDataVersion: 1, + provider: { id: SENSITIVE_DATA_PROVIDER_ID, version: SENSITIVE_DATA_PROVIDER_VERSION }, + analysis: "lexical-signals-and-direct-import-structure", + completeness: "not-a-security-proof", + scannedFiles: after.scannedFiles, + skippedFiles: after.skippedFiles, + flows, + omittedFlows: relevant.length - flows.length, + ...introducedCheck ? { introducedCheck } : {} + }; +} +function sensitiveDataVerifyFinding(evidence) { + const introduced = evidence.flows.filter((flow) => flow.introducedByDiff); + if (introduced.length === 0) + return void 0; + const paths = [...new Set(introduced.flatMap((flow) => [flow.source.path, flow.sink.path]))]; + const examples = introduced.slice(0, 3).map(describeFlow).join("; "); + return { + code: "sensitive-data-flow-introduced", + severity: "info", + paths: paths.slice(0, 8), + message: `This diff adds ${introduced.length === 1 ? "a possible sensitive-data flow" : `${introduced.length} possible sensitive-data flows`} from lexical evidence (${examples}${introduced.length > 3 ? "; \u2026" : ""}). Value flow was not verified; check that no secret or personal data reaches the sink.` + }; +} +function renderSensitiveDataMarkdown(evidence) { + return [ + "", + "## Sensitive Data", + "", + `Lexical indicators from \`${evidence.provider.id}\` ${evidence.provider.version} across ${evidence.scannedFiles} scanned file${evidence.scannedFiles === 1 ? "" : "s"}${evidence.skippedFiles > 0 ? ` (${evidence.skippedFiles} skipped)` : ""}. Locations and kinds only; matched values are not shown. This is not a taint analysis or a security proof.`, + ...evidence.introducedCheck === "unavailable-diff-truncated" ? ["", "The diff was too large to reconstruct pre-change contents, so newly introduced flows could not be identified."] : [], + "", + ...evidence.flows.length > 0 ? evidence.flows.map((flow) => `- ${flow.introducedByDiff ? "**new** " : ""}${describeFlow(flow)}`) : ["- No possible source-to-sink flows touch the files in this report."], + ...evidence.omittedFlows > 0 ? ["", `${evidence.omittedFlows} further flow${evidence.omittedFlows === 1 ? " was" : "s were"} not listed.`] : [] + ]; +} +function isReportSensitiveData(candidate) { + if (!isRecord3(candidate) || candidate.sensitiveDataVersion !== 1 || !isRecord3(candidate.provider) || candidate.provider.id !== SENSITIVE_DATA_PROVIDER_ID || typeof candidate.provider.version !== "string" || candidate.analysis !== "lexical-signals-and-direct-import-structure" || candidate.completeness !== "not-a-security-proof" || !count(candidate.scannedFiles) || !count(candidate.skippedFiles) || !count(candidate.omittedFlows) || candidate.introducedCheck !== void 0 && !["compared-with-diff", "unavailable-diff-truncated"].includes(String(candidate.introducedCheck)) || !Array.isArray(candidate.flows) || candidate.flows.length > MAX_REPORT_SENSITIVE_DATA_FLOWS) + return false; + return candidate.flows.every((flow) => isRecord3(flow) && (flow.relation === "same-file" || flow.relation === "direct-import") && (flow.introducedByDiff === void 0 || flow.introducedByDiff === true) && validEnd(flow.source, SOURCE_CATEGORIES) && validEnd(flow.sink, SINK_CATEGORIES) && (flow.relation !== "same-file" || flow.source.path === flow.sink.path)); +} +function validEnd(candidate, categories2) { + return isRecord3(candidate) && isRepositoryRelativePath(candidate.path) && categories2.includes(String(candidate.category)) && Array.isArray(candidate.ruleIds) && candidate.ruleIds.length > 0 && candidate.ruleIds.length <= 8 && candidate.ruleIds.every((id) => typeof id === "string" && RULE_ID.test(id)) && (candidate.line === void 0 || Number.isSafeInteger(candidate.line) && candidate.line > 0); +} +function describeFlow(flow) { + const at = (end) => markdownCode(end.line ? `${end.path}:${end.line}` : end.path); + return flow.relation === "same-file" ? `${flow.source.category} \u2192 ${flow.sink.category} in ${at(flow.source)} and ${at(flow.sink)} (same file)` : `${flow.source.category} in ${at(flow.source)} \u2192 ${flow.sink.category} in ${at(flow.sink)} (direct import)`; +} +function flowsFrom(root, files) { + const result = collectSensitiveDataSignals({ root, files: [...files] }); + const signals = /* @__PURE__ */ new Map(); + let scannedFiles = 0; + let skippedFiles = 0; + for (const item of result.items) { + const metadata = item.metadata ?? {}; + if (item.id === "scope") { + scannedFiles = Number(metadata.scannedFiles) || 0; + skippedFiles = Number(metadata.skippedFiles) || 0; + continue; + } + const subject = item.subjects[0]; + if (!subject || subject.kind !== "file") + continue; + signals.set(item.id, { + path: subject.path, + role: metadata.role === "sink" ? "sink" : "source", + category: String(metadata.category), + ruleIds: String(metadata.matchedRuleIds ?? "").split(",").filter(Boolean) + }); + } + const flows = []; + for (const relationship of result.relationships ?? []) { + const source = signals.get(relationship.from); + const sink = signals.get(relationship.to); + if (!source || !sink) + continue; + flows.push({ + relation: relationship.relation === "same-file-sensitive-signal-and-sink" ? "same-file" : "direct-import", + source: { path: source.path, category: source.category, ruleIds: source.ruleIds }, + sink: { path: sink.path, category: sink.category, ruleIds: sink.ruleIds } + }); + } + return { flows, scannedFiles, skippedFiles }; +} +function flowKey(flow) { + return [flow.relation, flow.source.path, flow.source.category, flow.sink.path, flow.sink.category].join("\0"); +} +function filesBeforeDiff(repo) { + if (repo.diagnostics.some((diagnostic) => diagnostic.code === "diff-text-truncated")) + return void 0; + const patches = parseUnifiedDiff(repo.diffText); + const changed = new Set(repo.changedFiles); + const tracked = repo.trackedFiles ? new Set(repo.trackedFiles) : void 0; + return repo.files.flatMap((file) => { + if (!changed.has(file.path)) + return [file]; + const patch = patches.get(file.path); + if (!patch) + return tracked && !tracked.has(file.path) ? [] : [file]; + if (patch.created) + return []; + const lines = file.textSample.split(/\r?\n/); + for (const added of patch.added) { + const index = lines.indexOf(added); + if (index !== -1) + lines.splice(index, 1); + } + return [{ ...file, textSample: [...lines, ...patch.removed].join("\n") }]; + }); +} +function parseUnifiedDiff(diffText) { + const patches = /* @__PURE__ */ new Map(); + let current2; + let created = false; + let inHunk = false; + for (const line of diffText.split(/\r?\n/)) { + if (line.startsWith("diff --git ")) { + current2 = void 0; + created = false; + inHunk = false; + } else if (!inHunk && line.startsWith("--- ")) { + created = line === "--- /dev/null"; + } else if (!inHunk && line.startsWith("+++ ")) { + const path = diffPath(line.slice(4)); + current2 = path ? { added: [], removed: [], created } : void 0; + if (path && current2) + patches.set(path, current2); + } else if (line.startsWith("@@")) { + inHunk = true; + } else if (inHunk && current2) { + if (line.startsWith("+")) + current2.added.push(line.slice(1)); + else if (line.startsWith("-")) + current2.removed.push(line.slice(1)); + } + } + return patches; +} +function diffPath(raw) { + if (raw === "/dev/null") + return void 0; + let path = raw.replace(/\t.*$/, ""); + if (path.startsWith('"')) { + try { + path = JSON.parse(path); + } catch { + return void 0; + } + } + return path.replace(/^[a-z]\//, ""); +} +function count(value) { + return Number.isSafeInteger(value) && value >= 0; +} +function isRecord3(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +// packages/core/dist/report-supply-chain.js +var MAX_REPORT_SUPPLY_CHAIN_FINDINGS = 50; +var SEVERITIES = ["critical", "high", "medium", "low", "info", "unknown"]; +function buildReportSupplyChain(bundle, documentSha256, focusPaths) { + const components = new Map(bundle.components.map((component) => [component.id, component])); + const relevant = []; + for (const finding of bundle.findings) { + const component = components.get(finding.componentId); + const manifestPaths = component?.paths.filter((path) => focusPaths.has(path)) ?? []; + if (!component || manifestPaths.length === 0) + continue; + relevant.push({ + id: finding.id, + kind: finding.kind, + severity: finding.severity, + confidence: finding.confidence, + summary: finding.summary, + package: { + name: component.name, + ...component.version ? { version: component.version } : {}, + ...component.purl ? { purl: component.purl } : {} + }, + manifestPaths, + ...finding.advisoryId ? { advisoryId: finding.advisoryId } : {}, + ...finding.fixedVersion ? { fixedVersion: finding.fixedVersion } : {}, + ...finding.licenseId ? { licenseId: finding.licenseId } : {}, + ...finding.policy ? { policy: finding.policy } : {}, + ...finding.sourceUrl ? { sourceUrl: finding.sourceUrl } : {} + }); + } + const findings = relevant.slice(0, MAX_REPORT_SUPPLY_CHAIN_FINDINGS); + return { + supplyChainVersion: 1, + source: { + tool: bundle.source.tool, + toolVersion: bundle.source.toolVersion, + ...bundle.source.databaseVersion ? { databaseVersion: bundle.source.databaseVersion } : {}, + documentFingerprint: bundle.source.documentFingerprint, + generatedAt: bundle.generatedAt, + documentSha256 + }, + findings, + omittedFindings: bundle.findings.length - findings.length + }; +} +function renderSupplyChainReportMarkdown(evidence) { + const { source } = evidence; + return [ + "", + "## Supply-Chain Evidence", + "", + `Imported from ${markdownCode(source.tool)} ${inlineProse(source.toolVersion)}${source.databaseVersion ? `, database ${inlineProse(source.databaseVersion)}` : ""}, generated ${source.generatedAt} (bundle sha256 ${markdownCode(source.documentSha256)}). Findings are shown as supplied; FixMap did not fetch advisories, run a scanner, or verify exploitability.`, + "", + ...evidence.findings.length > 0 ? evidence.findings.map((finding) => { + const details = [ + finding.advisoryId && `advisory ${markdownCode(finding.advisoryId)}`, + finding.fixedVersion && `fixed in ${markdownCode(finding.fixedVersion)}`, + finding.licenseId && `license ${markdownCode(finding.licenseId)}`, + finding.policy && `policy ${inlineProse(finding.policy)}` + ].filter(Boolean).join("; "); + const name = `${finding.package.name}${finding.package.version ? `@${finding.package.version}` : ""}`; + return `- **${finding.severity}** ${finding.kind} for ${markdownCode(name)} declared in ${finding.manifestPaths.map(markdownCode).join(", ")}: ${inlineProse(finding.summary)}${details ? ` (${details})` : ""}`; + }) : ["- No imported findings are for packages declared in manifests among this report's files."], + ...evidence.omittedFindings > 0 ? ["", `${evidence.omittedFindings} further finding${evidence.omittedFindings === 1 ? " was" : "s were"} for manifests outside this report or over the listing limit.`] : [] + ]; +} +function isReportSupplyChain(candidate) { + if (!isRecord4(candidate) || candidate.supplyChainVersion !== 1 || !isRecord4(candidate.source)) + return false; + const source = candidate.source; + if (!text(source.tool, 100) || !text(source.toolVersion, 100) || !optionalText(source.databaseVersion, 200) || typeof source.documentFingerprint !== "string" || !/^sha256:[a-f0-9]{64}$/.test(source.documentFingerprint) || typeof source.generatedAt !== "string" || !Number.isFinite(Date.parse(source.generatedAt)) || typeof source.documentSha256 !== "string" || !/^[a-f0-9]{64}$/.test(source.documentSha256) || !Number.isSafeInteger(candidate.omittedFindings) || candidate.omittedFindings < 0 || !Array.isArray(candidate.findings) || candidate.findings.length > MAX_REPORT_SUPPLY_CHAIN_FINDINGS) + return false; + return candidate.findings.every((finding) => isRecord4(finding) && text(finding.id, 80) && ["vulnerability", "outdated-version", "license-policy"].includes(String(finding.kind)) && SEVERITIES.includes(String(finding.severity)) && ["low", "medium", "high"].includes(String(finding.confidence)) && text(finding.summary, 1e3) && isRecord4(finding.package) && text(finding.package.name, 300) && optionalText(finding.package.version, 300) && (finding.package.purl === void 0 || typeof finding.package.purl === "string" && finding.package.purl.startsWith("pkg:")) && Array.isArray(finding.manifestPaths) && finding.manifestPaths.length > 0 && finding.manifestPaths.every(isRepositoryRelativePath) && optionalText(finding.advisoryId, 300) && optionalText(finding.fixedVersion, 300) && optionalText(finding.licenseId, 200) && optionalText(finding.policy, 500) && (finding.sourceUrl === void 0 || typeof finding.sourceUrl === "string" && finding.sourceUrl.startsWith("https://"))); +} +function text(value, max) { + return typeof value === "string" && value.trim().length > 0 && value.length <= max; +} +function optionalText(value, max) { + return value === void 0 || text(value, max); +} +function isRecord4(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + // packages/core/dist/text.js var DIAGNOSTIC_TERM_LIMIT = 48; var DIAGNOSTIC_SPEC_LIMIT = 80; @@ -4452,7 +4885,7 @@ function removeAnnotation(store, id) { return { annotationStoreVersion: 1, annotations }; } function validateAnnotationStore(candidate) { - if (!isRecord3(candidate) || candidate.annotationStoreVersion !== 1 || !Array.isArray(candidate.annotations)) { + if (!isRecord5(candidate) || candidate.annotationStoreVersion !== 1 || !Array.isArray(candidate.annotations)) { throw new Error("Unsupported or invalid FixMap annotation store. Expected annotationStoreVersion 1."); } const ids = /* @__PURE__ */ new Set(); @@ -4517,7 +4950,7 @@ function normalizeAnnotationInput(input) { }; } function validateAnnotation(candidate) { - if (!isRecord3(candidate) || typeof candidate.id !== "string" || !ID.test(candidate.id) || typeof candidate.note !== "string" || typeof candidate.createdAt !== "string") { + if (!isRecord5(candidate) || typeof candidate.id !== "string" || !ID.test(candidate.id) || typeof candidate.note !== "string" || typeof candidate.createdAt !== "string") { throw new Error("Invalid FixMap annotation record."); } const normalized = normalizeAnnotationInput({ @@ -4536,7 +4969,7 @@ function validateAnnotation(candidate) { throw new Error(`Annotation ${candidate.id} does not match its content identity.`); } function validateScope(candidate) { - if (!isRecord3(candidate) || typeof candidate.kind !== "string") + if (!isRecord5(candidate) || typeof candidate.kind !== "string") throw new Error("Annotation scope is invalid."); if (candidate.kind === "file") { return { kind: "file", path: validateRelativePath(String(candidate.path ?? ""), "annotation file") }; @@ -4599,11 +5032,11 @@ function canonicalize(value) { if (Array.isArray(value)) return `[${value.map(canonicalize).join(",")}]`; if (value && typeof value === "object") { - return `{${Object.entries(value).filter(([, entry2]) => entry2 !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry2]) => `${JSON.stringify(key)}:${canonicalize(entry2)}`).join(",")}}`; + return `{${Object.entries(value).filter(([, entry2]) => entry2 !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([key2, entry2]) => `${JSON.stringify(key2)}:${canonicalize(entry2)}`).join(",")}}`; } return JSON.stringify(value); } -function isRecord3(value) { +function isRecord5(value) { return typeof value === "object" && value !== null && !Array.isArray(value); } function stableHash(value) { @@ -4827,9 +5260,9 @@ function documentHeadings(body) { } return headings; } -function parseExplicitTargets(text) { +function parseExplicitTargets(text2) { const targets = []; - const values = text.replace(/^\s*[-*]\s+/gm, "").replace(/^\[|\]$/g, "").split(/[\n,]/).map((value) => unquote(value.trim().replace(/^`|`$/g, ""))).filter(Boolean); + const values = text2.replace(/^\s*[-*]\s+/gm, "").replace(/^\[|\]$/g, "").split(/[\n,]/).map((value) => unquote(value.trim().replace(/^`|`$/g, ""))).filter(Boolean); for (const value of values) { const typed = /^(file|symbol|service|contract)\s*:\s*(.+)$/i.exec(value); const kind = typed?.[1]?.toLowerCase(); @@ -4856,10 +5289,10 @@ function literalPathTargets(body, knownPaths) { function normalizeTargets(targets) { const byKey = /* @__PURE__ */ new Map(); for (const target of targets) { - const key = target.kind === "file" ? `file:${target.path}` : target.kind === "symbol" ? `symbol:${target.path ?? ""}:${target.name}` : `${target.kind}:${target.name}`; - const existing = byKey.get(key); + const key2 = target.kind === "file" ? `file:${target.path}` : target.kind === "symbol" ? `symbol:${target.path ?? ""}:${target.name}` : `${target.kind}:${target.name}`; + const existing = byKey.get(key2); if (!existing || existing.evidence === "literal-mention") - byKey.set(key, { ...target }); + byKey.set(key2, { ...target }); } return [...byKey.values()].sort((left, right) => targetKey(left).localeCompare(targetKey(right))); } @@ -4871,10 +5304,10 @@ function targetKey(target) { return `${target.kind}:${target.name}`; } var MAX_DEPENDENCY_RULES = 100; -function parseDependencyRules(text) { - if (text === void 0 || !text.trim()) +function parseDependencyRules(text2) { + if (text2 === void 0 || !text2.trim()) return []; - const rules = text.split("\n").map((line) => line.trim()).filter(Boolean).map((line) => { + const rules = text2.split("\n").map((line) => line.trim()).filter(Boolean).map((line) => { const match = /^(.+?)\s*->\s*(.+)$/.exec(unquote(line.replace(/^`|`$/g, ""))); if (!match) throw new Error(`Invalid fixmap-deny-imports rule: ${line}`); @@ -4892,8 +5325,8 @@ function dependencyPattern(value) { } return pattern; } -function parseReferences(text) { - return [...new Set(text.split(/[\n,]/).map((value) => value.replace(/^\s*[-*]\s+/, "").trim()).filter(Boolean))].sort(); +function parseReferences(text2) { + return [...new Set(text2.split(/[\n,]/).map((value) => value.replace(/^\s*[-*]\s+/, "").trim()).filter(Boolean))].sort(); } function normalizeStatus(value) { const normalized = value?.toLowerCase().replace(/[*_`]/g, " ").trim() ?? ""; @@ -4944,9 +5377,9 @@ function normalizeProse(value, maximum) { function titleTerms(title) { return title.toLowerCase().match(/[a-z0-9][a-z0-9_-]{3,}/g)?.filter((term2) => !["decision", "record", "architecture", "using", "with"].includes(term2)) ?? []; } -function containsLiteralTerm(text, term2) { +function containsLiteralTerm(text2, term2) { const literal = term2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - return new RegExp(`(^|[^\\p{L}\\p{N}_-])${literal}(?=$|[^\\p{L}\\p{N}_-])`, "iu").test(text); + return new RegExp(`(^|[^\\p{L}\\p{N}_-])${literal}(?=$|[^\\p{L}\\p{N}_-])`, "iu").test(text2); } function validatePath(value) { const normalized = normalizePath2(value.trim()); @@ -4971,7 +5404,7 @@ function stableHash2(value) { } // packages/core/dist/architecture.js -var RULE_ID = /^[a-z0-9][a-z0-9._-]{0,63}$/; +var RULE_ID2 = /^[a-z0-9][a-z0-9._-]{0,63}$/; function parseArchitecturePolicy(input) { const sourcePath = validateRelativePath2(input.path, "architecture policy path"); if (!input.fingerprint.trim() || /[\0-\x20]/.test(input.fingerprint)) @@ -4982,7 +5415,7 @@ function parseArchitecturePolicy(input) { } catch { throw new Error(`${sourcePath} is not valid JSON.`); } - if (!isRecord4(parsed2) || parsed2.architecturePolicyVersion !== 1) { + if (!isRecord6(parsed2) || parsed2.architecturePolicyVersion !== 1) { throw new Error(`${sourcePath} must declare architecturePolicyVersion 1.`); } const policy = { @@ -5130,12 +5563,12 @@ function contractRule(value, index) { }; } function ruleRecord(value, section2, index) { - if (!isRecord4(value)) + if (!isRecord6(value)) throw new Error(`${section2}[${index}] must be an object.`); return value; } function ruleId(value, section2, index) { - if (typeof value !== "string" || !RULE_ID.test(value)) + if (typeof value !== "string" || !RULE_ID2.test(value)) throw new Error(`${section2}[${index}] has an invalid id.`); return value; } @@ -5185,7 +5618,7 @@ function array(value) { throw new Error("Architecture policy sections must be arrays."); return value; } -function isRecord4(value) { +function isRecord6(value) { return typeof value === "object" && value !== null && !Array.isArray(value); } @@ -5770,6 +6203,8 @@ function renderMarkdownReport(report) { ...report.evidence.omittedItems > 0 ? ["", `${report.evidence.omittedItems} further evidence item${report.evidence.omittedItems === 1 ? " was" : "s were"} not about files in this report.`] : [], ...report.evidence.diagnostics.map((diagnostic) => `- **${diagnostic.severity}** ${markdownCode(diagnostic.provider)} ${diagnostic.code}: ${inlineProse(diagnostic.message)}`) ] : [], + ...report.sensitiveData ? renderSensitiveDataMarkdown(report.sensitiveData) : [], + ...report.supplyChain ? renderSupplyChainReportMarkdown(report.supplyChain) : [], ...report.policy ? [ "", "## Architecture Policy", @@ -5814,9 +6249,6 @@ function describeAnnotationScope(assessment) { return `service ${markdownCode(scope.name)}`; return `contract ${markdownCode(scope.name)}${scope.path ? ` in ${markdownCode(scope.path)}` : ""}`; } -function inlineProse(value) { - return value.replace(/\s+/g, " ").trim(); -} function listOrEmpty(lines) { return lines.length > 0 ? lines : ["- None found"]; } @@ -6095,7 +6527,7 @@ async function readIncrementalScanIndex(location) { return void 0; const entries = /* @__PURE__ */ new Map(); for (const entry2 of candidate.files) { - if (!isRecord5(entry2) || !isCachedRelativePath(entry2.path) || typeof entry2.fingerprint !== "string" || !/^(?:git|worktree):[a-f0-9]{40,64}$/i.test(entry2.fingerprint) || !isCachedRepoFile(entry2.file) || entry2.file.path !== entry2.path || entries.has(entry2.path)) { + if (!isRecord7(entry2) || !isCachedRelativePath(entry2.path) || typeof entry2.fingerprint !== "string" || !/^(?:git|worktree):[a-f0-9]{40,64}$/i.test(entry2.fingerprint) || !isCachedRepoFile(entry2.file) || entry2.file.path !== entry2.path || entries.has(entry2.path)) { return void 0; } entries.set(entry2.path, entry2); @@ -6106,32 +6538,32 @@ async function readIncrementalScanIndex(location) { } } function isCachedHistory(candidate) { - if (!isRecord5(candidate) || !Array.isArray(candidate.commits) || typeof candidate.inspectedCommits !== "number" || !Number.isSafeInteger(candidate.inspectedCommits) || candidate.inspectedCommits < 0 || typeof candidate.skippedLargeCommits !== "number" || !Number.isSafeInteger(candidate.skippedLargeCommits) || candidate.skippedLargeCommits < 0 || typeof candidate.shallow !== "boolean" || typeof candidate.truncated !== "boolean") { + if (!isRecord7(candidate) || !Array.isArray(candidate.commits) || typeof candidate.inspectedCommits !== "number" || !Number.isSafeInteger(candidate.inspectedCommits) || candidate.inspectedCommits < 0 || typeof candidate.skippedLargeCommits !== "number" || !Number.isSafeInteger(candidate.skippedLargeCommits) || candidate.skippedLargeCommits < 0 || typeof candidate.shallow !== "boolean" || typeof candidate.truncated !== "boolean") { return false; } return candidate.commits.every((commit) => { - if (!isRecord5(commit) || typeof commit.hash !== "string" || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(commit.hash) || typeof commit.committedAt !== "number" || !Number.isSafeInteger(commit.committedAt) || commit.committedAt < 0 || commit.author !== void 0 && (typeof commit.author !== "string" || !commit.author.trim() || commit.author.length > 200 || /[\0-\x1f\x7f]/.test(commit.author)) || !Array.isArray(commit.files)) + if (!isRecord7(commit) || typeof commit.hash !== "string" || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(commit.hash) || typeof commit.committedAt !== "number" || !Number.isSafeInteger(commit.committedAt) || commit.committedAt < 0 || commit.author !== void 0 && (typeof commit.author !== "string" || !commit.author.trim() || commit.author.length > 200 || /[\0-\x1f\x7f]/.test(commit.author)) || !Array.isArray(commit.files)) return false; return commit.files.every(isCachedRelativePath); }); } function isCachedRepoFile(candidate) { - if (!isRecord5(candidate)) + if (!isRecord7(candidate)) return false; const validSkipReason = candidate.textSampleSkipReason === "too-large" || candidate.textSampleSkipReason === "not-text" || candidate.textSampleSkipReason === "unreadable"; return isCachedRelativePath(candidate.path) && typeof candidate.contentFingerprint === "string" && /^(?:git|worktree):[a-f0-9]{40,64}$/i.test(candidate.contentFingerprint) && typeof candidate.extension === "string" && typeof candidate.sizeBytes === "number" && Number.isFinite(candidate.sizeBytes) && candidate.sizeBytes >= 0 && typeof candidate.isTest === "boolean" && typeof candidate.isSource === "boolean" && (candidate.kind === "code" || candidate.kind === "config" || candidate.kind === "documentation" || candidate.kind === "other") && typeof candidate.textSample === "string" && typeof candidate.textSampleComplete === "boolean" && (candidate.textSampleComplete && candidate.textSampleSkipReason === void 0 || !candidate.textSampleComplete && validSkipReason); } function isCachedPackageScript(candidate) { - if (!isRecord5(candidate)) + if (!isRecord7(candidate)) return false; return typeof candidate.name === "string" && candidate.name.trim().length > 0 && typeof candidate.command === "string" && (candidate.packageDir === "" || isCachedRelativePath(candidate.packageDir)) && (candidate.packageName === void 0 || typeof candidate.packageName === "string" && candidate.packageName.trim().length > 0); } function isCachedDiagnostic(candidate) { - if (!isRecord5(candidate)) + if (!isRecord7(candidate)) return false; return typeof candidate.code === "string" && candidate.code.trim().length > 0 && typeof candidate.message === "string" && candidate.message.trim().length > 0 && (candidate.severity === "info" || candidate.severity === "warning" || candidate.severity === "error") && (candidate.paths === void 0 || Array.isArray(candidate.paths) && candidate.paths.every(isCachedRelativePath)); } -function isRecord5(candidate) { +function isRecord7(candidate) { return typeof candidate === "object" && candidate !== null && !Array.isArray(candidate); } function isCachedRelativePath(candidate) { @@ -6576,7 +7008,7 @@ async function toRepoFile(absolutePath, relativePath, contentFingerprint, reusab sizeBytes: fileStat.size, isTest: isLanguageTestPath(relativePath, extension) || TEST_PATTERNS.some((pattern) => pattern.test(relativePath)), isSource, - kind: customSource ? "code" : classifyFile(relativePath, extension), + kind: customSource ? "code" : classifyFile2(relativePath, extension), textSample: sample.text, ...sample.searchText ? { searchTextSample: sample.searchText } : {}, textSampleComplete: sample.complete, @@ -6591,10 +7023,10 @@ async function resolveRealPath(absolutePath) { return absolutePath; } } -function extractScriptBlocks(text) { - const blocks = [...text.matchAll(SFC_SCRIPT_BLOCK)].map((match) => match[1] ?? ""); +function extractScriptBlocks(text2) { + const blocks = [...text2.matchAll(SFC_SCRIPT_BLOCK)].map((match) => match[1] ?? ""); const joined = blocks.join("\n").trim(); - return joined || text; + return joined || text2; } function sameFilesystemPath(left, right) { return process.platform === "win32" ? left.toLowerCase() === right.toLowerCase() : left === right; @@ -6618,7 +7050,7 @@ function summarizeSkippedScope(paths) { const scope = path.includes("/") && head ? `${head}/` : "the repository root"; counts.set(scope, (counts.get(scope) ?? 0) + 1); } - return [...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, 3).map(([scope, count]) => `${scope} (${count.toLocaleString()})`).join(", "); + return [...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, 3).map(([scope, count2]) => `${scope} (${count2.toLocaleString()})`).join(", "); } async function readPackageScripts(root, files, diagnostics) { const manifests = files.filter((file) => file.path === "package.json" || file.path.endsWith("/package.json")); @@ -6933,7 +7365,7 @@ function packageManagersForPaths(paths) { managers.push("npm"); return managers; } -function classifyFile(path, extension) { +function classifyFile2(path, extension) { const lower = path.toLowerCase(); const conventionalKind = classifyConventionalTextFile(path); if (conventionalKind) @@ -6962,13 +7394,13 @@ async function readTextSample(path, sizeBytes) { if (bytes.includes(0)) { return { text: "", complete: false, skipReason: "not-text" }; } - const text = bytes.toString("utf8"); + const text2 = bytes.toString("utf8"); if (sizeBytes <= MAX_TEXT_SAMPLE_BYTES) - return { text, complete: true }; + return { text: text2, complete: true }; const searchBytes = await readDistributedWindows(path, sizeBytes); if (searchBytes.includes(0)) return { text: "", complete: false, skipReason: "not-text" }; - return { text, searchText: searchBytes.toString("utf8"), complete: false, skipReason: "too-large" }; + return { text: text2, searchText: searchBytes.toString("utf8"), complete: false, skipReason: "too-large" }; } catch { return { text: "", complete: false, skipReason: "unreadable" }; } @@ -7076,7 +7508,7 @@ async function scanCommit(repoRoot, requestedRef, commit) { ...ignoreBytes ? { ignoreFile: ignoreBytes.toString("utf8") } : {} }; } -function isRecord6(value) { +function isRecord8(value) { return typeof value === "object" && value !== null && !Array.isArray(value); } function historicalPackageScripts(files, diagnostics) { @@ -7087,7 +7519,7 @@ function historicalPackageScripts(files, diagnostics) { const parsed2 = JSON.parse(manifest.textSample.replace(/^/, "")); const packageDir = manifest.path.includes("/") ? manifest.path.slice(0, manifest.path.lastIndexOf("/")) : ""; const packageName = typeof parsed2.name === "string" && parsed2.name.trim() ? parsed2.name.trim() : void 0; - const scripts = isRecord6(parsed2.scripts) ? parsed2.scripts : {}; + const scripts = isRecord8(parsed2.scripts) ? parsed2.scripts : {}; return Object.entries(scripts).flatMap(([name, command]) => typeof command === "string" ? [{ name, command, packageDir, ...packageName ? { packageName } : {} }] : []); } catch { diagnostics.push({ @@ -7245,7 +7677,7 @@ function safePath(path) { var KINDS = /* @__PURE__ */ new Set(["function", "method", "class", "interface", "type", "variable"]); var record = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value); var term = (value) => typeof value === "string" && value.length > 0 && value.length <= 512 && !/[\x00-\x1f\x7f]/.test(value); -var fields = (value, allowed) => Object.keys(value).every((key) => allowed.includes(key)); +var fields = (value, allowed) => Object.keys(value).every((key2) => allowed.includes(key2)); var repoPath = (value) => typeof value === "string" && value.length > 0 && value.length <= 4096 && !/[\x00-\x1f\x7f\\:]/.test(value) && value.split("/").every((part) => part !== "" && part !== "." && part !== ".."); var MAX_RECORDED_FAILURES = 200; function validImports(value) { @@ -7259,12 +7691,12 @@ function createCustomLanguageContext(registry) { const failures = /* @__PURE__ */ new Map(); let failureCount = 0; const recordFailure = (failure) => { - const key = [failure.adapter, failure.path, failure.code].join("\0"); - if (failures.has(key)) + const key2 = [failure.adapter, failure.path, failure.code].join("\0"); + if (failures.has(key2)) return; failureCount += 1; if (failures.size < MAX_RECORDED_FAILURES) - failures.set(key, failure); + failures.set(key2, failure); }; return Object.freeze({ /** Detached, sorted, bounded failures; total counts every distinct failure seen. */ @@ -7306,25 +7738,25 @@ function createCustomLanguageContext(registry) { const adapter = registry.customForExtension(extension); if (!adapter) return { status: "unsupported" }; - const text = file.searchTextSample ?? file.textSample; + const text2 = file.searchTextSample ?? file.textSample; const previous = cache.get(file); - if (previous?.path === file.path && previous.extension === extension && previous.text === text) + if (previous?.path === file.path && previous.extension === extension && previous.text === text2) return structuredClone(previous.result); let result; - if (text.length > 64e3 || file.path.length > 4096 || !file.path || /[\x00-\x1f\x7f\\:]/.test(file.path) || file.path.split("/").some((part) => !part || part === "." || part === "..")) { + if (text2.length > 64e3 || file.path.length > 4096 || !file.path || /[\x00-\x1f\x7f\\:]/.test(file.path) || file.path.split("/").some((part) => !part || part === "." || part === "..")) { result = { status: "failed", adapter: adapter.id, code: "adapter-input-invalid" }; } else { try { - const rawImports = adapter.extractImports(text); + const rawImports = adapter.extractImports(text2); if (!validImports(rawImports)) throw new Error(); const imports = structuredClone(rawImports); - const rawDefinitions = adapter.extractDefinitions(text); - if (!validDefinitions(rawDefinitions, text.length)) + const rawDefinitions = adapter.extractDefinitions(text2); + if (!validDefinitions(rawDefinitions, text2.length)) throw new Error(); const definitions = structuredClone(rawDefinitions); const isTest = adapter.isTestPath(file.path); - if (!validImports(imports) || !validDefinitions(definitions, text.length) || typeof isTest !== "boolean") + if (!validImports(imports) || !validDefinitions(definitions, text2.length) || typeof isTest !== "boolean") throw new Error(); result = { status: "ok", facts: { adapter: adapter.id, version: adapter.version, imports, definitions, isTest } }; } catch { @@ -7334,7 +7766,7 @@ function createCustomLanguageContext(registry) { if (result.status === "failed" && repoPath(file.path)) { recordFailure({ adapter: adapter.id, path: file.path, code: result.code }); } - cache.set(file, { path: file.path, extension, text, result }); + cache.set(file, { path: file.path, extension, text: text2, result }); return structuredClone(result); } }); @@ -7452,7 +7884,7 @@ async function collectEvidence(providers, context, options = {}) { }; } function validateProviderResult(result) { - if (!isRecord7(result) || !Array.isArray(result.items) || !(result.relationships === void 0 || Array.isArray(result.relationships))) { + if (!isRecord9(result) || !Array.isArray(result.items) || !(result.relationships === void 0 || Array.isArray(result.relationships))) { return { success: false, message: "expected { items, relationships? } arrays" }; } const items = result.items; @@ -7484,7 +7916,7 @@ function validateProviderResult(result) { }; } function validateEvidenceItem(candidate) { - if (!isRecord7(candidate) || typeof candidate.id !== "string" || !LOCAL_ID.test(candidate.id)) + if (!isRecord9(candidate) || typeof candidate.id !== "string" || !LOCAL_ID.test(candidate.id)) return "an item has an invalid ID"; if (!isEvidenceKind(candidate.kind)) return `item ${candidate.id} has an invalid kind`; @@ -7501,7 +7933,7 @@ function validateEvidenceItem(candidate) { return void 0; } function validateRelationship(candidate, itemIds) { - if (!isRecord7(candidate) || typeof candidate.id !== "string" || !LOCAL_ID.test(candidate.id)) + if (!isRecord9(candidate) || typeof candidate.id !== "string" || !LOCAL_ID.test(candidate.id)) return "a relationship has an invalid ID"; if (typeof candidate.from !== "string" || !itemIds.has(candidate.from) || typeof candidate.to !== "string" || !itemIds.has(candidate.to)) return `relationship ${candidate.id} references an unknown item`; @@ -7514,7 +7946,7 @@ function validateRelationship(candidate, itemIds) { return void 0; } function isEvidenceSubject(candidate) { - if (!isRecord7(candidate)) + if (!isRecord9(candidate)) return false; if (candidate.kind === "repository") return typeof candidate.repository === "string" && candidate.repository.trim().length > 0; @@ -7534,9 +7966,9 @@ function isSafeRelativePath(path) { return path.replace(/\\/g, "/").split("/").every((segment) => segment.length > 0 && segment !== "." && segment !== ".."); } function isScalarMetadata(candidate) { - if (!isRecord7(candidate) || Object.keys(candidate).length > 50) + if (!isRecord9(candidate) || Object.keys(candidate).length > 50) return false; - return Object.entries(candidate).every(([key, value]) => key.length > 0 && key.length <= 100 && (typeof value === "string" && value.length <= 1e3 || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value))); + return Object.entries(candidate).every(([key2, value]) => key2.length > 0 && key2.length <= 100 && (typeof value === "string" && value.length <= 1e3 || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value))); } function isEvidenceKind(candidate) { return ["structure", "semantic", "history", "human-intent", "contract", "runtime", "security", "ownership", "custom"].includes(String(candidate)); @@ -7572,7 +8004,7 @@ function withTimeout(promise, timeoutMs, controller) { }); }); } -function isRecord7(candidate) { +function isRecord9(candidate) { return typeof candidate === "object" && candidate !== null && !Array.isArray(candidate); } @@ -7580,12 +8012,8 @@ function isRecord7(candidate) { var MAX_REPORT_EVIDENCE_ITEMS = 50; async function attachReportEvidence(report, repo, sources, context) { const collected = await collectEvidence(sources.map((source) => source.provider), { repo, issueText: context.issueText, diffText: repo.diffText ?? "" }, { allowNetwork: false, allowCodeExecution: false, ...context.now ? { now: context.now } : {} }); - const reportPaths = /* @__PURE__ */ new Set([ - ...report.contextFiles.map((file) => file.path), - ...(report.impact?.files ?? []).map((file) => file.path), - ...report.changedFiles - ]); - const relevant = collected.items.filter((item) => item.subjects.some((subject) => (subject.kind === "file" || subject.kind === "symbol" || subject.kind === "contract") && "path" in subject && typeof subject.path === "string" && reportPaths.has(subject.path))); + const paths = reportPaths(report); + const relevant = collected.items.filter((item) => item.subjects.some((subject) => (subject.kind === "file" || subject.kind === "symbol" || subject.kind === "contract") && "path" in subject && typeof subject.path === "string" && paths.has(subject.path))); const items = relevant.slice(0, MAX_REPORT_EVIDENCE_ITEMS); return { evidenceVersion: 1, @@ -7600,6 +8028,13 @@ async function attachReportEvidence(report, repo, sources, context) { diagnostics: collected.diagnostics }; } +function reportPaths(report) { + return /* @__PURE__ */ new Set([ + ...report.contextFiles.map((file) => file.path), + ...(report.impact?.files ?? []).map((file) => file.path), + ...report.changedFiles + ]); +} // packages/core/dist/plan.js async function buildFixMapReport(input) { @@ -7632,6 +8067,12 @@ async function buildFixMapAnalysis(input) { if (input.evidenceSources && input.evidenceSources.length > 0) { report.evidence = await attachReportEvidence(report, analyzedRepo, input.evidenceSources, { issueText: input.issueText ?? "" }); } + if (input.sensitiveData) { + report.sensitiveData = buildReportSensitiveData(analyzedRepo, reportPaths(report)); + } + if (input.supplyChain) { + report.supplyChain = buildReportSupplyChain(input.supplyChain.bundle, input.supplyChain.documentSha256, reportPaths(report)); + } if (input.languageRegistry && languageContext) { report.languageAdapters = input.languageRegistry.customAdapters.map((adapter) => ({ id: adapter.id, @@ -7746,7 +8187,7 @@ function classifyCustomTests(repo, context) { } // packages/core/dist/verify.js -function verifyPlan(report, repo) { +function verifyPlan(report, repo, options = {}) { const changed = repo.changedFiles; const findings = []; const fileByPath = new Map(repo.files.map((file) => [file.path, file])); @@ -7888,13 +8329,18 @@ function verifyPlan(report, repo) { message: `.fixmap/policy.json was not applied: ${error instanceof Error ? error.message : String(error)}` }); } + const sensitiveData = options.sensitiveData ? buildReportSensitiveData(repo, /* @__PURE__ */ new Set([...reportPaths(report), ...changed, ...impact.files.map((file) => file.path)]), { compareWithDiff: true }) : void 0; + const sensitiveFinding = sensitiveData ? sensitiveDataVerifyFinding(sensitiveData) : void 0; + if (sensitiveFinding) + findings.push(sensitiveFinding); return { summary: buildVerifySummary(changed.length, findings), changedFiles: changed, findings, diagnostics: repo.diagnostics, impact, - narrative: buildVerifyNarrative(report, changed, changedSource, changedTests, impact, newRisks, policy) + narrative: buildVerifyNarrative(report, changed, changedSource, changedTests, impact, newRisks, policy), + ...sensitiveData ? { sensitiveData } : {} }; } function policyVerifyFinding(finding) { @@ -8039,6 +8485,8 @@ function renderVerifyMarkdown(result) { lines.push("", "## Recalculated Impact", ""); lines.push(...result.impact.files.length > 0 ? result.impact.files.map((file) => `- ${markdownCode(file.path)} (${file.confidence} confidence): ${file.evidence.map((entry2) => entry2.reason).join("; ")}`) : ["- None found"]); } + if (result.sensitiveData) + lines.push(...renderSensitiveDataMarkdown(result.sensitiveData)); return `${lines.join("\n")} `; } @@ -8445,23 +8893,23 @@ function toLines(content) { break; } const leading = /^[ \t]*/.exec(raw)[0]; - const text = stripComment(raw.slice(leading.length)).trimEnd(); - if (!text) { + const text2 = stripComment(raw.slice(leading.length)).trimEnd(); + if (!text2) { 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 }); + lines.push({ number: index + 1, indent: leading.length, text: text2, raw }); } return lines; } -function stripComment(text) { - if (text.startsWith("#")) +function stripComment(text2) { + if (text2.startsWith("#")) return ""; let quote; - for (let index = 0; index < text.length; index += 1) { - const char = text[index]; + for (let index = 0; index < text2.length; index += 1) { + const char = text2[index]; if (quote) { if (quote === '"' && char === "\\") index += 1; @@ -8469,12 +8917,12 @@ function stripComment(text) { quote = void 0; continue; } - if ((char === '"' || char === "'") && (index === 0 || /[\s:\[\]{},-]/.test(text[index - 1]))) + if ((char === '"' || char === "'") && (index === 0 || /[\s:\[\]{},-]/.test(text2[index - 1]))) quote = char; - else if (char === "#" && /\s/.test(text[index - 1] ?? "")) - return text.slice(0, index); + else if (char === "#" && /\s/.test(text2[index - 1] ?? "")) + return text2.slice(0, index); } - return text; + return text2; } function current(state) { while (state.index < state.lines.length && state.lines[state.index].indent < 0) @@ -8494,8 +8942,8 @@ function parseNode(state, indent, depth5) { state.index += 1; return parseInlineValue(line, line.text, state, line.indent, depth5); } -function isSequenceItem(text) { - return text === "-" || text.startsWith("- "); +function isSequenceItem(text2) { + return text2 === "-" || text2.startsWith("- "); } function parseSequence(state, indent, depth5) { const values = []; @@ -8527,21 +8975,21 @@ function parseMapping(state, indent, depth5) { const split = splitKey(line.text); if (!split) fail(line, "expected a mapping key"); - const key = parseKey(line, split.key); - if (key === "<<") + const key2 = parseKey(line, split.key); + if (key2 === "<<") fail(line, "merge keys are not supported"); - if (Object.prototype.hasOwnProperty.call(result, key)) - fail(line, `duplicate key ${JSON.stringify(key)}`); + if (Object.prototype.hasOwnProperty.call(result, key2)) + fail(line, `duplicate key ${JSON.stringify(key2)}`); 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); + result[key2] = parseNode(state, next.indent, depth5 + 1); } else { - result[key] = null; + result[key2] = null; } } else { - result[key] = parseInlineValue(line, split.value, state, indent, depth5); + result[key2] = parseInlineValue(line, split.value, state, indent, depth5); } } const after = current(state); @@ -8549,24 +8997,24 @@ function parseMapping(state, indent, depth5) { fail(after, "unexpected indentation in a mapping"); return result; } -function splitKey(text) { - if (isSequenceItem(text) || text.startsWith("{") || text.startsWith("[")) +function splitKey(text2) { + if (isSequenceItem(text2) || text2.startsWith("{") || text2.startsWith("[")) return void 0; let index = 0; - if (text.startsWith('"') || text.startsWith("'")) { - const end = closingQuote(text, 0); + if (text2.startsWith('"') || text2.startsWith("'")) { + const end = closingQuote(text2, 0); if (end === -1) return void 0; index = end + 1; - const rest = text.slice(index); + const rest = text2.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() }; + return { key: text2.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() }; + for (; index < text2.length; index += 1) { + if (text2[index] === ":" && (index + 1 === text2.length || /\s/.test(text2[index + 1]))) { + return { key: text2.slice(0, index).trimEnd(), value: text2.slice(index + 1).trim() }; } } return void 0; @@ -8586,43 +9034,43 @@ function parseInlineValue(line, value, state, parentIndent, depth5) { if (/^[|>]/.test(value)) return parseBlockScalar(line, value, state, parentIndent); if (value.startsWith("{") || value.startsWith("[")) { - let text2 = value; - while (!flowBalanced(text2)) { + let text3 = value; + while (!flowBalanced(text3)) { const next = current(state); if (!next || next.indent <= parentIndent) fail(line, "unterminated flow collection"); - text2 += ` ${next.text}`; + text3 += ` ${next.text}`; state.index += 1; } - const parser = { text: text2, index: 0, line }; + const parser = { text: text3, index: 0, line }; const result = parseFlowValue(parser, depth5); skipSpace(parser); - if (parser.index !== text2.length) + if (parser.index !== text3.length) fail(line, "unexpected content after a flow collection"); return result; } if (value.startsWith('"') || value.startsWith("'")) { - let text2 = value; - while (closingQuote(text2, 0) === -1) { + let text3 = value; + while (closingQuote(text3, 0) === -1) { const next = current(state); if (!next) fail(line, "unterminated quoted scalar"); - text2 += ` ${next.raw.trim()}`; + text3 += ` ${next.raw.trim()}`; state.index += 1; } - const end = closingQuote(text2, 0); - if (text2.slice(end + 1).trim()) + const end = closingQuote(text3, 0); + if (text3.slice(end + 1).trim()) fail(line, "unexpected content after a quoted scalar"); - return parseQuoted(line, text2); + return parseQuoted(line, text3); } - let text = value; + let text2 = 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}`; + text2 += ` ${next.text}`; state.index += 1; } - return resolvePlain(text); + return resolvePlain(text2); } function parseBlockScalar(line, header, state, parentIndent) { const match = /^([|>])([+-]?)(\d?)([+-]?)$/.exec(header.trim()); @@ -8649,10 +9097,10 @@ function parseBlockScalar(line, header, state, parentIndent) { } while (collected.length > 0 && collected.at(-1) === "" && chomping !== "+") collected.pop(); - let text = folded ? foldLines(collected) : collected.join("\n"); + let text2 = folded ? foldLines(collected) : collected.join("\n"); if (chomping !== "-" && collected.length > 0) - text += "\n"; - return text; + text2 += "\n"; + return text2; } function foldLines(lines) { let result = ""; @@ -8672,8 +9120,8 @@ function foldLines(lines) { } return result; } -function resolvePlain(text) { - const value = text.trim(); +function resolvePlain(text2) { + const value = text2.trim(); if (value === "" || value === "~" || /^(?:null|Null|NULL)$/.test(value)) return null; if (/^(?:true|True|TRUE)$/.test(value)) @@ -8688,15 +9136,15 @@ function resolvePlain(text) { 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] === "\\") { +function closingQuote(text2, start) { + const quote = text2[start]; + for (let index = start + 1; index < text2.length; index += 1) { + if (quote === '"' && text2[index] === "\\") { index += 1; continue; } - if (text[index] === quote) { - if (quote === "'" && text[index + 1] === "'") { + if (text2[index] === quote) { + if (quote === "'" && text2[index + 1] === "'") { index += 1; continue; } @@ -8705,12 +9153,12 @@ function closingQuote(text, start) { } return -1; } -function parseQuoted(line, text) { - const end = closingQuote(text, 0); +function parseQuoted(line, text2) { + const end = closingQuote(text2, 0); if (end === -1) fail(line, "unterminated quoted scalar"); - const body = text.slice(1, end); - if (text[0] === "'") + const body = text2.slice(1, end); + if (text2[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) @@ -8721,11 +9169,11 @@ function parseQuoted(line, text) { return simple[escape]; }); } -function flowBalanced(text) { +function flowBalanced(text2) { let depth5 = 0; let quote; - for (let index = 0; index < text.length; index += 1) { - const char = text[index]; + for (let index = 0; index < text2.length; index += 1) { + const char = text2[index]; if (quote) { if (quote === '"' && char === "\\") index += 1; @@ -8804,19 +9252,19 @@ function parseFlowMapping(parser, depth5) { 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 === "<<") + const key2 = keyValue === null ? "" : String(keyValue); + if (key2 === "<<") fail(parser.line, "merge keys are not supported"); - if (Object.prototype.hasOwnProperty.call(result, key)) - fail(parser.line, `duplicate key ${JSON.stringify(key)}`); + if (Object.prototype.hasOwnProperty.call(result, key2)) + fail(parser.line, `duplicate key ${JSON.stringify(key2)}`); 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); + result[key2] = next === "," || next === "}" ? null : parseFlowValue(parser, depth5); } else { - result[key] = null; + result[key2] = null; } skipSpace(parser); const char = parser.text[parser.index]; @@ -8905,13 +9353,13 @@ function parseContract(source) { throw error; return parseFailed(source, `YAML ${error.message}.`); } - if (isRecord8(document)) { - for (const key of ["openapi", "swagger", "asyncapi"]) { - if (typeof document[key] !== "number") + if (isRecord10(document)) { + for (const key2 of ["openapi", "swagger", "asyncapi"]) { + if (typeof document[key2] !== "number") continue; - const written = new RegExp(`^${key}\\s*:\\s*([^\\s#]+)`, "m").exec(source.content)?.[1]; + const written = new RegExp(`^${key2}\\s*:\\s*([^\\s#]+)`, "m").exec(source.content)?.[1]; if (written) - document[key] = written; + document[key2] = written; } const structured = parsedStructured(source, document); if (structured.surface || structured.diagnostic) @@ -8937,7 +9385,7 @@ function parsedStructured(source, document) { const asyncapi = specVersion(document.asyncapi); if (asyncapi) return parsed(source, "asyncapi", { ...parseAsyncApiJson(document), version: asyncapi }); - if (typeof document.$schema === "string" || isRecord8(document.properties)) { + if (typeof document.$schema === "string" || isRecord10(document.properties)) { return parsed(source, "json-schema", { ...parseJsonSchema(document), ...typeof document.$schema === "string" ? { version: document.$schema } : {} @@ -9008,7 +9456,7 @@ function parseAsyncApiJson(root) { for (const [channel, channelValue] of Object.entries(recordValue(root.channels))) { const channelRecord = recordValue(channelValue); for (const operation of ["publish", "subscribe"]) { - if (!isRecord8(channelRecord[operation])) + if (!isRecord10(channelRecord[operation])) continue; entries.push(entry(`operation:${operation}:${channel}`, "operation", `${operation} ${channel}`)); } @@ -9108,8 +9556,8 @@ function parseMigration(content) { } return { entries }; } -function entry(key, role, signature, required = false) { - return { key, role, signature: signature.trim(), required }; +function entry(key2, role, signature, required = false) { + return { key: key2, role, signature: signature.trim(), required }; } function normalizeEntries(entries) { const byKey = /* @__PURE__ */ new Map(); @@ -9146,17 +9594,17 @@ function titleFromRoot(root) { return typeof title === "string" && title.trim() ? { name: title.trim() } : {}; } function recordValue(value) { - return isRecord8(value) ? value : {}; + return isRecord10(value) ? value : {}; } function parseJson(content) { try { const parsed2 = JSON.parse(content); - return isRecord8(parsed2) ? parsed2 : void 0; + return isRecord10(parsed2) ? parsed2 : void 0; } catch { return void 0; } } -function isRecord8(value) { +function isRecord10(value) { return typeof value === "object" && value !== null && !Array.isArray(value); } function stableHash3(value) { @@ -9431,7 +9879,7 @@ function validateFixMapReport(candidate, label) { } const versioned = record3.reportVersion === 1; const contextFiles = candidate.contextFiles; - const unsafeContextPath = contextFiles.findIndex((file) => isRecord9(file) && typeof file.path === "string" && file.path.trim().length > 0 && !isRepositoryRelativePath(file.path)); + const unsafeContextPath = contextFiles.findIndex((file) => isRecord11(file) && typeof file.path === "string" && file.path.trim().length > 0 && !isRepositoryRelativePath(file.path)); if (unsafeContextPath !== -1) { const path = contextFiles[unsafeContextPath].path; return { @@ -9440,7 +9888,7 @@ function validateFixMapReport(candidate, label) { }; } const invalid = contextFiles.findIndex((file) => { - if (!isRecord9(file)) + if (!isRecord11(file)) return true; const ranked = file; if (!isRepositoryRelativePath(ranked.path)) @@ -9483,7 +9931,7 @@ function validateFixMapReport(candidate, label) { } const testRoutes = record3.testRoutes; const invalidRoute = testRoutes.findIndex((route) => { - if (!isRecord9(route)) + if (!isRecord11(route)) return true; return typeof route.command !== "string" || !route.command.trim() || !isRepositoryRelativePathArray(route.relatedFiles) || (versioned || route.kind !== void 0) && route.kind !== "test" && route.kind !== "validation" || (versioned || route.reason !== void 0) && typeof route.reason !== "string"; }); @@ -9495,7 +9943,7 @@ function validateFixMapReport(candidate, label) { } const risks = record3.risks; const invalidRisk = risks.findIndex((risk) => { - if (!isRecord9(risk)) + if (!isRecord11(risk)) return true; return typeof risk.area !== "string" || !risk.area.trim() || (versioned || risk.reason !== void 0) && typeof risk.reason !== "string" || (versioned || risk.severity !== void 0) && risk.severity !== "low" && risk.severity !== "medium" && risk.severity !== "high"; }); @@ -9507,14 +9955,14 @@ function validateFixMapReport(candidate, label) { } if (record3.impact !== void 0) { const impact = record3.impact; - const history = isRecord9(impact) ? impact.history : void 0; - if (!isRecord9(impact) || !isRepositoryRelativePathArray(impact.seeds) || !Array.isArray(impact.files) || !isRepositoryRelativePathArray(impact.inspectionOrder) || !isRecord9(history) || typeof history.available !== "boolean" || typeof history.eligibleCommits !== "number" || !Number.isSafeInteger(history.eligibleCommits) || history.eligibleCommits < 0 || typeof history.shallow !== "boolean" || typeof history.truncated !== "boolean") { + const history = isRecord11(impact) ? impact.history : void 0; + if (!isRecord11(impact) || !isRepositoryRelativePathArray(impact.seeds) || !Array.isArray(impact.files) || !isRepositoryRelativePathArray(impact.inspectionOrder) || !isRecord11(history) || typeof history.available !== "boolean" || typeof history.eligibleCommits !== "number" || !Number.isSafeInteger(history.eligibleCommits) || history.eligibleCommits < 0 || typeof history.shallow !== "boolean" || typeof history.truncated !== "boolean") { return { success: false, message: `${label} has an invalid impact graph envelope.` }; } const invalidImpact = impact.files.findIndex((file) => { - if (!isRecord9(file) || !isRepositoryRelativePath(file.path) || typeof file.score !== "number" || !Number.isFinite(file.score) || file.score < 0 || file.confidence !== "high" && file.confidence !== "medium" && file.confidence !== "low" || !Array.isArray(file.evidence)) + if (!isRecord11(file) || !isRepositoryRelativePath(file.path) || typeof file.score !== "number" || !Number.isFinite(file.score) || file.score < 0 || file.confidence !== "high" && file.confidence !== "medium" && file.confidence !== "low" || !Array.isArray(file.evidence)) return true; - return file.evidence.some((evidence) => !isRecord9(evidence) || !["imports", "imported-by", "co-change", "test-route"].includes(String(evidence.kind)) || !isRepositoryRelativePath(evidence.seed) || typeof evidence.reason !== "string" || !evidence.reason.trim() || evidence.occurrences !== void 0 && (!Number.isSafeInteger(evidence.occurrences) || evidence.occurrences < 0) || evidence.seedChanges !== void 0 && (!Number.isSafeInteger(evidence.seedChanges) || evidence.seedChanges < 0)); + return file.evidence.some((evidence) => !isRecord11(evidence) || !["imports", "imported-by", "co-change", "test-route"].includes(String(evidence.kind)) || !isRepositoryRelativePath(evidence.seed) || typeof evidence.reason !== "string" || !evidence.reason.trim() || evidence.occurrences !== void 0 && (!Number.isSafeInteger(evidence.occurrences) || evidence.occurrences < 0) || evidence.seedChanges !== void 0 && (!Number.isSafeInteger(evidence.seedChanges) || evidence.seedChanges < 0)); }); if (invalidImpact !== -1) { return { success: false, message: `${label} has an invalid impact.files entry at index ${invalidImpact}.` }; @@ -9523,12 +9971,12 @@ function validateFixMapReport(candidate, label) { const primaryPaths = new Set(contextFiles.map((file) => file.path)); const seenEdges = /* @__PURE__ */ new Set(); if (!Array.isArray(impact.primaryImports) || impact.primaryImports.some((edge) => { - if (!isRecord9(edge) || !isRepositoryRelativePath(edge.from) || !isRepositoryRelativePath(edge.to) || edge.from === edge.to || !primaryPaths.has(edge.from) || !primaryPaths.has(edge.to)) + if (!isRecord11(edge) || !isRepositoryRelativePath(edge.from) || !isRepositoryRelativePath(edge.to) || edge.from === edge.to || !primaryPaths.has(edge.from) || !primaryPaths.has(edge.to)) return true; - const key = JSON.stringify([edge.from, edge.to]); - if (seenEdges.has(key)) + const key2 = JSON.stringify([edge.from, edge.to]); + if (seenEdges.has(key2)) return true; - seenEdges.add(key); + seenEdges.add(key2); return false; })) { return { success: false, message: `${label} has invalid impact.primaryImports; each unique edge must join two distinct primary context paths.` }; @@ -9540,24 +9988,30 @@ function validateFixMapReport(candidate, label) { } if (record3.evidence !== void 0) { const evidence = record3.evidence; - const validSubject = (subject) => isRecord9(subject) && typeof subject.kind === "string" && (subject.path === void 0 || isRepositoryRelativePath(subject.path)); - if (!isRecord9(evidence) || evidence.evidenceVersion !== 1 || typeof evidence.collectedAt !== "string" || !Array.isArray(evidence.sources) || !evidence.sources.every((source) => isRecord9(source) && typeof source.provider === "string" && typeof source.version === "string" && (source.documentSha256 === void 0 || typeof source.documentSha256 === "string" && /^[a-f0-9]{64}$/.test(source.documentSha256))) || !Array.isArray(evidence.items) || evidence.items.length > 50 || !evidence.items.every((item) => isRecord9(item) && typeof item.id === "string" && typeof item.summary === "string" && typeof item.kind === "string" && ["high", "medium", "low"].includes(String(item.confidence)) && isRecord9(item.provider) && Array.isArray(item.subjects) && item.subjects.length > 0 && item.subjects.every(validSubject)) || !Number.isSafeInteger(evidence.omittedItems) || evidence.omittedItems < 0 || !Array.isArray(evidence.diagnostics)) { + const validSubject = (subject) => isRecord11(subject) && typeof subject.kind === "string" && (subject.path === void 0 || isRepositoryRelativePath(subject.path)); + if (!isRecord11(evidence) || evidence.evidenceVersion !== 1 || typeof evidence.collectedAt !== "string" || !Array.isArray(evidence.sources) || !evidence.sources.every((source) => isRecord11(source) && typeof source.provider === "string" && typeof source.version === "string" && (source.documentSha256 === void 0 || typeof source.documentSha256 === "string" && /^[a-f0-9]{64}$/.test(source.documentSha256))) || !Array.isArray(evidence.items) || evidence.items.length > 50 || !evidence.items.every((item) => isRecord11(item) && typeof item.id === "string" && typeof item.summary === "string" && typeof item.kind === "string" && ["high", "medium", "low"].includes(String(item.confidence)) && isRecord11(item.provider) && Array.isArray(item.subjects) && item.subjects.length > 0 && item.subjects.every(validSubject)) || !Number.isSafeInteger(evidence.omittedItems) || evidence.omittedItems < 0 || !Array.isArray(evidence.diagnostics)) { return { success: false, message: `${label} has invalid evidence; it needs evidenceVersion 1, sources, at most 50 items with safe repository-relative subjects, omittedItems, and diagnostics.` }; } } + if (record3.sensitiveData !== void 0 && !isReportSensitiveData(record3.sensitiveData)) { + return { success: false, message: `${label} has invalid sensitiveData; it needs sensitiveDataVersion 1, the fixmap-sensitive-data provider, counts, and at most 50 flows with safe paths, known categories, and rule ids.` }; + } + if (record3.supplyChain !== void 0 && !isReportSupplyChain(record3.supplyChain)) { + return { success: false, message: `${label} has invalid supplyChain; it needs supplyChainVersion 1, tool and bundle provenance, omittedFindings, and at most 50 findings with manifest paths.` }; + } if (record3.languageAdapters !== void 0) { const adapters = record3.languageAdapters; - if (!Array.isArray(adapters) || adapters.length > 32 || !adapters.every((adapter) => isRecord9(adapter) && Object.keys(adapter).every((key) => key === "id" || key === "version" || key === "extensions") && typeof adapter.id === "string" && /^custom:[a-z][a-z0-9-]{0,63}$/.test(adapter.id) && typeof adapter.version === "string" && /^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(adapter.version) && Array.isArray(adapter.extensions) && adapter.extensions.length > 0 && adapter.extensions.length <= 32 && adapter.extensions.every((extension) => typeof extension === "string" && /^\.[a-z0-9][a-z0-9_-]{0,15}$/.test(extension)))) { + if (!Array.isArray(adapters) || adapters.length > 32 || !adapters.every((adapter) => isRecord11(adapter) && Object.keys(adapter).every((key2) => key2 === "id" || key2 === "version" || key2 === "extensions") && typeof adapter.id === "string" && /^custom:[a-z][a-z0-9-]{0,63}$/.test(adapter.id) && typeof adapter.version === "string" && /^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(adapter.version) && Array.isArray(adapter.extensions) && adapter.extensions.length > 0 && adapter.extensions.length <= 32 && adapter.extensions.every((extension) => typeof extension === "string" && /^\.[a-z0-9][a-z0-9_-]{0,15}$/.test(extension)))) { return { success: false, message: `${label} has invalid languageAdapters; each entry needs a custom: id, a version, and lowercase extensions.` }; } } if (record3.annotations !== void 0) { const annotations = record3.annotations; - if (!isRecord9(annotations) || typeof annotations.asOf !== "string" || !Number.isFinite(Date.parse(annotations.asOf)) || !isRepositoryRelativePath(annotations.sourcePath) || typeof annotations.sourceFingerprint !== "string" || !/^(?:git|worktree):[a-f0-9]{40,64}$/i.test(annotations.sourceFingerprint) || !Array.isArray(annotations.entries)) { + if (!isRecord11(annotations) || typeof annotations.asOf !== "string" || !Number.isFinite(Date.parse(annotations.asOf)) || !isRepositoryRelativePath(annotations.sourcePath) || typeof annotations.sourceFingerprint !== "string" || !/^(?:git|worktree):[a-f0-9]{40,64}$/i.test(annotations.sourceFingerprint) || !Array.isArray(annotations.entries)) { return { success: false, message: `${label} has an invalid annotations envelope.` }; } const invalidAnnotation = annotations.entries.findIndex((assessment) => { - if (!isRecord9(assessment) || !isRecord9(assessment.annotation) || typeof assessment.message !== "string" || !["active", "expired", "missing-target", "renamed-target"].includes(String(assessment.status)) || assessment.suggestedPath !== void 0 && !isRepositoryRelativePath(assessment.suggestedPath)) + if (!isRecord11(assessment) || !isRecord11(assessment.annotation) || typeof assessment.message !== "string" || !["active", "expired", "missing-target", "renamed-target"].includes(String(assessment.status)) || assessment.suggestedPath !== void 0 && !isRepositoryRelativePath(assessment.suggestedPath)) return true; try { validateAnnotationStore({ annotationStoreVersion: 1, annotations: [assessment.annotation] }); @@ -9574,12 +10028,12 @@ function validateFixMapReport(candidate, label) { if (!Array.isArray(record3.decisions)) return { success: false, message: `${label} has invalid decisions; expected an array.` }; const invalidDecision = record3.decisions.findIndex((decision) => { - if (!isRecord9(decision) || typeof decision.id !== "string" || !/^decision:[a-f0-9]{16}$/.test(decision.id) || !isRepositoryRelativePath(decision.path) || typeof decision.title !== "string" || !decision.title.trim() || !["proposed", "accepted", "rejected", "deprecated", "superseded", "unknown"].includes(String(decision.status)) || typeof decision.decision !== "string" || !decision.decision.trim() || typeof decision.sourceFingerprint !== "string" || !/^(?:git|worktree):[a-f0-9]{40,64}$/i.test(decision.sourceFingerprint) || !Array.isArray(decision.targets) || !Array.isArray(decision.supersedes) || !decision.supersedes.every((value) => typeof value === "string" && value.trim()) || decision.date !== void 0 && (typeof decision.date !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(decision.date)) || decision.context !== void 0 && typeof decision.context !== "string" || decision.authoredStatus !== void 0 && (typeof decision.authoredStatus !== "string" || !decision.authoredStatus.trim() || decision.authoredStatus.length > 500 || decision.authoredStatus.includes("\0")) || decision.consequences !== void 0 && typeof decision.consequences !== "string" || decision.dependencyRules !== void 0 && (!Array.isArray(decision.dependencyRules) || !decision.dependencyRules.every((rule) => isRecord9(rule) && typeof rule.from === "string" && rule.from.trim() && typeof rule.deny === "string" && rule.deny.trim()))) + if (!isRecord11(decision) || typeof decision.id !== "string" || !/^decision:[a-f0-9]{16}$/.test(decision.id) || !isRepositoryRelativePath(decision.path) || typeof decision.title !== "string" || !decision.title.trim() || !["proposed", "accepted", "rejected", "deprecated", "superseded", "unknown"].includes(String(decision.status)) || typeof decision.decision !== "string" || !decision.decision.trim() || typeof decision.sourceFingerprint !== "string" || !/^(?:git|worktree):[a-f0-9]{40,64}$/i.test(decision.sourceFingerprint) || !Array.isArray(decision.targets) || !Array.isArray(decision.supersedes) || !decision.supersedes.every((value) => typeof value === "string" && value.trim()) || decision.date !== void 0 && (typeof decision.date !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(decision.date)) || decision.context !== void 0 && typeof decision.context !== "string" || decision.authoredStatus !== void 0 && (typeof decision.authoredStatus !== "string" || !decision.authoredStatus.trim() || decision.authoredStatus.length > 500 || decision.authoredStatus.includes("\0")) || decision.consequences !== void 0 && typeof decision.consequences !== "string" || decision.dependencyRules !== void 0 && (!Array.isArray(decision.dependencyRules) || !decision.dependencyRules.every((rule) => isRecord11(rule) && typeof rule.from === "string" && rule.from.trim() && typeof rule.deny === "string" && rule.deny.trim()))) return true; - if (decision.source !== void 0 && (!isRecord9(decision.source) || decision.source.kind !== "pull-request" || decision.source.verification !== "unverified-local-attribution" || !isDecisionPullRequestUrl(decision.source.url))) + if (decision.source !== void 0 && (!isRecord11(decision.source) || decision.source.kind !== "pull-request" || decision.source.verification !== "unverified-local-attribution" || !isDecisionPullRequestUrl(decision.source.url))) return true; return decision.targets.some((target) => { - if (!isRecord9(target) || !["explicit", "literal-mention"].includes(String(target.evidence))) + if (!isRecord11(target) || !["explicit", "literal-mention"].includes(String(target.evidence))) return true; if (target.kind === "file") return !isRepositoryRelativePath(target.path); @@ -9593,13 +10047,13 @@ function validateFixMapReport(candidate, label) { } if (record3.policy !== void 0) { const policy = record3.policy; - if (!isRecord9(policy) || typeof policy.policyFingerprint !== "string" || !/^(?:git|worktree):[a-f0-9]{40,64}$/i.test(policy.policyFingerprint) || !Array.isArray(policy.findings)) { + if (!isRecord11(policy) || typeof policy.policyFingerprint !== "string" || !/^(?:git|worktree):[a-f0-9]{40,64}$/i.test(policy.policyFingerprint) || !Array.isArray(policy.findings)) { return { success: false, message: `${label} has an invalid architecture policy envelope.` }; } const invalidPolicyFinding = policy.findings.findIndex((finding) => { - if (!isRecord9(finding) || !["boundary-violation", "required-test-missing", "review-required", "breaking-contract"].includes(String(finding.code)) || !["info", "warning", "error"].includes(String(finding.severity)) || typeof finding.ruleId !== "string" || !/^[a-z0-9][a-z0-9._-]{0,63}$/.test(finding.ruleId) || typeof finding.message !== "string" || !finding.message.trim() || !isRepositoryRelativePathArray(finding.paths) || !Array.isArray(finding.evidence)) + if (!isRecord11(finding) || !["boundary-violation", "required-test-missing", "review-required", "breaking-contract"].includes(String(finding.code)) || !["info", "warning", "error"].includes(String(finding.severity)) || typeof finding.ruleId !== "string" || !/^[a-z0-9][a-z0-9._-]{0,63}$/.test(finding.ruleId) || typeof finding.message !== "string" || !finding.message.trim() || !isRepositoryRelativePathArray(finding.paths) || !Array.isArray(finding.evidence)) return true; - return finding.evidence.some((evidence) => !isRecord9(evidence) || !["import", "changed-file", "test-pattern", "reviewer", "contract-change", "decision-record"].includes(String(evidence.kind)) || typeof evidence.detail !== "string" || !evidence.detail.trim() || evidence.path !== void 0 && !isRepositoryRelativePath(evidence.path) || evidence.relatedPath !== void 0 && !isRepositoryRelativePath(evidence.relatedPath)); + return finding.evidence.some((evidence) => !isRecord11(evidence) || !["import", "changed-file", "test-pattern", "reviewer", "contract-change", "decision-record"].includes(String(evidence.kind)) || typeof evidence.detail !== "string" || !evidence.detail.trim() || evidence.path !== void 0 && !isRepositoryRelativePath(evidence.path) || evidence.relatedPath !== void 0 && !isRepositoryRelativePath(evidence.relatedPath)); }); if (invalidPolicyFinding !== -1) { return { success: false, message: `${label} has an invalid architecture policy finding at index ${invalidPolicyFinding}.` }; @@ -9607,7 +10061,7 @@ function validateFixMapReport(candidate, label) { } const diagnostics = record3.diagnostics; const invalidDiagnostic = diagnostics.findIndex((diagnostic) => { - if (!isRecord9(diagnostic)) + if (!isRecord11(diagnostic)) return true; return typeof diagnostic.code !== "string" || !diagnostic.code.trim() || typeof diagnostic.message !== "string" || diagnostic.severity !== "info" && diagnostic.severity !== "warning" && diagnostic.severity !== "error" || diagnostic.paths !== void 0 && !isRepositoryRelativePathArray(diagnostic.paths); }); @@ -9619,21 +10073,21 @@ function validateFixMapReport(candidate, label) { } if (record3.analysis !== void 0) { const analysis = record3.analysis; - const grounding = isRecord9(analysis) ? analysis.grounding : void 0; - const specificity = isRecord9(grounding) ? grounding.specificity : void 0; + const grounding = isRecord11(analysis) ? analysis.grounding : void 0; + const specificity = isRecord11(grounding) ? grounding.specificity : void 0; if (specificity !== "anchored" && specificity !== "descriptive" && specificity !== "vague") { return { success: false, message: `${label} has invalid analysis.grounding.specificity; expected anchored, descriptive, or vague.` }; } - if (!isRecord9(analysis) || !isRecord9(grounding) || !Array.isArray(grounding.identifiers) || !isStringArray(grounding.unresolvedIdentifiers) || !isStringArray(grounding.partiallyResolvedIdentifiers) || !isStringArray(grounding.unverifiedIdentifiers) || typeof grounding.scanComplete !== "boolean" || !isRecord9(analysis.ranking) || !isNullableFiniteNumber(analysis.ranking.topScore) || !isNullableFiniteNumber(analysis.ranking.runnerUpScore) || !isNullableFiniteNumber(analysis.ranking.topGap) || typeof analysis.ranking.clustered !== "boolean" || typeof analysis.nextAction !== "string") { + if (!isRecord11(analysis) || !isRecord11(grounding) || !Array.isArray(grounding.identifiers) || !isStringArray(grounding.unresolvedIdentifiers) || !isStringArray(grounding.partiallyResolvedIdentifiers) || !isStringArray(grounding.unverifiedIdentifiers) || typeof grounding.scanComplete !== "boolean" || !isRecord11(analysis.ranking) || !isNullableFiniteNumber(analysis.ranking.topScore) || !isNullableFiniteNumber(analysis.ranking.runnerUpScore) || !isNullableFiniteNumber(analysis.ranking.topGap) || typeof analysis.ranking.clustered !== "boolean" || typeof analysis.nextAction !== "string") { return { success: false, message: `${label} has incomplete or invalid analysis grounding, ranking, or nextAction fields.` }; } - const invalidIdentifier = grounding.identifiers.findIndex((identifier) => !isRecord9(identifier) || typeof identifier.identifier !== "string" || !identifier.identifier.trim() || !isIdentifierStatus(identifier.status) || !isRepositoryRelativePathArray(identifier.matchedFiles)); + const invalidIdentifier = grounding.identifiers.findIndex((identifier) => !isRecord11(identifier) || typeof identifier.identifier !== "string" || !identifier.identifier.trim() || !isIdentifierStatus(identifier.status) || !isRepositoryRelativePathArray(identifier.matchedFiles)); if (invalidIdentifier !== -1) { return { success: false, @@ -9642,15 +10096,15 @@ function validateFixMapReport(candidate, label) { } if (analysis.retrievalRanking !== void 0) { const retrievalRanking = analysis.retrievalRanking; - if (!isRecord9(retrievalRanking) || !isNullableFiniteNumber(retrievalRanking.topFusionScore) || !isNullableFiniteNumber(retrievalRanking.runnerUpFusionScore) || !isNullableFiniteNumber(retrievalRanking.topGap)) { + if (!isRecord11(retrievalRanking) || !isNullableFiniteNumber(retrievalRanking.topFusionScore) || !isNullableFiniteNumber(retrievalRanking.runnerUpFusionScore) || !isNullableFiniteNumber(retrievalRanking.topGap)) { return { success: false, message: `${label} has invalid analysis.retrievalRanking fields.` }; } } } if (record3.retrieval !== void 0) { const retrieval = record3.retrieval; - const weights = isRecord9(retrieval) ? retrieval.weights : void 0; - if (!isRecord9(retrieval) || retrieval.mode !== "structural-lexical" && retrieval.mode !== "structural-lexical-semantic" || !isRecord9(weights) || !isPositiveFiniteNumber(weights.structural) || !isPositiveFiniteNumber(weights.lexical) || !isPositiveFiniteNumber(weights.semantic) || !isPositiveFiniteNumber(weights.reciprocalRankConstant)) { + const weights = isRecord11(retrieval) ? retrieval.weights : void 0; + if (!isRecord11(retrieval) || retrieval.mode !== "structural-lexical" && retrieval.mode !== "structural-lexical-semantic" || !isRecord11(weights) || !isPositiveFiniteNumber(weights.structural) || !isPositiveFiniteNumber(weights.lexical) || !isPositiveFiniteNumber(weights.semantic) || !isPositiveFiniteNumber(weights.reciprocalRankConstant)) { return { success: false, message: `${label} has an invalid retrieval envelope.` }; } if (retrieval.mode === "structural-lexical-semantic" && !isSemanticProvenance(retrieval.semantic)) { @@ -9662,7 +10116,7 @@ function validateFixMapReport(candidate, label) { } return { success: true, report: candidate }; } -function isRecord9(candidate) { +function isRecord11(candidate) { return typeof candidate === "object" && candidate !== null && !Array.isArray(candidate); } function isStringArray(candidate) { @@ -9671,13 +10125,6 @@ function isStringArray(candidate) { function isRepositoryRelativePathArray(candidate) { return Array.isArray(candidate) && candidate.every(isRepositoryRelativePath); } -function isRepositoryRelativePath(candidate) { - if (typeof candidate !== "string" || !candidate.trim() || candidate.includes("\0") || /^[\\/]/.test(candidate) || /^[A-Za-z]:/.test(candidate)) { - return false; - } - const segments = candidate.replace(/\\/g, "/").split("/"); - return segments.every((segment) => segment.length > 0 && segment !== "." && segment !== ".."); -} function isNullableFiniteNumber(candidate) { return candidate === null || typeof candidate === "number" && Number.isFinite(candidate); } @@ -9685,7 +10132,7 @@ function isIdentifierStatus(candidate) { return candidate === "exact-definition" || candidate === "exact-text" || candidate === "partial-definition" || candidate === "not-found" || candidate === "unverified"; } function isRetrievalSignal(candidate) { - if (!isRecord9(candidate)) + if (!isRecord11(candidate)) return false; const ranks = [candidate.structuralRank, candidate.lexicalRank, candidate.semanticRank]; if (ranks.every((rank) => rank === void 0)) @@ -9697,7 +10144,7 @@ function isRetrievalSignal(candidate) { return candidate.semanticSimilarity === void 0 || typeof candidate.semanticSimilarity === "number" && Number.isFinite(candidate.semanticSimilarity) && candidate.semanticSimilarity >= -1 && candidate.semanticSimilarity <= 1; } function isSemanticProvenance(candidate) { - if (!isRecord9(candidate)) + if (!isRecord11(candidate)) return false; return typeof candidate.id === "string" && candidate.id.trim().length > 0 && typeof candidate.version === "string" && candidate.version.trim().length > 0 && typeof candidate.model === "string" && candidate.model.trim().length > 0 && typeof candidate.artifactHash === "string" && /^[a-f0-9]{64}$/.test(candidate.artifactHash) && typeof candidate.runtime === "string" && candidate.runtime.trim().length > 0 && Number.isSafeInteger(candidate.dimensions) && Number(candidate.dimensions) > 0 && (candidate.normalization === "l2" || candidate.normalization === "none") && typeof candidate.local === "boolean" && typeof candidate.cacheKey === "string" && candidate.cacheKey.trim().length > 0 && Number.isSafeInteger(candidate.indexedFiles) && Number(candidate.indexedFiles) >= 0 && Number.isSafeInteger(candidate.truncatedFiles) && Number(candidate.truncatedFiles) >= 0; } @@ -9714,7 +10161,7 @@ var CAPABILITY_ID = /^[a-z0-9][a-z0-9._-]{0,63}$/; var MAX_CAPABILITIES = 256; var MAX_ANCHORS2 = 64; function validateCapabilityStore(candidate) { - if (!isRecord10(candidate) || candidate.capabilityStoreVersion !== 1 || typeof candidate.workspace !== "string" || typeof candidate.repository !== "string" || !Array.isArray(candidate.capabilities)) { + if (!isRecord12(candidate) || candidate.capabilityStoreVersion !== 1 || typeof candidate.workspace !== "string" || typeof candidate.repository !== "string" || !Array.isArray(candidate.capabilities)) { throw new Error("Capability store must be a version-1 object with workspace, repository, and capabilities fields."); } assertOnlyKeys(candidate, ["capabilityStoreVersion", "workspace", "repository", "capabilities"], "capability store"); @@ -9779,7 +10226,7 @@ function buildCapabilityMap(repo, input) { }; } function validateDefinition(candidate, index) { - if (!isRecord10(candidate)) + if (!isRecord12(candidate)) throw new Error(`Capability at index ${index} must be an object.`); assertOnlyKeys(candidate, ["id", "name", "anchors", "traversal"], `capability at index ${index}`); if (typeof candidate.id !== "string" || !CAPABILITY_ID.test(candidate.id)) { @@ -9794,10 +10241,10 @@ function validateDefinition(candidate, index) { const anchors = candidate.anchors.map((anchor, anchorIndex) => validateAnchor(anchor, candidate.id, anchorIndex)); const anchorKeys = /* @__PURE__ */ new Set(); for (const anchor of anchors) { - const key = `${anchor.operation}\0${anchor.path}`; - if (anchorKeys.has(key)) + const key2 = `${anchor.operation}\0${anchor.path}`; + if (anchorKeys.has(key2)) throw new Error(`Capability ${candidate.id} has a duplicate ${anchor.operation} anchor for ${anchor.path}.`); - anchorKeys.add(key); + anchorKeys.add(key2); } const traversal = candidate.traversal === void 0 ? void 0 : validateTraversal(candidate.traversal, candidate.id); return { @@ -9808,7 +10255,7 @@ function validateDefinition(candidate, index) { }; } function validateAnchor(candidate, capability, index) { - if (!isRecord10(candidate)) + if (!isRecord12(candidate)) throw new Error(`Capability ${capability} anchor at index ${index} must be an object.`); assertOnlyKeys(candidate, ["operation", "path"], `capability ${capability} anchor at index ${index}`); if (candidate.operation !== "touch" && candidate.operation !== "add") { @@ -9820,7 +10267,7 @@ function validateAnchor(candidate, capability, index) { return { operation: candidate.operation, path }; } function validateTraversal(candidate, capability) { - if (!isRecord10(candidate)) + if (!isRecord12(candidate)) throw new Error(`Capability ${capability} traversal must be an object.`); assertOnlyKeys(candidate, ["direction", "maxDepth", "maxNodes"], `capability ${capability} traversal`); const direction = candidate.direction; @@ -9855,11 +10302,11 @@ function copyDefinition(capability) { } function assertOnlyKeys(record3, allowed, label) { const allowedSet = new Set(allowed); - const unknown = Object.keys(record3).filter((key) => !allowedSet.has(key)); + const unknown = Object.keys(record3).filter((key2) => !allowedSet.has(key2)); if (unknown.length > 0) throw new Error(`${label} has unknown field${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}.`); } -function isRecord10(candidate) { +function isRecord12(candidate) { return typeof candidate === "object" && candidate !== null && !Array.isArray(candidate); } @@ -9943,15 +10390,15 @@ function compareEntities(previous, current2) { 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 (!current2.has(key)) - result.removed.push(key); - else if (previous.get(key) !== current2.get(key)) - result.modified.push(key); + for (const key2 of keys) { + if (!previous.has(key2)) + result.added.push(key2); + else if (!current2.has(key2)) + result.removed.push(key2); + else if (previous.get(key2) !== current2.get(key2)) + result.modified.push(key2); else - result.unchanged.push(key); + result.unchanged.push(key2); } return result; } @@ -9971,7 +10418,7 @@ function canonicalize2(value) { if (Array.isArray(value)) return `[${value.map(canonicalize2).join(",")}]`; if (value && typeof value === "object") { - return `{${Object.entries(value).filter(([, entry2]) => entry2 !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry2]) => `${JSON.stringify(key)}:${canonicalize2(entry2)}`).join(",")}}`; + return `{${Object.entries(value).filter(([, entry2]) => entry2 !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([key2, entry2]) => `${JSON.stringify(key2)}:${canonicalize2(entry2)}`).join(",")}}`; } return JSON.stringify(value); } @@ -9995,7 +10442,7 @@ async function runAnnotationAction(input, repoRoot, allowWrite) { } if (!record2(request) || !["list", "add", "remove"].includes(String(request.action))) throw new Error("annotation-request requires action: list, add, or remove."); const allowed = request.action === "list" ? ["action"] : request.action === "remove" ? ["action", "id"] : ["action", "scope", "note", "owner", "expiresAt"]; - if (Object.keys(request).some((key) => !allowed.includes(key))) throw new Error("annotation-request contains fields not allowed for this action."); + if (Object.keys(request).some((key2) => !allowed.includes(key2))) throw new Error("annotation-request contains fields not allowed for this action."); if (request.action === "list") return `${JSON.stringify(await readAnnotationStore(repoRoot), null, 2)} `; if (!allowWrite) throw new Error("Annotation mutation requires allow-annotation-write: true."); @@ -10014,7 +10461,7 @@ async function runAnnotationAction(input, repoRoot, allowWrite) { contract: ["kind", "name", "path"] }; const fields2 = typeof request.scope.kind === "string" && Object.hasOwn(scopeFields, request.scope.kind) ? scopeFields[request.scope.kind] : void 0; - if (!fields2 || Object.keys(request.scope).some((key) => !fields2.includes(key))) { + if (!fields2 || Object.keys(request.scope).some((key2) => !fields2.includes(key2))) { throw new Error("Annotation scope contains an unsupported kind or fields."); } const annotation = createAnnotation({ @@ -10314,7 +10761,7 @@ function renderCapabilityDiffSection(diff) { `- Head ${markdownCode2(diff.to.requestedRef)}: ${diff.to.state}`, `- Definition changed: ${diff.definitionChanged ? "yes" : "no"}` ]; - const categories = [ + const categories2 = [ ["Selected", diff.selected], ["Affected", diff.affected], ["Contracts", diff.contracts], @@ -10323,7 +10770,7 @@ function renderCapabilityDiffSection(diff) { ["Reviewers", diff.reviewers], ["Architecture findings", diff.architectureFindings] ]; - for (const [label, entry2] of categories) { + for (const [label, entry2] of categories2) { if (entry2.added.length + entry2.removed.length + entry2.modified.length === 0) continue; lines.push(`- ${label}: +${entry2.added.length} \u2212${entry2.removed.length} ~${entry2.modified.length}`); } @@ -10357,8 +10804,8 @@ function escapeMarkdown(value) { return value.replace(/[\\`*_[\]<>#|]/g, (character) => `\\${character}`); } function message(error) { - const text = (error instanceof Error ? error.message : String(error)).replace(/\s+/g, " ").trim(); - const bounded = text.length > 300 ? `${text.slice(0, 299)}\u2026` : text; + const text2 = (error instanceof Error ? error.message : String(error)).replace(/\s+/g, " ").trim(); + const bounded = text2.length > 300 ? `${text2.slice(0, 299)}\u2026` : text2; return /[.…]$/.test(bounded) ? bounded : `${bounded}.`; } @@ -10488,7 +10935,7 @@ var SCOPE_INPUTS = ["change-scope-touch", "change-scope-add", "capability"]; async function runAction(env = process.env, dependencies = {}) { const appendFile = dependencies.appendFile ?? ((path, contents) => appendFileSync(path, contents)); const readFile4 = dependencies.readFile ?? ((path) => readFileSync(path, "utf8")); - const stdout = dependencies.stdout ?? ((text) => process.stdout.write(text)); + const stdout = dependencies.stdout ?? ((text2) => process.stdout.write(text2)); if (readInput("mode", env)?.toLowerCase() === "annotate") { const incompatible = ["issue", "diff", "base", "head", "limit", "exclude", "report-path", "comment-author", ...SCOPE_INPUTS].filter((name) => readInput(name, env)); for (const name of ["working-tree", "include-untracked", "no-cache"]) { @@ -10777,9 +11224,9 @@ ${json.trimEnd()} `; } -function trimToBoundary(text) { - const lastBreak = text.lastIndexOf("\n\n"); - const trimmed = lastBreak > text.length / 2 ? text.slice(0, lastBreak) : text; +function trimToBoundary(text2) { + const lastBreak = text2.lastIndexOf("\n\n"); + const trimmed = lastBreak > text2.length / 2 ? text2.slice(0, lastBreak) : text2; const fences = (trimmed.match(/^```/gm) ?? []).length; return fences % 2 === 0 ? trimmed : `${trimmed} \`\`\``; diff --git a/packages/cli/src/cli-runner.ts b/packages/cli/src/cli-runner.ts index 7fea78c..65ec119 100644 --- a/packages/cli/src/cli-runner.ts +++ b/packages/cli/src/cli-runner.ts @@ -57,6 +57,8 @@ export type CliOptions = { noCache: boolean; semanticModelPath?: string | undefined; evidencePaths: string[]; + sensitiveData: boolean; + supplyChainPath?: string | undefined; unknownArgs: string[]; invalidValues: string[]; }; @@ -170,6 +172,8 @@ Options: --no-cache Bypass the exact git-state repository scan cache --semantic-model Use an existing local embedding model; never downloads or uploads source --evidence Attach a version-1 evidence bundle from another tool (repeatable; data only, never executed) + --sensitive-data Preview: Attach possible sensitive-data source-to-sink flows (locations and kinds only); with verify, flag flows the diff adds + --supply-chain Preview: Attach findings from a normalized scanner/SBOM bundle for packages in manifests among the report's files --repo Local path or public GitHub HTTPS URL (defaults to current directory) --ref Branch or tag to scan when --repo is a remote GitHub URL --at Preview: Rank against a local committed ref, read from Git objects without checkout @@ -665,7 +669,7 @@ export async function runCli(args: string[], dependencies: CliDependencies = {}) return 1; } if (options.command === "verify") { - const planOnly = [options.issueText && "--issue", options.issueFile && "--issue-file", options.comparePath && "--compare", options.limit !== undefined && "--limit", options.exclude.length > 0 && "--exclude", options.explainPath && "--explain", options.semanticModelPath && "--semantic-model", options.evidencePaths.length > 0 && "--evidence", options.atRef && "--at"].filter(Boolean); + const planOnly = [options.issueText && "--issue", options.issueFile && "--issue-file", options.comparePath && "--compare", options.limit !== undefined && "--limit", options.exclude.length > 0 && "--exclude", options.explainPath && "--explain", options.semanticModelPath && "--semantic-model", options.evidencePaths.length > 0 && "--evidence", options.supplyChainPath && "--supply-chain", options.atRef && "--at"].filter(Boolean); if (planOnly.length > 0) { stderr(`verify does not accept plan-only option(s): ${planOnly.join(", ")}.\n`); return 1; } const outputCollision = await describeOutputInputCollision(options); if (outputCollision) { stderr(`${outputCollision}\n`); return 1; } @@ -833,7 +837,9 @@ export async function runCli(args: string[], dependencies: CliDependencies = {}) exclude: options.exclude, internalExclude: localPlanArtifactExclusions(options), semanticModelPath: options.semanticModelPath, - evidencePaths: options.evidencePaths + evidencePaths: options.evidencePaths, + ...(options.sensitiveData ? { sensitiveData: true } : {}), + ...(options.supplyChainPath ? { supplyChainPath: options.supplyChainPath } : {}) }); } catch (error) { stderr(`${error instanceof Error ? error.message : String(error)}\n`); @@ -1081,6 +1087,7 @@ const SINGLE_VALUE_FLAGS = new Set([ "--repo", "--semantic-model", "--evidence", + "--supply-chain", "--format", "--report", "--explain", @@ -1089,7 +1096,7 @@ const SINGLE_VALUE_FLAGS = new Set([ "--fail-on", "--output" ]); -const BOOLEAN_FLAGS = new Set(["--working-tree", "--include-untracked", "--no-cache"]); +const BOOLEAN_FLAGS = new Set(["--working-tree", "--include-untracked", "--no-cache", "--sensitive-data"]); function hasStandaloneHelpFlag(args: string[]): boolean { for (let index = 1; index < args.length; index += 1) { @@ -1133,6 +1140,8 @@ export function parseArgs(args: string[]): CliOptions { let semanticModelPath: string | undefined; const exclude: string[] = []; const evidencePaths: string[] = []; + let sensitiveData = false; + let supplyChainPath: string | undefined; const unknownArgs: string[] = []; const invalidValues: string[] = []; const flagCounts = new Map(); @@ -1219,6 +1228,10 @@ export function parseArgs(args: string[]): CliOptions { consumeValue(); if (value?.trim()) evidencePaths.push(expandHomePath(value.trim())); else invalidValues.push("--evidence requires a local evidence bundle file"); + } else if (arg === "--supply-chain") { + consumeValue(); + if (value?.trim()) supplyChainPath = expandHomePath(value.trim()); + else invalidValues.push("--supply-chain requires a local supply-chain bundle file"); } else if (arg === "--format") { consumeValue(); const normalized = value?.trim().toLowerCase(); @@ -1274,6 +1287,11 @@ export function parseArgs(args: string[]): CliOptions { flagCounts.set(arg, 1); if (inlineValue !== undefined) invalidValues.push(`${arg} does not accept a value; pass ${arg} by itself`); else noCache = true; + } else if (arg === "--sensitive-data") { + if (flagCounts.has(arg)) invalidValues.push(`pass ${arg} only once`); + flagCounts.set(arg, 1); + if (inlineValue !== undefined) invalidValues.push(`${arg} does not accept a value; pass ${arg} by itself`); + else sensitiveData = true; } else if (arg === "--output") { consumeValue(); if (value?.trim()) output = expandHomePath(value.trim()); @@ -1306,6 +1324,8 @@ export function parseArgs(args: string[]): CliOptions { noCache, semanticModelPath, evidencePaths, + sensitiveData, + supplyChainPath, unknownArgs, invalidValues }; @@ -1569,7 +1589,7 @@ async function runVerify( return 1; } - const result = verifyPlan(report, repo); + const result = verifyPlan(report, repo, { sensitiveData: options.sensitiveData }); const rendered = options.format === "json" ? `${JSON.stringify(result, null, 2)}\n` : renderVerifyMarkdown(result); diff --git a/packages/cli/src/mcp.ts b/packages/cli/src/mcp.ts index d775a70..bcf750f 100644 --- a/packages/cli/src/mcp.ts +++ b/packages/cli/src/mcp.ts @@ -77,6 +77,8 @@ type PlanArguments = { noCache?: boolean; semanticModel?: string; evidence?: string[]; + sensitiveData?: boolean; + supplyChain?: string; }; type ExplainArguments = { @@ -114,6 +116,7 @@ type VerifyArguments = { workingTree?: boolean; includeUntracked?: boolean; noCache?: boolean; + sensitiveData?: boolean; }; const PLAN_TOOL = { @@ -188,6 +191,14 @@ const PLAN_TOOL = { items: { type: "string" }, maxItems: 8, description: "Local version-1 evidence bundle files from other tools (data only, never executed). Relevant items are attached to the report." + }, + sensitiveData: { + type: "boolean", + description: "Preview: attach possible sensitive-data source-to-sink flows (credential, token, PII, payment to logging, network, storage, analytics) touching the report's files. Locations and kinds only; matched values are never included." + }, + supplyChain: { + type: "string", + description: "Preview: local version-1 normalized scanner/SBOM bundle file. Findings for packages declared in manifests among the report's files are attached with tool, database, and bundle provenance." } }, additionalProperties: false @@ -527,7 +538,11 @@ const VERIFY_TOOL = { workingTree: { type: "boolean", description: "Verify staged and unstaged tracked changes against HEAD" }, includeUntracked: { type: "boolean", description: "With workingTree, include untracked files" }, format: { type: "string", description: "Output format: markdown (default) or json, case-insensitive" }, - noCache: { type: "boolean", description: "Bypass the exact-state repository scan cache" } + noCache: { type: "boolean", description: "Bypass the exact-state repository scan cache" }, + sensitiveData: { + type: "boolean", + description: "Preview: attach possible sensitive-data flows touching the plan or diff and add an advisory finding when the diff adds one. Locations and kinds only." + } }, required: ["report"], additionalProperties: false @@ -1010,7 +1025,7 @@ export function createFixMapMcpServer( if (diffFailure) { throw new Error(`${diffFailure.message} Verification needs a resolvable diff.`); } - const result = verifyPlan(args.report, repo); + const result = verifyPlan(args.report, repo, { sensitiveData: args.sensitiveData === true }); const text = args.format === "json" ? `${JSON.stringify(result, null, 2)}\n` : renderVerifyMarkdown(result); @@ -1111,7 +1126,9 @@ export function createFixMapMcpServer( limit: args.limit, exclude: args.exclude, semanticModelPath: args.semanticModel, - ...(args.evidence ? { evidencePaths: args.evidence } : {}) + ...(args.evidence ? { evidencePaths: args.evidence } : {}), + ...(args.sensitiveData ? { sensitiveData: true } : {}), + ...(args.supplyChain ? { supplyChainPath: args.supplyChain } : {}) }, repositorySourceDependencies); } catch (error) { return { @@ -1153,7 +1170,7 @@ export function parsePlanArguments(input: unknown): PlanArgumentsValidation { } const record = input as Record; - const allowed = new Set(["issue", "diff", "base", "head", "repo", "ref", "format", "limit", "exclude", "workingTree", "includeUntracked", "noCache", "semanticModel", "evidence", "at"]); + const allowed = new Set(["issue", "diff", "base", "head", "repo", "ref", "format", "limit", "exclude", "workingTree", "includeUntracked", "noCache", "semanticModel", "evidence", "sensitiveData", "supplyChain", "at"]); const unknown = Object.keys(record).filter((key) => !allowed.has(key)); if (unknown.length > 0) { return { @@ -1214,6 +1231,16 @@ export function parsePlanArguments(input: unknown): PlanArgumentsValidation { } value.evidence = record.evidence.map((entry: string) => entry.trim()); } + if (record.sensitiveData !== undefined && typeof record.sensitiveData !== "boolean") { + return { success: false, message: '"sensitiveData" must be a boolean.' }; + } + if (record.sensitiveData === true) value.sensitiveData = true; + if (record.supplyChain !== undefined) { + if (typeof record.supplyChain !== "string" || !record.supplyChain.trim() || record.supplyChain.length > 1_000 || record.supplyChain.includes("\0")) { + return { success: false, message: '"supplyChain" must be a non-empty local bundle file path.' }; + } + value.supplyChain = record.supplyChain.trim(); + } if (value.ref && !/^https?:\/\//i.test(value.repo ?? "") && !tryParseGitHubIssueSource(value.issue ?? "")) { return { success: false, message: '"ref" requires a remote GitHub "repo" or issue URL.' }; } @@ -1376,7 +1403,7 @@ export function parseVerifyArguments(input: unknown): VerifyArgumentsValidation return { success: false, message: "tool arguments must be an object." }; } const record = input as Record; - const allowed = new Set(["report", "diff", "base", "head", "repo", "format", "workingTree", "includeUntracked", "noCache"]); + const allowed = new Set(["report", "diff", "base", "head", "repo", "format", "workingTree", "includeUntracked", "noCache", "sensitiveData"]); const unknown = Object.keys(record).filter((key) => !allowed.has(key)); if (unknown.length > 0) { return { success: false, message: `unknown argument${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}.` }; @@ -1398,7 +1425,7 @@ export function parseVerifyArguments(input: unknown): VerifyArgumentsValidation if (!record.diff && !record.base && record.workingTree !== true) { return { success: false, message: 'provide "diff", "base"/"head", or "workingTree" so FixMap can see what changed.' }; } - for (const name of ["workingTree", "includeUntracked", "noCache"] as const) if (record[name] !== undefined && typeof record[name] !== "boolean") return { success: false, message: `"${name}" must be a boolean.` }; + for (const name of ["workingTree", "includeUntracked", "noCache", "sensitiveData"] as const) if (record[name] !== undefined && typeof record[name] !== "boolean") return { success: false, message: `"${name}" must be a boolean.` }; if (record.includeUntracked === true && record.workingTree !== true) return { success: false, message: '"includeUntracked" requires "workingTree".' }; if (record.workingTree === true && (record.diff || record.base || record.head)) return { success: false, message: 'use either "workingTree" or diff/base/head, not both.' }; if (record.diff && (record.base || record.head)) return { success: false, message: 'use either "diff" or base/head, not both.' }; @@ -1416,6 +1443,7 @@ export function parseVerifyArguments(input: unknown): VerifyArgumentsValidation ...(record.workingTree === true ? { workingTree: true } : {}), ...(record.includeUntracked === true ? { includeUntracked: true } : {}), ...(record.noCache === true ? { noCache: true } : {}), + ...(record.sensitiveData === true ? { sensitiveData: true } : {}), ...(format.value ? { format: format.value } : {}) } }; diff --git a/packages/cli/src/repository-source.ts b/packages/cli/src/repository-source.ts index 674fba4..91dba3f 100644 --- a/packages/cli/src/repository-source.ts +++ b/packages/cli/src/repository-source.ts @@ -13,6 +13,7 @@ import { type ReportEvidenceSource, type ScanDiagnostic } from "@aryam/fixmap-core"; +import { readSupplyChainBundleFile } from "./supply-chain-command.js"; const exec = promisify(execFile); const GIT_MAX_BUFFER = 10 * 1024 * 1024; @@ -42,6 +43,10 @@ export type RepositoryPlanInput = { semanticModelPath?: string | undefined; /** Local evidence bundle files (data only, version-1 envelope). */ evidencePaths?: string[] | undefined; + /** Attach local lexical sensitive-data flows (locations and kinds only). */ + sensitiveData?: boolean | undefined; + /** Local normalized supply-chain bundle file (data only). */ + supplyChainPath?: string | undefined; }; export type ClonedRepository = { @@ -552,6 +557,7 @@ export async function buildReportForRepository( const bundle = await readEvidenceProviderBundle(path); evidenceSources.push({ provider: bundle.provider, documentSha256: bundle.documentSha256 }); } + const supplyChain = input.supplyChainPath ? readSupplyChainBundleFile(input.supplyChainPath) : undefined; return withRepositorySource( source, @@ -577,6 +583,8 @@ export async function buildReportForRepository( internalExclude: input.internalExclude, embeddingProvider, ...(evidenceSources.length > 0 ? { evidenceSources } : {}), + ...(input.sensitiveData ? { sensitiveData: true } : {}), + ...(supplyChain ? { supplyChain } : {}), ...(input.atRef ? { atRef: input.atRef } : {}) }); reportProgress(`ranked ${report.contextFiles.length} context files`); diff --git a/packages/cli/src/supply-chain-command.ts b/packages/cli/src/supply-chain-command.ts index 65ed0be..49bd8ff 100644 --- a/packages/cli/src/supply-chain-command.ts +++ b/packages/cli/src/supply-chain-command.ts @@ -1,3 +1,5 @@ +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; import { writeFile } from "node:fs/promises"; import { homedir } from "node:os"; import { resolve } from "node:path"; @@ -7,7 +9,7 @@ import { validateSupplyChainEvidenceBundle, type SupplyChainEvidenceBundle } from "@aryam/fixmap-core"; -import { describeInputReadError, readDecodedTextFile } from "./decode-input.js"; +import { decodeInputText, describeInputReadError, readDecodedTextFile } from "./decode-input.js"; export const SUPPLY_CHAIN_USAGE = `Usage: fixmap supply-chain --input [--format markdown|json] [--output ] @@ -16,6 +18,19 @@ Validates a version-1 normalized external scanner/SBOM bundle and renders packag export type SupplyChainReport = Awaited>; +/** Read and validate a bundle for `plan --supply-chain`, with the SHA-256 of its exact bytes. */ +export function readSupplyChainBundleFile(path: string): { bundle: SupplyChainEvidenceBundle; documentSha256: string } { + try { + const bytes = readFileSync(path); + return { + bundle: validateSupplyChainEvidenceBundle(JSON.parse(decodeInputText(bytes)) as unknown), + documentSha256: createHash("sha256").update(bytes).digest("hex") + }; + } catch (error) { + throw new Error(`Could not import supply-chain evidence from "${path}": ${describeInputReadError(path, error)}`); + } +} + export async function buildSupplyChainReport(candidate: unknown) { const bundle = validateSupplyChainEvidenceBundle(candidate); const evidence = await collectEvidence([createSupplyChainEvidenceProvider(bundle)], { diff --git a/packages/cli/test/cli-runner.test.ts b/packages/cli/test/cli-runner.test.ts index 3f516b7..06375c4 100644 --- a/packages/cli/test/cli-runner.test.ts +++ b/packages/cli/test/cli-runner.test.ts @@ -1,5 +1,5 @@ import { execFile } from "node:child_process"; -import { link, mkdir, mkdtemp, readFile, readdir, symlink, writeFile } from "node:fs/promises"; +import { link, mkdir, mkdtemp, readFile, readdir, rm, symlink, writeFile } from "node:fs/promises"; import { homedir, tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { promisify } from "node:util"; @@ -200,7 +200,7 @@ describe("CLI argument handling", () => { const features = (JSON.parse(catalog.stdout.join("")) as { features: Array<{ name: string; preview?: true }> }).features; expect(features.filter((feature) => feature.preview).map((feature) => feature.name)).toEqual([ "Change scope", "Reviewer suggestions", "Product capabilities", "Cross-repository workspace", "Repository Q&A", "Migration planning", - "Reverse documentation", "Architecture history", "Historical plans", "Contract Guardian", "Supply-chain evidence", "Runtime evidence", "Evidence import", "Outcome feedback loop", "Change dossier", "Execution sandbox", + "Reverse documentation", "Architecture history", "Historical plans", "Contract Guardian", "Supply-chain evidence", "Runtime evidence", "Evidence import", "Sensitive-data flows", "Supply-chain in plans", "Outcome feedback loop", "Change dossier", "Execution sandbox", "Local hybrid retrieval" ]); expect(features.find((feature) => feature.name === "Plan")?.preview).toBeUndefined(); @@ -1155,6 +1155,51 @@ describe("CLI argument handling", () => { })); }); + it("passes --sensitive-data and --supply-chain to the report builder and rejects bad forms", async () => { + const io = capture(); + const buildReport = vi.fn(async () => report); + await runCli( + ["plan", "--issue", "rotate the session token", "--sensitive-data", "--supply-chain", "scanner.json"], + { ...io.dependencies, buildReport } + ); + expect(buildReport).toHaveBeenCalledWith(expect.objectContaining({ sensitiveData: true, supplyChainPath: "scanner.json" })); + + const plain = vi.fn(async () => report); + await runCli(["plan", "--issue", "rotate the session token"], { ...capture().dependencies, buildReport: plain }); + expect(plain.mock.calls[0]![0]).not.toHaveProperty("sensitiveData"); + expect(plain.mock.calls[0]![0]).not.toHaveProperty("supplyChainPath"); + + for (const args of [ + ["plan", "--issue", "x", "--sensitive-data=yes"], + ["plan", "--issue", "x", "--sensitive-data", "--sensitive-data"], + ["plan", "--issue", "x", "--supply-chain"], + ["plan", "--issue", "x", "--supply-chain", "a.json", "--supply-chain", "b.json"] + ]) { + const rejected = capture(); + expect(await runCli(args, { ...rejected.dependencies, buildReport })).toBe(1); + } + + const verify = capture(); + expect(await runCli(["verify", "--report", "plan.json", "--supply-chain", "scanner.json"], verify.dependencies)).toBe(1); + expect(verify.stderr.join("")).toContain("verify does not accept plan-only option(s): --supply-chain"); + }); + + it("reports a malformed supply-chain bundle without a stack or its contents", async () => { + const directory = await mkdtemp(join(tmpdir(), "fixmap-cli-supply-")); + try { + const bundlePath = join(directory, "scanner.json"); + await writeFile(bundlePath, JSON.stringify({ supplyChainBundleVersion: 2, secret: "sk_live_SUPERSECRET_1234" })); + const io = capture(); + expect(await runCli(["plan", "--issue", "upgrade left-pad", "--repo", directory, "--supply-chain", bundlePath], io.dependencies)).toBe(1); + const stderr = io.stderr.join(""); + expect(stderr).toContain("Could not import supply-chain evidence"); + expect(stderr).toContain("Invalid supply-chain evidence bundle envelope."); + expect(stderr).not.toContain("SUPERSECRET"); + } finally { + await rm(directory, { recursive: true, force: true }); + } + }); + it("keeps semantic-model selection out of verify", async () => { const io = capture(); expect(await runCli([ diff --git a/packages/cli/test/mcp.test.ts b/packages/cli/test/mcp.test.ts index 1dcae56..db83ca5 100644 --- a/packages/cli/test/mcp.test.ts +++ b/packages/cli/test/mcp.test.ts @@ -190,6 +190,75 @@ describe("fixmap mcp server", () => { } }); + it("attaches sensitive-data and supply-chain evidence to plans and flags a new flow in verify", async () => { + const secret = "sk_live_SUPERSECRET_5150"; + const root = await createAuthFixture(); + const bundleDir = await mkdtemp(join(tmpdir(), "fixmap-mcp-supply-")); + const bundlePath = join(bundleDir, "scanner.json"); + const bundleText = JSON.stringify({ + supplyChainBundleVersion: 1, + generatedAt: "2026-11-01T00:00:00Z", + source: { tool: "external-scanner", toolVersion: "4.2.0", databaseVersion: "db-2026-11-01", documentFingerprint: `sha256:${"a".repeat(64)}` }, + components: [{ id: "npm-left-pad", name: "left-pad", version: "1.0.0", licenses: ["MIT"], paths: ["package.json"] }], + findings: [{ id: "adv-1", kind: "vulnerability", severity: "high", confidence: "high", componentId: "npm-left-pad", summary: "Advisory matched left-pad." }] + }); + await writeFile(bundlePath, bundleText); + await writeFile(join(root, "src", "auth", "session.ts"), `export function refresh() {\n const accessToken = "${secret}";\n return accessToken;\n}\n`); + await exec("git", ["init", "-q"], { cwd: root }); + await exec("git", ["add", "-A"], { cwd: root }); + await exec("git", ["-c", "user.name=FixMap Test", "-c", "user.email=test@example.invalid", "commit", "-qm", "fixture"], { cwd: root }); + await writeFile(join(root, "package.json"), JSON.stringify({ scripts: { test: "vitest run" }, dependencies: { "left-pad": "1.0.0" } })); + const client = await connectClient(); + try { + const planned = await client.callTool({ + name: "fixmap_plan", + arguments: { issue: "refresh session accessToken", repo: root, workingTree: true, format: "json", sensitiveData: true, supplyChain: bundlePath } + }); + expect(planned.isError).toBeFalsy(); + const plan = JSON.parse((planned.content as Array<{ text: string }>)[0]!.text); + expect(plan.sensitiveData).toMatchObject({ sensitiveDataVersion: 1, flows: [] }); + expect(plan.supplyChain.source.documentSha256).toBe(createHash("sha256").update(bundleText).digest("hex")); + expect(plan.supplyChain.findings).toEqual([expect.objectContaining({ id: "adv-1", manifestPaths: ["package.json"] })]); + + await writeFile(join(root, "src", "auth", "session.ts"), `export function refresh() {\n const accessToken = "${secret}";\n console.log("refreshed", accessToken);\n return accessToken;\n}\n`); + for (const format of ["json", "markdown"]) { + const verified = await client.callTool({ name: "fixmap_verify", arguments: { report: plan, repo: root, workingTree: true, format, sensitiveData: true } }); + expect(verified.isError).toBeFalsy(); + const text = (verified.content as Array<{ text: string }>)[0]!.text; + expect(text).not.toContain(secret); + if (format === "json") { + const result = JSON.parse(text); + expect(result.findings).toContainEqual(expect.objectContaining({ code: "sensitive-data-flow-introduced", severity: "info", paths: ["src/auth/session.ts"] })); + expect(result.sensitiveData.flows).toContainEqual(expect.objectContaining({ introducedByDiff: true, relation: "same-file" })); + } else { + expect(text).toContain("## Sensitive Data"); + } + } + const withoutFlag = await client.callTool({ name: "fixmap_verify", arguments: { report: plan, repo: root, workingTree: true, format: "json" } }); + expect(JSON.parse((withoutFlag.content as Array<{ text: string }>)[0]!.text).sensitiveData).toBeUndefined(); + + await writeFile(bundlePath, JSON.stringify({ supplyChainBundleVersion: 1, generatedAt: "not-a-date" })); + const malformed = await client.callTool({ name: "fixmap_plan", arguments: { issue: "x", repo: root, supplyChain: bundlePath } }); + expect(malformed.isError).toBe(true); + expect((malformed.content as Array<{ text: string }>)[0]!.text).toContain("Invalid supply-chain evidence bundle envelope."); + } finally { + await client.close(); + await rm(root, { recursive: true, force: true }); + await rm(bundleDir, { recursive: true, force: true }); + } + }, 30_000); + + it("validates sensitiveData and supplyChain arguments", () => { + expect(parsePlanArguments({ issue: "x", sensitiveData: "yes" })).toMatchObject({ success: false, message: '"sensitiveData" must be a boolean.' }); + expect(parsePlanArguments({ issue: "x", supplyChain: ["a.json"] })).toMatchObject({ success: false }); + expect(parsePlanArguments({ issue: "x", supplyChain: " " })).toMatchObject({ success: false }); + expect(parsePlanArguments({ issue: "x", sensitiveData: true, supplyChain: " scanner.json " })).toMatchObject({ success: true, value: { sensitiveData: true, supplyChain: "scanner.json" } }); + const report = { summary: "", contextFiles: [], testRoutes: [], risks: [], changedFiles: [], diagnostics: [] }; + expect(parseVerifyArguments({ report, diff: "HEAD", sensitiveData: 1 })).toMatchObject({ success: false, message: '"sensitiveData" must be a boolean.' }); + expect(parseVerifyArguments({ report, diff: "HEAD", supplyChain: "scanner.json" })).toMatchObject({ success: false }); + expect(parseVerifyArguments({ report, diff: "HEAD", sensitiveData: true })).toMatchObject({ success: true, value: { sensitiveData: true } }); + }); + it("suggests reviewers read-only and validates fixmap_reviewers arguments", async () => { const root = await mkdtemp(join(tmpdir(), "fixmap-mcp-reviewers-")); execFileSync("git", ["init", "-q"], { cwd: root }); @@ -427,7 +496,7 @@ describe("fixmap mcp server", () => { expect(plan).toBeDefined(); expect(plan?.description).toContain("test commands"); expect(Object.keys(plan?.inputSchema.properties ?? {}).sort()).toEqual( - ["issue", "diff", "base", "head", "repo", "ref", "at", "format", "limit", "exclude", "workingTree", "includeUntracked", "noCache", "semanticModel", "evidence"].sort() + ["issue", "diff", "base", "head", "repo", "ref", "at", "format", "limit", "exclude", "workingTree", "includeUntracked", "noCache", "semanticModel", "evidence", "sensitiveData", "supplyChain"].sort() ); expect(plan?.inputSchema.additionalProperties).toBe(false); expect(plan?.inputSchema.properties?.repo?.description).toContain("public GitHub HTTPS"); @@ -477,7 +546,7 @@ describe("fixmap mcp server", () => { expect(runtime?.inputSchema.additionalProperties).toBe(false); expect(verify).toBeDefined(); expect(Object.keys(verify?.inputSchema.properties ?? {}).sort()).toEqual( - ["report", "diff", "base", "head", "repo", "workingTree", "includeUntracked", "format", "noCache"].sort() + ["report", "diff", "base", "head", "repo", "workingTree", "includeUntracked", "format", "noCache", "sensitiveData"].sort() ); expect(verify?.inputSchema.required).toEqual(["report"]); expect(verify?.inputSchema.additionalProperties).toBe(false); diff --git a/packages/core/src/feature-catalog.ts b/packages/core/src/feature-catalog.ts index 160cb4e..6df1184 100644 --- a/packages/core/src/feature-catalog.ts +++ b/packages/core/src/feature-catalog.ts @@ -28,6 +28,8 @@ export const FIXMAP_FEATURES: readonly FixMapFeature[] = [ { name: "Supply-chain evidence", preview: true, command: "fixmap supply-chain --input ", detail: "Validate normalized external scanner or SBOM evidence with exact tool, database, document, advisory, version, and license provenance." }, { name: "Runtime evidence", preview: true, command: "fixmap runtime --input ", detail: "Map redaction-reviewed OpenTelemetry, APM, Speedscope, or pprof observations only through exact repository paths and file fingerprints." }, { name: "Evidence import", preview: true, command: "fixmap plan --evidence ", detail: "Attach findings from other tools (scanners, CI, runtime monitors) to the files in a plan from a version-1 data-only bundle; claims are shown as supplied and never executed." }, + { name: "Sensitive-data flows", preview: true, command: "fixmap plan --sensitive-data", detail: "Attach possible credential, token, PII, or payment source-to-sink flows (logging, network, storage, analytics) touching a plan's files from local lexical and direct-import evidence; verify --sensitive-data adds an advisory finding when the diff introduces one. Locations and kinds only, never matched values." }, + { name: "Supply-chain in plans", preview: true, command: "fixmap plan --supply-chain ", detail: "Attach imported scanner or SBOM findings for packages declared in manifests among a plan's files, with tool, database, document, and bundle SHA-256 provenance." }, { name: "Outcome feedback loop", preview: true, command: "fixmap outcome record --report --working-tree", detail: "Save what a plan predicted next to what was edited and which commands passed, one atomic file per record in .fixmap/outcomes/, then calibrate precision and recall; ranking weights never change automatically." }, { name: "Change dossier", preview: true, command: "fixmap dossier create --report --task ", detail: "Save a fingerprinted record linking the request, plan and graph fingerprints, ADRs, diff, command results, and commit/PR identifiers in .fixmap/dossiers/, with optional SHA-256 redaction of the task text." }, { name: "Execution sandbox", preview: true, command: "fixmap sandbox --request --execute-declared-command", detail: "Run exactly one reviewed command in an already-present digest-pinned Docker image with network off and source/root read-only by default." }, diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 4b35793..2281ab9 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -32,8 +32,12 @@ export type { } from "./language-adapters.js"; export { FIXMAP_FEATURES } from "./feature-catalog.js"; export type { FixMapFeature } from "./feature-catalog.js"; -export { attachReportEvidence, MAX_REPORT_EVIDENCE_ITEMS } from "./report-evidence.js"; +export { attachReportEvidence, MAX_REPORT_EVIDENCE_ITEMS, reportPaths } from "./report-evidence.js"; export type { ReportEvidence, ReportEvidenceSource } from "./report-evidence.js"; +export { buildReportSensitiveData, MAX_REPORT_SENSITIVE_DATA_FLOWS, renderSensitiveDataMarkdown } from "./report-sensitive-data.js"; +export type { ReportSensitiveData, SensitiveDataFlow, SensitiveDataSignalLocation } from "./report-sensitive-data.js"; +export { buildReportSupplyChain, MAX_REPORT_SUPPLY_CHAIN_FINDINGS, renderSupplyChainReportMarkdown } from "./report-supply-chain.js"; +export type { ReportSupplyChain, ReportSupplyChainFinding } from "./report-supply-chain.js"; export { createLanguageRegistry } from "./language-registry.js"; export type { CustomLanguageAdapter, LanguageRegistry } from "./language-registry.js"; export { buildImpactMap } from "./impact.js"; diff --git a/packages/core/src/markdown.ts b/packages/core/src/markdown.ts index 8b08c30..64fb1e5 100644 --- a/packages/core/src/markdown.ts +++ b/packages/core/src/markdown.ts @@ -11,3 +11,8 @@ export function longestBacktickRun(value: string): number { for (const match of value.matchAll(/`+/g)) longest = Math.max(longest, match[0].length); return longest; } + +/** Collapse whitespace so supplied text stays on one Markdown line. */ +export function inlineProse(value: string): string { + return value.replace(/\s+/g, " ").trim(); +} diff --git a/packages/core/src/paths.ts b/packages/core/src/paths.ts index 1b34533..c3b1412 100644 --- a/packages/core/src/paths.ts +++ b/packages/core/src/paths.ts @@ -130,3 +130,13 @@ export function isBackupPath(path: string): boolean { const fileName = path.split("/").pop() ?? ""; return BACKUP_FILE_PATTERNS.some((pattern) => pattern.test(fileName)); } + +/** A non-empty relative path with no absolute prefix and no empty, `.`, or `..` segment. */ +export function isRepositoryRelativePath(candidate: unknown): candidate is string { + if (typeof candidate !== "string" || !candidate.trim() || candidate.includes("\0") || + /^[\\/]/.test(candidate) || /^[A-Za-z]:/.test(candidate)) { + return false; + } + const segments = candidate.replace(/\\/g, "/").split("/"); + return segments.every((segment) => segment.length > 0 && segment !== "." && segment !== ".."); +} diff --git a/packages/core/src/plan.ts b/packages/core/src/plan.ts index 25e8849..a1b304a 100644 --- a/packages/core/src/plan.ts +++ b/packages/core/src/plan.ts @@ -11,7 +11,10 @@ import { createCustomLanguageContext } from "./custom-language-context.js"; import type { EmbeddingProvider } from "./semantic.js"; import type { FixMapInput, FixMapReport } from "./types.js"; import { fixMapArtifactKind, isFixMapArtifact } from "./artifacts.js"; -import { attachReportEvidence, type ReportEvidenceSource } from "./report-evidence.js"; +import { attachReportEvidence, reportPaths, type ReportEvidenceSource } from "./report-evidence.js"; +import { buildReportSensitiveData } from "./report-sensitive-data.js"; +import { buildReportSupplyChain } from "./report-supply-chain.js"; +import type { SupplyChainEvidenceBundle } from "./supply-chain.js"; export async function buildFixMapReport( input: Pick< @@ -26,6 +29,10 @@ export async function buildFixMapReport( languageRegistry?: LanguageRegistry; /** Explicit evidence providers, typically imported bundles; collected without network or code execution. */ evidenceSources?: readonly ReportEvidenceSource[]; + /** Attach local lexical sensitive-data flows touching the report's files (locations and kinds only). */ + sensitiveData?: boolean; + /** A validated supply-chain bundle and the SHA-256 of its exact bytes. */ + supplyChain?: { bundle: SupplyChainEvidenceBundle; documentSha256: string }; /** Preview: rank against this committed ref, read from Git objects without checkout. */ atRef?: string | undefined; } @@ -50,6 +57,10 @@ export async function buildFixMapAnalysis( languageRegistry?: LanguageRegistry; /** Explicit evidence providers, typically imported bundles; collected without network or code execution. */ evidenceSources?: readonly ReportEvidenceSource[]; + /** Attach local lexical sensitive-data flows touching the report's files (locations and kinds only). */ + sensitiveData?: boolean; + /** A validated supply-chain bundle and the SHA-256 of its exact bytes. */ + supplyChain?: { bundle: SupplyChainEvidenceBundle; documentSha256: string }; /** Preview: rank against this committed ref, read from Git objects without checkout. */ atRef?: string | undefined; } @@ -93,6 +104,12 @@ export async function buildFixMapAnalysis( if (input.evidenceSources && input.evidenceSources.length > 0) { report.evidence = await attachReportEvidence(report, analyzedRepo, input.evidenceSources, { issueText: input.issueText ?? "" }); } + if (input.sensitiveData) { + report.sensitiveData = buildReportSensitiveData(analyzedRepo, reportPaths(report)); + } + if (input.supplyChain) { + report.supplyChain = buildReportSupplyChain(input.supplyChain.bundle, input.supplyChain.documentSha256, reportPaths(report)); + } if (input.languageRegistry && languageContext) { report.languageAdapters = input.languageRegistry.customAdapters.map((adapter) => ({ diff --git a/packages/core/src/report-evidence.ts b/packages/core/src/report-evidence.ts index 1aabe9d..3c3ebc0 100644 --- a/packages/core/src/report-evidence.ts +++ b/packages/core/src/report-evidence.ts @@ -36,14 +36,10 @@ export async function attachReportEvidence( { repo, issueText: context.issueText, diffText: repo.diffText ?? "" }, { allowNetwork: false, allowCodeExecution: false, ...(context.now ? { now: context.now } : {}) } ); - const reportPaths = new Set([ - ...report.contextFiles.map((file) => file.path), - ...(report.impact?.files ?? []).map((file) => file.path), - ...report.changedFiles - ]); + const paths = reportPaths(report); const relevant = collected.items.filter((item) => item.subjects.some((subject) => (subject.kind === "file" || subject.kind === "symbol" || subject.kind === "contract") && - "path" in subject && typeof subject.path === "string" && reportPaths.has(subject.path) + "path" in subject && typeof subject.path === "string" && paths.has(subject.path) )); const items = relevant.slice(0, MAX_REPORT_EVIDENCE_ITEMS); return { @@ -59,3 +55,12 @@ export async function attachReportEvidence( diagnostics: collected.diagnostics }; } + +/** The paths a report is about: ranked context files, impact files, and changed files. */ +export function reportPaths(report: Pick): Set { + return new Set([ + ...report.contextFiles.map((file) => file.path), + ...(report.impact?.files ?? []).map((file) => file.path), + ...report.changedFiles + ]); +} diff --git a/packages/core/src/report-sensitive-data.ts b/packages/core/src/report-sensitive-data.ts new file mode 100644 index 0000000..81b9724 --- /dev/null +++ b/packages/core/src/report-sensitive-data.ts @@ -0,0 +1,278 @@ +import { + collectSensitiveDataSignals, + SENSITIVE_DATA_PROVIDER_ID, + SENSITIVE_DATA_PROVIDER_VERSION, + sensitiveSignalLine, + type SensitiveDataCategory, + type SensitiveSinkCategory +} from "./sensitive-data.js"; +import { markdownCode } from "./markdown.js"; +import { isRepositoryRelativePath } from "./paths.js"; +import type { RepoFile, RepoMap, VerifyFinding } from "./types.js"; + +/** One end of a possible flow: a file, the indicator kind, and the rule ids that matched. Never the matched text. */ +export type SensitiveDataSignalLocation = { + path: string; + category: T; + ruleIds: string[]; + /** First 1-based line where one of the rules matched on a single line, when one did. */ + line?: number; +}; + +export type SensitiveDataFlow = { + relation: "same-file" | "direct-import"; + source: SensitiveDataSignalLocation; + sink: SensitiveDataSignalLocation; + /** Verify only: absent from the pre-change file contents reconstructed from the diff. */ + introducedByDiff?: true; +}; + +/** + * Lexical sensitive-data indicators about the files a report covers. Locations and + * kinds only: matched values are never copied into the report. + */ +export type ReportSensitiveData = { + sensitiveDataVersion: 1; + provider: { id: typeof SENSITIVE_DATA_PROVIDER_ID; version: string }; + analysis: "lexical-signals-and-direct-import-structure"; + completeness: "not-a-security-proof"; + scannedFiles: number; + skippedFiles: number; + flows: SensitiveDataFlow[]; + /** Flows touching the report's paths that were not listed because of the size bound. */ + omittedFlows: number; + /** Verify only: whether pre-change contents could be reconstructed from the diff. */ + introducedCheck?: "compared-with-diff" | "unavailable-diff-truncated"; +}; + +export const MAX_REPORT_SENSITIVE_DATA_FLOWS = 50; + +const SOURCE_CATEGORIES: readonly string[] = ["credential", "token", "pii", "payment"]; +const SINK_CATEGORIES: readonly string[] = ["logging", "network", "storage", "analytics"]; +const RULE_ID = /^[a-z0-9-]{1,64}$/; + +type Signal = { path: string; role: "source" | "sink"; category: string; ruleIds: string[] }; + +/** + * Runs the local `fixmap-sensitive-data` analysis and keeps flows with an end among + * `focusPaths`. With `compareWithDiff`, each changed file's pre-change contents are + * reconstructed from `repo.diffText` and the flows absent there are marked as introduced. + */ +export function buildReportSensitiveData( + repo: Pick, + focusPaths: ReadonlySet, + options: { compareWithDiff?: boolean } = {} +): ReportSensitiveData { + const after = flowsFrom(repo.root, repo.files); + let introducedCheck: ReportSensitiveData["introducedCheck"]; + let before: Set | undefined; + if (options.compareWithDiff) { + const previousFiles = filesBeforeDiff(repo); + introducedCheck = previousFiles ? "compared-with-diff" : "unavailable-diff-truncated"; + if (previousFiles) before = new Set(flowsFrom(repo.root, previousFiles).flows.map(flowKey)); + } + + const relevant = after.flows + .filter((flow) => focusPaths.has(flow.source.path) || focusPaths.has(flow.sink.path)) + .map((flow): SensitiveDataFlow => before && !before.has(flowKey(flow)) ? { ...flow, introducedByDiff: true } : flow) + .sort((a, b) => + Number(b.introducedByDiff === true) - Number(a.introducedByDiff === true) || + a.relation.localeCompare(b.relation) || + flowKey(a).localeCompare(flowKey(b)) + ); + const textByPath = new Map(repo.files.map((file) => [file.path, file.textSample])); + const withLine = (end: SensitiveDataSignalLocation): SensitiveDataSignalLocation => { + const line = sensitiveSignalLine(textByPath.get(end.path) ?? "", end.ruleIds); + return line === undefined ? end : { ...end, line }; + }; + const flows = relevant.slice(0, MAX_REPORT_SENSITIVE_DATA_FLOWS) + .map((flow) => ({ ...flow, source: withLine(flow.source), sink: withLine(flow.sink) })); + return { + sensitiveDataVersion: 1, + provider: { id: SENSITIVE_DATA_PROVIDER_ID, version: SENSITIVE_DATA_PROVIDER_VERSION }, + analysis: "lexical-signals-and-direct-import-structure", + completeness: "not-a-security-proof", + scannedFiles: after.scannedFiles, + skippedFiles: after.skippedFiles, + flows, + omittedFlows: relevant.length - flows.length, + ...(introducedCheck ? { introducedCheck } : {}) + }; +} + +/** Advisory Verify finding for flows the diff introduced; undefined when there are none. */ +export function sensitiveDataVerifyFinding(evidence: ReportSensitiveData): VerifyFinding | undefined { + const introduced = evidence.flows.filter((flow) => flow.introducedByDiff); + if (introduced.length === 0) return undefined; + const paths = [...new Set(introduced.flatMap((flow) => [flow.source.path, flow.sink.path]))]; + const examples = introduced.slice(0, 3).map(describeFlow).join("; "); + return { + code: "sensitive-data-flow-introduced", + severity: "info", + paths: paths.slice(0, 8), + message: + `This diff adds ${introduced.length === 1 ? "a possible sensitive-data flow" : `${introduced.length} possible sensitive-data flows`} ` + + `from lexical evidence (${examples}${introduced.length > 3 ? "; …" : ""}). ` + + "Value flow was not verified; check that no secret or personal data reaches the sink." + }; +} + +export function renderSensitiveDataMarkdown(evidence: ReportSensitiveData): string[] { + return [ + "", + "## Sensitive Data", + "", + `Lexical indicators from \`${evidence.provider.id}\` ${evidence.provider.version} across ${evidence.scannedFiles} scanned file${evidence.scannedFiles === 1 ? "" : "s"}` + + `${evidence.skippedFiles > 0 ? ` (${evidence.skippedFiles} skipped)` : ""}. Locations and kinds only; matched values are not shown. ` + + "This is not a taint analysis or a security proof.", + ...(evidence.introducedCheck === "unavailable-diff-truncated" + ? ["", "The diff was too large to reconstruct pre-change contents, so newly introduced flows could not be identified."] + : []), + "", + ...(evidence.flows.length > 0 + ? evidence.flows.map((flow) => `- ${flow.introducedByDiff ? "**new** " : ""}${describeFlow(flow)}`) + : ["- No possible source-to-sink flows touch the files in this report."]), + ...(evidence.omittedFlows > 0 + ? ["", `${evidence.omittedFlows} further flow${evidence.omittedFlows === 1 ? " was" : "s were"} not listed.`] + : []) + ]; +} + +export function isReportSensitiveData(candidate: unknown): candidate is ReportSensitiveData { + if (!isRecord(candidate) || candidate.sensitiveDataVersion !== 1 || !isRecord(candidate.provider) || + candidate.provider.id !== SENSITIVE_DATA_PROVIDER_ID || typeof candidate.provider.version !== "string" || + candidate.analysis !== "lexical-signals-and-direct-import-structure" || candidate.completeness !== "not-a-security-proof" || + !count(candidate.scannedFiles) || !count(candidate.skippedFiles) || !count(candidate.omittedFlows) || + (candidate.introducedCheck !== undefined && !["compared-with-diff", "unavailable-diff-truncated"].includes(String(candidate.introducedCheck))) || + !Array.isArray(candidate.flows) || candidate.flows.length > MAX_REPORT_SENSITIVE_DATA_FLOWS) return false; + return candidate.flows.every((flow) => isRecord(flow) && + (flow.relation === "same-file" || flow.relation === "direct-import") && + (flow.introducedByDiff === undefined || flow.introducedByDiff === true) && + validEnd(flow.source, SOURCE_CATEGORIES) && validEnd(flow.sink, SINK_CATEGORIES) && + (flow.relation !== "same-file" || (flow.source as { path: string }).path === (flow.sink as { path: string }).path)); +} + +function validEnd(candidate: unknown, categories: readonly string[]): boolean { + return isRecord(candidate) && isRepositoryRelativePath(candidate.path) && categories.includes(String(candidate.category)) && + Array.isArray(candidate.ruleIds) && candidate.ruleIds.length > 0 && candidate.ruleIds.length <= 8 && + candidate.ruleIds.every((id) => typeof id === "string" && RULE_ID.test(id)) && + (candidate.line === undefined || (Number.isSafeInteger(candidate.line) && (candidate.line as number) > 0)); +} + +function describeFlow(flow: SensitiveDataFlow): string { + const at = (end: SensitiveDataSignalLocation) => markdownCode(end.line ? `${end.path}:${end.line}` : end.path); + return flow.relation === "same-file" + ? `${flow.source.category} → ${flow.sink.category} in ${at(flow.source)} and ${at(flow.sink)} (same file)` + : `${flow.source.category} in ${at(flow.source)} → ${flow.sink.category} in ${at(flow.sink)} (direct import)`; +} + +function flowsFrom(root: string, files: readonly RepoFile[]): { flows: SensitiveDataFlow[]; scannedFiles: number; skippedFiles: number } { + const result = collectSensitiveDataSignals({ root, files: [...files] }); + const signals = new Map(); + let scannedFiles = 0; + let skippedFiles = 0; + for (const item of result.items) { + const metadata = item.metadata ?? {}; + if (item.id === "scope") { + scannedFiles = Number(metadata.scannedFiles) || 0; + skippedFiles = Number(metadata.skippedFiles) || 0; + continue; + } + const subject = item.subjects[0]; + if (!subject || subject.kind !== "file") continue; + signals.set(item.id, { + path: subject.path, + role: metadata.role === "sink" ? "sink" : "source", + category: String(metadata.category), + ruleIds: String(metadata.matchedRuleIds ?? "").split(",").filter(Boolean) + }); + } + const flows: SensitiveDataFlow[] = []; + for (const relationship of result.relationships ?? []) { + const source = signals.get(relationship.from); + const sink = signals.get(relationship.to); + if (!source || !sink) continue; + flows.push({ + relation: relationship.relation === "same-file-sensitive-signal-and-sink" ? "same-file" : "direct-import", + source: { path: source.path, category: source.category as SensitiveDataCategory, ruleIds: source.ruleIds }, + sink: { path: sink.path, category: sink.category as SensitiveSinkCategory, ruleIds: sink.ruleIds } + }); + } + return { flows, scannedFiles, skippedFiles }; +} + +function flowKey(flow: SensitiveDataFlow): string { + return [flow.relation, flow.source.path, flow.source.category, flow.sink.path, flow.sink.category].join("\0"); +} + +type FilePatch = { added: string[]; removed: string[]; created: boolean }; + +/** + * Pre-change contents of the scanned files, rebuilt from the unified diff as a line + * multiset (the lexical rules match single lines, so order does not matter). Returns + * undefined when the diff was sampled and no longer carries removed lines. + */ +function filesBeforeDiff( + repo: Pick +): RepoFile[] | undefined { + if (repo.diagnostics.some((diagnostic) => diagnostic.code === "diff-text-truncated")) return undefined; + const patches = parseUnifiedDiff(repo.diffText); + const changed = new Set(repo.changedFiles); + const tracked = repo.trackedFiles ? new Set(repo.trackedFiles) : undefined; + return repo.files.flatMap((file): RepoFile[] => { + if (!changed.has(file.path)) return [file]; + const patch = patches.get(file.path); + // A changed path with no textual patch is untracked (new) or binary/renamed (treated as unchanged). + if (!patch) return tracked && !tracked.has(file.path) ? [] : [file]; + if (patch.created) return []; + const lines = file.textSample.split(/\r?\n/); + for (const added of patch.added) { + const index = lines.indexOf(added); + if (index !== -1) lines.splice(index, 1); + } + return [{ ...file, textSample: [...lines, ...patch.removed].join("\n") }]; + }); +} + +function parseUnifiedDiff(diffText: string): Map { + const patches = new Map(); + let current: FilePatch | undefined; + let created = false; + let inHunk = false; + for (const line of diffText.split(/\r?\n/)) { + if (line.startsWith("diff --git ")) { + current = undefined; + created = false; + inHunk = false; + } else if (!inHunk && line.startsWith("--- ")) { + created = line === "--- /dev/null"; + } else if (!inHunk && line.startsWith("+++ ")) { + const path = diffPath(line.slice(4)); + current = path ? { added: [], removed: [], created } : undefined; + if (path && current) patches.set(path, current); + } else if (line.startsWith("@@")) { + inHunk = true; + } else if (inHunk && current) { + if (line.startsWith("+")) current.added.push(line.slice(1)); + else if (line.startsWith("-")) current.removed.push(line.slice(1)); + } + } + return patches; +} + +function diffPath(raw: string): string | undefined { + if (raw === "/dev/null") return undefined; + let path = raw.replace(/\t.*$/, ""); + if (path.startsWith("\"")) { + try { path = JSON.parse(path) as string; } catch { return undefined; } + } + return path.replace(/^[a-z]\//, ""); +} + +function count(value: unknown): boolean { + return Number.isSafeInteger(value) && (value as number) >= 0; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} diff --git a/packages/core/src/report-supply-chain.ts b/packages/core/src/report-supply-chain.ts new file mode 100644 index 0000000..54a98b2 --- /dev/null +++ b/packages/core/src/report-supply-chain.ts @@ -0,0 +1,154 @@ +import type { EvidenceConfidence } from "./evidence.js"; +import { inlineProse, markdownCode } from "./markdown.js"; +import { isRepositoryRelativePath } from "./paths.js"; +import type { SupplyChainEvidenceBundle, SupplyChainFindingKind, SupplyChainSeverity } from "./supply-chain.js"; + +export type ReportSupplyChainFinding = { + id: string; + kind: SupplyChainFindingKind; + severity: SupplyChainSeverity; + confidence: EvidenceConfidence; + summary: string; + package: { name: string; version?: string; purl?: string }; + /** Manifests among the report's paths that declare this package. */ + manifestPaths: string[]; + advisoryId?: string; + fixedVersion?: string; + licenseId?: string; + policy?: string; + sourceUrl?: string; +}; + +/** + * External scanner/SBOM findings for packages declared in manifests the report covers. + * Claims are shown as supplied; FixMap never fetched, scanned, or verified them. + */ +export type ReportSupplyChain = { + supplyChainVersion: 1; + source: { + tool: string; + toolVersion: string; + databaseVersion?: string; + /** Producer-declared fingerprint of the original scanner document. */ + documentFingerprint: string; + generatedAt: string; + /** SHA-256 of the exact bundle bytes FixMap read. */ + documentSha256: string; + }; + findings: ReportSupplyChainFinding[]; + /** Bundle findings not attached: their manifests are outside the report, or the size bound was reached. */ + omittedFindings: number; +}; + +export const MAX_REPORT_SUPPLY_CHAIN_FINDINGS = 50; + +const SEVERITIES: readonly string[] = ["critical", "high", "medium", "low", "info", "unknown"]; + +export function buildReportSupplyChain( + bundle: SupplyChainEvidenceBundle, + documentSha256: string, + focusPaths: ReadonlySet +): ReportSupplyChain { + const components = new Map(bundle.components.map((component) => [component.id, component])); + const relevant: ReportSupplyChainFinding[] = []; + for (const finding of bundle.findings) { + const component = components.get(finding.componentId); + const manifestPaths = component?.paths.filter((path) => focusPaths.has(path)) ?? []; + if (!component || manifestPaths.length === 0) continue; + relevant.push({ + id: finding.id, + kind: finding.kind, + severity: finding.severity, + confidence: finding.confidence, + summary: finding.summary, + package: { + name: component.name, + ...(component.version ? { version: component.version } : {}), + ...(component.purl ? { purl: component.purl } : {}) + }, + manifestPaths, + ...(finding.advisoryId ? { advisoryId: finding.advisoryId } : {}), + ...(finding.fixedVersion ? { fixedVersion: finding.fixedVersion } : {}), + ...(finding.licenseId ? { licenseId: finding.licenseId } : {}), + ...(finding.policy ? { policy: finding.policy } : {}), + ...(finding.sourceUrl ? { sourceUrl: finding.sourceUrl } : {}) + }); + } + // The validated bundle is already ordered by severity, then id. + const findings = relevant.slice(0, MAX_REPORT_SUPPLY_CHAIN_FINDINGS); + return { + supplyChainVersion: 1, + source: { + tool: bundle.source.tool, + toolVersion: bundle.source.toolVersion, + ...(bundle.source.databaseVersion ? { databaseVersion: bundle.source.databaseVersion } : {}), + documentFingerprint: bundle.source.documentFingerprint, + generatedAt: bundle.generatedAt, + documentSha256 + }, + findings, + omittedFindings: bundle.findings.length - findings.length + }; +} + +export function renderSupplyChainReportMarkdown(evidence: ReportSupplyChain): string[] { + const { source } = evidence; + return [ + "", + "## Supply-Chain Evidence", + "", + `Imported from ${markdownCode(source.tool)} ${inlineProse(source.toolVersion)}` + + `${source.databaseVersion ? `, database ${inlineProse(source.databaseVersion)}` : ""}, generated ${source.generatedAt} ` + + `(bundle sha256 ${markdownCode(source.documentSha256)}). Findings are shown as supplied; FixMap did not fetch advisories, run a scanner, or verify exploitability.`, + "", + ...(evidence.findings.length > 0 + ? evidence.findings.map((finding) => { + const details = [ + finding.advisoryId && `advisory ${markdownCode(finding.advisoryId)}`, + finding.fixedVersion && `fixed in ${markdownCode(finding.fixedVersion)}`, + finding.licenseId && `license ${markdownCode(finding.licenseId)}`, + finding.policy && `policy ${inlineProse(finding.policy)}` + ].filter(Boolean).join("; "); + const name = `${finding.package.name}${finding.package.version ? `@${finding.package.version}` : ""}`; + return `- **${finding.severity}** ${finding.kind} for ${markdownCode(name)} declared in ${finding.manifestPaths.map(markdownCode).join(", ")}: ` + + `${inlineProse(finding.summary)}${details ? ` (${details})` : ""}`; + }) + : ["- No imported findings are for packages declared in manifests among this report's files."]), + ...(evidence.omittedFindings > 0 + ? ["", `${evidence.omittedFindings} further finding${evidence.omittedFindings === 1 ? " was" : "s were"} for manifests outside this report or over the listing limit.`] + : []) + ]; +} + +export function isReportSupplyChain(candidate: unknown): candidate is ReportSupplyChain { + if (!isRecord(candidate) || candidate.supplyChainVersion !== 1 || !isRecord(candidate.source)) return false; + const source = candidate.source; + if (!text(source.tool, 100) || !text(source.toolVersion, 100) || !optionalText(source.databaseVersion, 200) || + typeof source.documentFingerprint !== "string" || !/^sha256:[a-f0-9]{64}$/.test(source.documentFingerprint) || + typeof source.generatedAt !== "string" || !Number.isFinite(Date.parse(source.generatedAt)) || + typeof source.documentSha256 !== "string" || !/^[a-f0-9]{64}$/.test(source.documentSha256) || + !Number.isSafeInteger(candidate.omittedFindings) || (candidate.omittedFindings as number) < 0 || + !Array.isArray(candidate.findings) || candidate.findings.length > MAX_REPORT_SUPPLY_CHAIN_FINDINGS) return false; + return candidate.findings.every((finding) => isRecord(finding) && + text(finding.id, 80) && ["vulnerability", "outdated-version", "license-policy"].includes(String(finding.kind)) && + SEVERITIES.includes(String(finding.severity)) && ["low", "medium", "high"].includes(String(finding.confidence)) && + text(finding.summary, 1_000) && isRecord(finding.package) && text(finding.package.name, 300) && + optionalText(finding.package.version, 300) && + (finding.package.purl === undefined || (typeof finding.package.purl === "string" && finding.package.purl.startsWith("pkg:"))) && + Array.isArray(finding.manifestPaths) && finding.manifestPaths.length > 0 && finding.manifestPaths.every(isRepositoryRelativePath) && + optionalText(finding.advisoryId, 300) && optionalText(finding.fixedVersion, 300) && + optionalText(finding.licenseId, 200) && optionalText(finding.policy, 500) && + (finding.sourceUrl === undefined || (typeof finding.sourceUrl === "string" && finding.sourceUrl.startsWith("https://")))); +} + +function text(value: unknown, max: number): boolean { + return typeof value === "string" && value.trim().length > 0 && value.length <= max; +} + +function optionalText(value: unknown, max: number): boolean { + return value === undefined || text(value, max); +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} diff --git a/packages/core/src/report.ts b/packages/core/src/report.ts index 218b8b5..34b663f 100644 --- a/packages/core/src/report.ts +++ b/packages/core/src/report.ts @@ -10,7 +10,9 @@ import { buildImpactMap } from "./impact.js"; import { DEFAULT_CONTEXT_FILE_LIMIT, rankContextFiles, rankContextFilesEvidenceDetailed } from "./rank.js"; import { extractTaskSignals, tokenizePath } from "./signals.js"; import { findGatedTestDiagnostics } from "./test-gates.js"; -import { markdownCode } from "./markdown.js"; +import { inlineProse, markdownCode } from "./markdown.js"; +import { renderSensitiveDataMarkdown } from "./report-sensitive-data.js"; +import { renderSupplyChainReportMarkdown } from "./report-supply-chain.js"; import { DIAGNOSTIC_TERM_LIMIT, truncateForDiagnostic } from "./text.js"; import { rankContextFilesHybrid } from "./semantic.js"; import type { createCustomLanguageContext } from "./custom-language-context.js"; @@ -874,6 +876,8 @@ export function renderMarkdownReport(report: FixMapReport): string { ...(report.evidence.omittedItems > 0 ? ["", `${report.evidence.omittedItems} further evidence item${report.evidence.omittedItems === 1 ? " was" : "s were"} not about files in this report.`] : []), ...report.evidence.diagnostics.map((diagnostic) => `- **${diagnostic.severity}** ${markdownCode(diagnostic.provider)} ${diagnostic.code}: ${inlineProse(diagnostic.message)}`) ] : []), + ...(report.sensitiveData ? renderSensitiveDataMarkdown(report.sensitiveData) : []), + ...(report.supplyChain ? renderSupplyChainReportMarkdown(report.supplyChain) : []), ...(report.policy ? [ "", "## Architecture Policy", @@ -975,10 +979,6 @@ function describeAnnotationScope(assessment: AnnotationAssessment): string { return `contract ${markdownCode(scope.name)}${scope.path ? ` in ${markdownCode(scope.path)}` : ""}`; } -function inlineProse(value: string): string { - return value.replace(/\s+/g, " ").trim(); -} - function listOrEmpty(lines: string[]): string[] { return lines.length > 0 ? lines : ["- None found"]; } diff --git a/packages/core/src/sensitive-data.ts b/packages/core/src/sensitive-data.ts index 994451f..1e799c5 100644 --- a/packages/core/src/sensitive-data.ts +++ b/packages/core/src/sensitive-data.ts @@ -1,6 +1,6 @@ import { buildImportGraph } from "./import-graph.js"; import type { EvidenceItem, EvidenceProvider, EvidenceProviderResult, EvidenceRelationship } from "./evidence.js"; -import type { RepoFile } from "./types.js"; +import type { RepoFile, RepoMap } from "./types.js"; export type SensitiveDataCategory = "credential" | "token" | "pii" | "payment"; export type SensitiveSinkCategory = "logging" | "network" | "storage" | "analytics"; @@ -10,7 +10,9 @@ type ClassifiedFile = { file: RepoFile; sources: SensitiveDataCategory[]; sinks: const MAX_ANALYZED_FILES = 5_000; const MAX_RELATIONSHIPS = 10_000; -const PROVIDER_VERSION = "1.0.0"; +export const SENSITIVE_DATA_PROVIDER_ID = "fixmap-sensitive-data"; +export const SENSITIVE_DATA_PROVIDER_VERSION = "1.0.0"; +const PROVIDER_VERSION = SENSITIVE_DATA_PROVIDER_VERSION; const SOURCE_RULES: readonly SignalRule[] = [ { id: "credential-password", category: "credential", pattern: /\b(?:password|passwd|credential|client[_-]?secret|api[_-]?key)\b/i }, @@ -31,63 +33,82 @@ const SINK_RULES: readonly SignalRule[] = [ * it never claims that a value flowed, that a sink is unsafe, or that unmatched code is safe. */ export const sensitiveDataFlowEvidenceProvider: EvidenceProvider = { - id: "fixmap-sensitive-data", + id: SENSITIVE_DATA_PROVIDER_ID, version: PROVIDER_VERSION, capabilities: { network: "never", executesCode: false }, collect({ repo }): EvidenceProviderResult { - const codeFiles = repo.files.filter((file) => file.kind === "code"); - const eligible = codeFiles.filter((file) => file.textSampleComplete !== false && file.contentFingerprint); - const selected = eligible.slice(0, MAX_ANALYZED_FILES); - const classified = selected.map(classifyFile).filter((entry) => entry.sources.length > 0 || entry.sinks.length > 0); - const exact = classified; - const skippedFiles = codeFiles.length - selected.length; - const items: EvidenceItem[] = [scopeItem(repo.root, selected.length, skippedFiles)]; - const itemId = new Map(); - - for (const entry of exact) { - for (const category of entry.sources) { - const id = stableId("source", category, entry.file.path); - itemId.set(key(entry.file.path, "source", category), id); - items.push(fileItem(id, entry.file, "source", category)); - } - for (const category of entry.sinks) { - const id = stableId("sink", category, entry.file.path); - itemId.set(key(entry.file.path, "sink", category), id); - items.push(fileItem(id, entry.file, "sink", category)); - } + return collectSensitiveDataSignals(repo); + } +}; + +/** Synchronous core of the provider, shared by Plan and Verify report attachment. */ +export function collectSensitiveDataSignals(repo: Pick): EvidenceProviderResult { + const codeFiles = repo.files.filter((file) => file.kind === "code"); + const eligible = codeFiles.filter((file) => file.textSampleComplete !== false && file.contentFingerprint); + const selected = eligible.slice(0, MAX_ANALYZED_FILES); + const classified = selected.map(classifyFile).filter((entry) => entry.sources.length > 0 || entry.sinks.length > 0); + const exact = classified; + const skippedFiles = codeFiles.length - selected.length; + const items: EvidenceItem[] = [scopeItem(repo.root, selected.length, skippedFiles)]; + const itemId = new Map(); + + for (const entry of exact) { + for (const category of entry.sources) { + const id = stableId("source", category, entry.file.path); + itemId.set(key(entry.file.path, "source", category), id); + items.push(fileItem(id, entry.file, "source", category)); + } + for (const category of entry.sinks) { + const id = stableId("sink", category, entry.file.path); + itemId.set(key(entry.file.path, "sink", category), id); + items.push(fileItem(id, entry.file, "sink", category)); } + } - const relationships: EvidenceRelationship[] = []; - const relationshipIds = new Set(); - for (const entry of exact) { - for (const source of entry.sources) for (const sink of entry.sinks) { - pushRelationship(relationships, relationshipIds, { - from: itemId.get(key(entry.file.path, "source", source))!, - to: itemId.get(key(entry.file.path, "sink", sink))!, - relation: "same-file-sensitive-signal-and-sink", - reason: `${entry.file.path} contains both ${source} vocabulary and a ${sink} call pattern; value flow was not verified.` - }); - } + const relationships: EvidenceRelationship[] = []; + const relationshipIds = new Set(); + for (const entry of exact) { + for (const source of entry.sources) for (const sink of entry.sinks) { + pushRelationship(relationships, relationshipIds, { + from: itemId.get(key(entry.file.path, "source", source))!, + to: itemId.get(key(entry.file.path, "sink", sink))!, + relation: "same-file-sensitive-signal-and-sink", + reason: `${entry.file.path} contains both ${source} vocabulary and a ${sink} call pattern; value flow was not verified.` + }); } + } - const graph = buildImportGraph(repo.files); - const byPath = new Map(exact.map((entry) => [entry.file.path, entry])); - for (const [fromPath, targets] of graph.imports) { - const from = byPath.get(fromPath); - if (!from) continue; - for (const toPath of targets) { - const to = byPath.get(toPath); - if (!to) continue; - connectAcrossImport(relationships, relationshipIds, itemId, from, to); - connectAcrossImport(relationships, relationshipIds, itemId, to, from); - } + const graph = buildImportGraph(repo.files); + const byPath = new Map(exact.map((entry) => [entry.file.path, entry])); + for (const [fromPath, targets] of graph.imports) { + const from = byPath.get(fromPath); + if (!from) continue; + for (const toPath of targets) { + const to = byPath.get(toPath); + if (!to) continue; + connectAcrossImport(relationships, relationshipIds, itemId, from, to); + connectAcrossImport(relationships, relationshipIds, itemId, to, from); } - return { - items: items.sort((a, b) => a.id.localeCompare(b.id)), - relationships: relationships.slice(0, MAX_RELATIONSHIPS).sort((a, b) => a.id.localeCompare(b.id)) - }; } -}; + return { + items: items.sort((a, b) => a.id.localeCompare(b.id)), + relationships: relationships.slice(0, MAX_RELATIONSHIPS).sort((a, b) => a.id.localeCompare(b.id)) + }; +} + +/** + * First 1-based line on which any of the given rules matches, so reports can point at a + * location without quoting it. Returns undefined when no single line matches. + */ +export function sensitiveSignalLine(text: string, ruleIds: readonly string[]): number | undefined { + const rules = [...SOURCE_RULES, ...SINK_RULES].filter((rule) => ruleIds.includes(rule.id)); + if (rules.length === 0) return undefined; + const lines = text.split(/\r?\n/); + for (let index = 0; index < lines.length; index += 1) { + if (rules.some((rule) => rule.pattern.test(lines[index]!))) return index + 1; + } + return undefined; +} function classifyFile(file: RepoFile): ClassifiedFile { return { diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index 04597d8..922557b 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -2,6 +2,8 @@ import type { AnnotationAssessment } from "./annotations.js"; import type { DecisionRecord } from "./decisions.js"; import type { ArchitecturePolicyResult } from "./architecture.js"; import type { ReportEvidence } from "./report-evidence.js"; +import type { ReportSensitiveData } from "./report-sensitive-data.js"; +import type { ReportSupplyChain } from "./report-supply-chain.js"; export type FixMapInput = { repoRoot: string; @@ -294,6 +296,10 @@ export type FixMapReport = { policy?: ArchitecturePolicyResult; /** Evidence from explicitly supplied providers about files in this report; never fetched or executed. */ evidence?: ReportEvidence; + /** Opt-in lexical sensitive-data flows touching this report's files; locations and kinds only. */ + sensitiveData?: ReportSensitiveData; + /** Imported scanner/SBOM findings for packages declared in manifests among this report's files. */ + supplyChain?: ReportSupplyChain; /** Explicitly registered custom language adapters used for this report; callbacks are never serialized. */ languageAdapters?: ReportLanguageAdapter[]; }; @@ -321,7 +327,8 @@ export type VerifyFinding = { | "architecture-boundary-violation" | "architecture-required-test" | "architecture-review-required" - | "architecture-breaking-contract"; + | "architecture-breaking-contract" + | "sensitive-data-flow-introduced"; severity: "info" | "warning" | "error"; paths: string[]; message: string; @@ -340,6 +347,8 @@ export type VerifyResult = { diagnostics: ScanDiagnostic[]; impact?: ImpactMap; narrative?: VerifyNarrativeStatement[]; + /** Opt-in lexical sensitive-data flows touching the plan or diff, with newly introduced ones marked. */ + sensitiveData?: ReportSensitiveData; }; export type VerifyNarrativeEvidence = { diff --git a/packages/core/src/validate.ts b/packages/core/src/validate.ts index d2821b8..ae7292e 100644 --- a/packages/core/src/validate.ts +++ b/packages/core/src/validate.ts @@ -1,6 +1,9 @@ import type { FixMapReport } from "./types.js"; import { validateAnnotationStore } from "./annotations.js"; import { isDecisionPullRequestUrl } from "./decisions.js"; +import { isRepositoryRelativePath } from "./paths.js"; +import { isReportSensitiveData } from "./report-sensitive-data.js"; +import { isReportSupplyChain } from "./report-supply-chain.js"; export type ValidatedFixMapReport = | { success: true; report: FixMapReport } @@ -195,6 +198,14 @@ export function validateFixMapReport(candidate: unknown, label: string): Validat } } + if (record.sensitiveData !== undefined && !isReportSensitiveData(record.sensitiveData)) { + return { success: false, message: `${label} has invalid sensitiveData; it needs sensitiveDataVersion 1, the fixmap-sensitive-data provider, counts, and at most 50 flows with safe paths, known categories, and rule ids.` }; + } + + if (record.supplyChain !== undefined && !isReportSupplyChain(record.supplyChain)) { + return { success: false, message: `${label} has invalid supplyChain; it needs supplyChainVersion 1, tool and bundle provenance, omittedFindings, and at most 50 findings with manifest paths.` }; + } + if (record.languageAdapters !== undefined) { const adapters = record.languageAdapters; if (!Array.isArray(adapters) || adapters.length > 32 || !adapters.every((adapter) => @@ -387,15 +398,6 @@ function isRepositoryRelativePathArray(candidate: unknown): candidate is string[ return Array.isArray(candidate) && candidate.every(isRepositoryRelativePath); } -function isRepositoryRelativePath(candidate: unknown): candidate is string { - if (typeof candidate !== "string" || !candidate.trim() || candidate.includes("\0") || - /^[\\/]/.test(candidate) || /^[A-Za-z]:/.test(candidate)) { - return false; - } - const segments = candidate.replace(/\\/g, "/").split("/"); - return segments.every((segment) => segment.length > 0 && segment !== "." && segment !== ".."); -} - function isNullableFiniteNumber(candidate: unknown): boolean { return candidate === null || (typeof candidate === "number" && Number.isFinite(candidate)); } diff --git a/packages/core/src/verify.ts b/packages/core/src/verify.ts index 3e62eb5..741ebc5 100644 --- a/packages/core/src/verify.ts +++ b/packages/core/src/verify.ts @@ -14,8 +14,17 @@ import type { FixMapReport, ImpactMap, RepoMap, VerifyFinding, VerifyNarrativeSt import { markdownCode } from "./markdown.js"; import { architecturePolicyFromRepo, evaluateArchitecturePolicy } from "./architecture.js"; import type { ArchitecturePolicyFinding, ArchitecturePolicyResult } from "./architecture.js"; +import { reportPaths } from "./report-evidence.js"; +import { buildReportSensitiveData, renderSensitiveDataMarkdown, sensitiveDataVerifyFinding } from "./report-sensitive-data.js"; -export function verifyPlan(report: FixMapReport, repo: RepoMap): VerifyResult { +export function verifyPlan( + report: FixMapReport, + repo: RepoMap, + options: { + /** Attach lexical sensitive-data flows and add an advisory finding for flows the diff introduced. */ + sensitiveData?: boolean; + } = {} +): VerifyResult { const changed = repo.changedFiles; const findings: VerifyFinding[] = []; const fileByPath = new Map(repo.files.map((file) => [file.path, file])); @@ -230,13 +239,25 @@ export function verifyPlan(report: FixMapReport, repo: RepoMap): VerifyResult { }); } + // 7. Opt-in and advisory: possible sensitive-data flows the diff added. Lexical evidence only. + const sensitiveData = options.sensitiveData + ? buildReportSensitiveData( + repo, + new Set([...reportPaths(report), ...changed, ...impact.files.map((file) => file.path)]), + { compareWithDiff: true } + ) + : undefined; + const sensitiveFinding = sensitiveData ? sensitiveDataVerifyFinding(sensitiveData) : undefined; + if (sensitiveFinding) findings.push(sensitiveFinding); + return { summary: buildVerifySummary(changed.length, findings), changedFiles: changed, findings, diagnostics: repo.diagnostics, impact, - narrative: buildVerifyNarrative(report, changed, changedSource, changedTests, impact, newRisks, policy) + narrative: buildVerifyNarrative(report, changed, changedSource, changedTests, impact, newRisks, policy), + ...(sensitiveData ? { sensitiveData } : {}) }; } @@ -405,5 +426,6 @@ export function renderVerifyMarkdown(result: VerifyResult): string { ) : ["- None found"])); } + if (result.sensitiveData) lines.push(...renderSensitiveDataMarkdown(result.sensitiveData)); return `${lines.join("\n")}\n`; } diff --git a/packages/core/test/report-sensitive-supply.test.ts b/packages/core/test/report-sensitive-supply.test.ts new file mode 100644 index 0000000..4ddcd65 --- /dev/null +++ b/packages/core/test/report-sensitive-supply.test.ts @@ -0,0 +1,278 @@ +import { execFile } from "node:child_process"; +import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { promisify } from "node:util"; +import { describe, expect, it } from "vitest"; +import { buildFixMapAnalysis } from "../src/plan.js"; +import { renderMarkdownReport } from "../src/report.js"; +import { buildReportSupplyChain } from "../src/report-supply-chain.js"; +import { validateSupplyChainEvidenceBundle } from "../src/supply-chain.js"; +import type { RepoFile, RepoMap, FixMapReport } from "../src/types.js"; +import { validateFixMapReport } from "../src/validate.js"; +import { renderVerifyMarkdown, verifyPlan } from "../src/verify.js"; + +const exec = promisify(execFile); +const SECRET = "sk_live_SUPERSECRET_9f8e7d6c"; +const PERSONAL = "hunter2-ZZTOP-4417"; + +async function git(root: string, ...args: string[]): Promise { + await exec("git", args, { cwd: root }); +} + +async function createRepo(files: Record): Promise { + const root = await mkdtemp(join(tmpdir(), "fixmap-sensitive-")); + for (const [path, contents] of Object.entries(files)) { + await mkdir(join(root, path, ".."), { recursive: true }); + await writeFile(join(root, path), contents); + } + await git(root, "init", "-q"); + await git(root, "add", "-A"); + await git(root, "-c", "user.name=FixMap Test", "-c", "user.email=test@example.invalid", "commit", "-qm", "initial"); + return root; +} + +function bundle(): ReturnType { + return validateSupplyChainEvidenceBundle({ + supplyChainBundleVersion: 1, + generatedAt: "2026-11-01T00:00:00Z", + source: { tool: "external-scanner", toolVersion: "4.2.0", databaseVersion: "advisories-2026-11-01", documentFingerprint: `sha256:${"a".repeat(64)}` }, + components: [ + { id: "npm-left-pad", name: "left-pad", version: "1.0.0", purl: "pkg:npm/left-pad@1.0.0", licenses: ["MIT"], paths: ["package.json"] }, + { id: "npm-billing-lib", name: "billing-lib", version: "2.0.0", licenses: ["GPL-3.0"], paths: ["services/billing/package.json"] } + ], + findings: [ + { id: "adv-1", kind: "vulnerability", severity: "high", confidence: "high", componentId: "npm-left-pad", summary: "Advisory matched left-pad.", advisoryId: "GHSA-xxxx-yyyy-zzzz", fixedVersion: "1.0.1", sourceUrl: "https://github.com/advisories/GHSA-xxxx-yyyy-zzzz" }, + { id: "lic-1", kind: "license-policy", severity: "medium", confidence: "medium", componentId: "npm-billing-lib", summary: "GPL license denied by policy.", licenseId: "GPL-3.0", policy: "deny-copyleft" } + ] + }); +} + +describe("sensitive-data evidence in plans", () => { + it("attaches flows touching ranked files, omits others, and never copies matched values", async () => { + const root = await createRepo({ + "package.json": JSON.stringify({ scripts: { test: "vitest run" } }), + "src/auth/session.ts": `export function startSession() {\n const apiKey = "${SECRET}";\n console.log("session started", apiKey);\n}\n`, + "src/reports/export.ts": `export function exportReport(url: string) {\n const password = "${PERSONAL}";\n return fetch(url, { body: password });\n}\n` + }); + try { + const { report } = await buildFixMapAnalysis({ repoRoot: root, issueText: "startSession session auth", limit: 1, sensitiveData: true }); + expect(report.contextFiles.map((file) => file.path)).toEqual(["src/auth/session.ts"]); + expect(report.sensitiveData?.flows).toEqual([{ + relation: "same-file", + source: { path: "src/auth/session.ts", category: "credential", ruleIds: ["credential-password"], line: 2 }, + sink: { path: "src/auth/session.ts", category: "logging", ruleIds: ["sink-log"], line: 3 } + }]); + expect(report.sensitiveData).toMatchObject({ completeness: "not-a-security-proof", omittedFlows: 0, provider: { id: "fixmap-sensitive-data" } }); + expect(report.sensitiveData?.introducedCheck).toBeUndefined(); + const markdown = renderMarkdownReport(report); + expect(markdown).toContain("## Sensitive Data"); + expect(markdown).toContain("`src/auth/session.ts:2`"); + for (const output of [JSON.stringify(report), markdown]) { + expect(output).not.toContain(SECRET); + expect(output).not.toContain(PERSONAL); + } + expect(validateFixMapReport(report, "sensitive report")).toMatchObject({ success: true }); + + const { report: plain } = await buildFixMapAnalysis({ repoRoot: root, issueText: "startSession session auth", limit: 1 }); + expect(plain.sensitiveData).toBeUndefined(); + expect(renderMarkdownReport(plain)).not.toContain("## Sensitive Data"); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); + + it("rejects tampered sensitiveData fields", async () => { + const root = await createRepo({ + "src/auth/session.ts": `const apiKey = "${SECRET}";\nconsole.log(apiKey);\n` + }); + try { + const { report } = await buildFixMapAnalysis({ repoRoot: root, issueText: "session apiKey", sensitiveData: true }); + const evidence = report.sensitiveData!; + const flow = evidence.flows[0]!; + for (const tampered of [ + { ...evidence, sensitiveDataVersion: 2 }, + { ...evidence, completeness: "complete" }, + { ...evidence, omittedFlows: -1 }, + { ...evidence, flows: [{ ...flow, source: { ...flow.source, path: "../outside.ts" } }] }, + { ...evidence, flows: [{ ...flow, sink: { ...flow.sink, category: "email" } }] }, + { ...evidence, flows: [{ ...flow, source: { ...flow.source, ruleIds: [SECRET] } }] }, + { ...evidence, flows: [{ ...flow, sink: { ...flow.sink, path: "src/other.ts" } }] }, + { ...evidence, flows: Array.from({ length: 51 }, () => flow) } + ]) { + expect(validateFixMapReport({ ...report, sensitiveData: tampered }, "tampered")).toMatchObject({ success: false }); + } + } finally { + await rm(root, { recursive: true, force: true }); + } + }); +}); + +describe("supply-chain evidence in plans", () => { + it("attaches findings for manifests among the report's paths with provenance", async () => { + const root = await createRepo({ + "package.json": JSON.stringify({ dependencies: { "left-pad": "1.0.0" } }), + "services/billing/package.json": JSON.stringify({ dependencies: { "billing-lib": "2.0.0" } }), + "src/index.ts": "export const ready = true;\n" + }); + try { + await writeFile(join(root, "package.json"), JSON.stringify({ dependencies: { "left-pad": "1.0.1" } })); + const sha = "b".repeat(64); + const { report } = await buildFixMapAnalysis({ + repoRoot: root, issueText: "upgrade left-pad", workingTree: true, supplyChain: { bundle: bundle(), documentSha256: sha } + }); + expect(report.changedFiles).toEqual(["package.json"]); + expect(report.supplyChain?.source).toEqual({ + tool: "external-scanner", toolVersion: "4.2.0", databaseVersion: "advisories-2026-11-01", + documentFingerprint: `sha256:${"a".repeat(64)}`, generatedAt: "2026-11-01T00:00:00.000Z", documentSha256: sha + }); + expect(report.supplyChain?.findings).toEqual([expect.objectContaining({ + id: "adv-1", severity: "high", manifestPaths: ["package.json"], advisoryId: "GHSA-xxxx-yyyy-zzzz", fixedVersion: "1.0.1", + package: { name: "left-pad", version: "1.0.0", purl: "pkg:npm/left-pad@1.0.0" } + })]); + expect(report.supplyChain?.omittedFindings).toBe(1); + const markdown = renderMarkdownReport(report); + expect(markdown).toContain("## Supply-Chain Evidence"); + expect(markdown).toContain("`left-pad@1.0.0` declared in `package.json`"); + expect(markdown).not.toContain("billing-lib"); + expect(validateFixMapReport(report, "supply report")).toMatchObject({ success: true }); + + const supply = report.supplyChain!; + const finding = supply.findings[0]!; + for (const tampered of [ + { ...supply, supplyChainVersion: 2 }, + { ...supply, source: { ...supply.source, documentSha256: "not-a-digest" } }, + { ...supply, source: { ...supply.source, tool: "" } }, + { ...supply, omittedFindings: 1.5 }, + { ...supply, findings: [{ ...finding, manifestPaths: ["/etc/package.json"] }] }, + { ...supply, findings: [{ ...finding, manifestPaths: [] }] }, + { ...supply, findings: [{ ...finding, severity: "catastrophic" }] }, + { ...supply, findings: [{ ...finding, sourceUrl: "http://example.com/advisory" }] } + ]) { + expect(validateFixMapReport({ ...report, supplyChain: tampered }, "tampered")).toMatchObject({ success: false }); + } + } finally { + await rm(root, { recursive: true, force: true }); + } + }); + + it("attaches nothing when no manifest is among the report's paths", () => { + const supply = buildReportSupplyChain(bundle(), "c".repeat(64), new Set(["src/index.ts"])); + expect(supply.findings).toEqual([]); + expect(supply.omittedFindings).toBe(2); + expect(buildReportSupplyChain(bundle(), "c".repeat(64), new Set(["services/billing/package.json"])).findings.map((finding) => finding.id)).toEqual(["lic-1"]); + }); + + it("rejects malformed bundles before attachment", () => { + const valid = { + supplyChainBundleVersion: 1, generatedAt: "2026-11-01T00:00:00Z", + source: { tool: "scanner", toolVersion: "1", documentFingerprint: `sha256:${"a".repeat(64)}` }, + components: [{ id: "c1", name: "x", licenses: [], paths: ["package.json"] }], + findings: [] + }; + expect(() => validateSupplyChainEvidenceBundle({ ...valid, supplyChainBundleVersion: 2 })).toThrow("envelope"); + expect(() => validateSupplyChainEvidenceBundle({ ...valid, components: [{ ...valid.components[0], paths: ["../package.json"] }] })).toThrow("component"); + expect(() => validateSupplyChainEvidenceBundle({ ...valid, findings: [{ id: "f", kind: "vulnerability", severity: "high", confidence: "high", componentId: "missing", summary: "x" }] })).toThrow("finding"); + }); +}); + +function file(path: string, textSample: string): RepoFile { + return { + path, extension: ".ts", sizeBytes: textSample.length, isSource: true, isTest: false, kind: "code", + textSample, textSampleComplete: true, contentFingerprint: `git:${"0".repeat(40)}` + }; +} + +function verifyRepo(files: RepoFile[], changedFiles: string[], diffText: string, diagnostics: RepoMap["diagnostics"] = []): RepoMap { + return { root: "/repo", files, packageScripts: [], changedFiles, trackedFiles: files.map((entry) => entry.path), diffText, packageManager: "npm", diagnostics }; +} + +function plan(path: string): FixMapReport { + return { + summary: "", + contextFiles: [{ rank: 1, path, score: 10, confidence: "high", reasons: ["path matches task terms"] }], + testRoutes: [], risks: [], changedFiles: [], diagnostics: [] + }; +} + +describe("sensitive-data evidence in verify", () => { + const sessionAfter = `export function refresh() {\n const accessToken = "${SECRET}";\n console.log("refreshed", accessToken);\n return accessToken;\n}\n`; + const sessionDiff = [ + "diff --git a/src/auth/session.ts b/src/auth/session.ts", + "index 1111111..2222222 100644", + "--- a/src/auth/session.ts", + "+++ b/src/auth/session.ts", + "@@ -1,4 +1,5 @@", + " export function refresh() {", + ` const accessToken = "${SECRET}";`, + "+ console.log(\"refreshed\", accessToken);", + " return accessToken;", + " }", + "" + ].join("\n"); + const existing = file("src/payments/charge.ts", "const cardNumber = input.cardNumber;\nlogger.info(\"charging\", cardNumber);\nexport const touched = 2;\n"); + const existingDiff = [ + "diff --git a/src/payments/charge.ts b/src/payments/charge.ts", + "--- a/src/payments/charge.ts", + "+++ b/src/payments/charge.ts", + "@@ -3 +3 @@", + "-export const touched = 1;", + "+export const touched = 2;", + "" + ].join("\n"); + + it("adds an advisory finding only for flows the diff introduced", () => { + const repo = verifyRepo([file("src/auth/session.ts", sessionAfter), existing], ["src/auth/session.ts", "src/payments/charge.ts"], sessionDiff + existingDiff); + const result = verifyPlan(plan("src/auth/session.ts"), repo, { sensitiveData: true }); + expect(result.sensitiveData?.introducedCheck).toBe("compared-with-diff"); + const flows = result.sensitiveData!.flows; + expect(flows.find((flow) => flow.source.path === "src/auth/session.ts")).toMatchObject({ relation: "same-file", introducedByDiff: true, source: { category: "token" }, sink: { category: "logging", line: 3 } }); + expect(flows.find((flow) => flow.source.path === "src/payments/charge.ts")).not.toHaveProperty("introducedByDiff"); + const finding = result.findings.find((entry) => entry.code === "sensitive-data-flow-introduced"); + expect(finding).toMatchObject({ severity: "info", paths: ["src/auth/session.ts"] }); + expect(finding?.message).toContain("token → logging"); + const markdown = renderVerifyMarkdown(result); + expect(markdown).toContain("## Sensitive Data"); + expect(markdown).toContain("**new**"); + for (const output of [JSON.stringify(result), markdown]) expect(output).not.toContain(SECRET); + }); + + it("marks a flow introduced by a new import as new", () => { + const logger = file("src/auth/logger.ts", "export function write(message: string) { console.log(message); }\n"); + const session = file("src/auth/session.ts", "import { write } from \"./logger\";\nconst password = readPassword();\nwrite(\"ok\");\n"); + const diff = [ + "diff --git a/src/auth/session.ts b/src/auth/session.ts", + "--- a/src/auth/session.ts", + "+++ b/src/auth/session.ts", + "@@ -0,0 +1 @@", + "+import { write } from \"./logger\";", + "" + ].join("\n"); + const result = verifyPlan(plan("src/auth/session.ts"), verifyRepo([logger, session], ["src/auth/session.ts"], diff), { sensitiveData: true }); + expect(result.sensitiveData?.flows).toContainEqual(expect.objectContaining({ + relation: "direct-import", introducedByDiff: true, + source: expect.objectContaining({ path: "src/auth/session.ts", category: "credential" }), + sink: expect.objectContaining({ path: "src/auth/logger.ts", category: "logging" }) + })); + expect(result.findings.map((entry) => entry.code)).toContain("sensitive-data-flow-introduced"); + }); + + it("raises no finding for unchanged flows, a truncated diff, or when not requested", () => { + const unchanged = verifyPlan(plan("src/payments/charge.ts"), verifyRepo([existing], ["src/payments/charge.ts"], existingDiff), { sensitiveData: true }); + expect(unchanged.sensitiveData?.flows).toHaveLength(1); + expect(unchanged.findings.map((entry) => entry.code)).not.toContain("sensitive-data-flow-introduced"); + + const truncated = verifyPlan( + plan("src/auth/session.ts"), + verifyRepo([file("src/auth/session.ts", sessionAfter)], ["src/auth/session.ts"], sessionDiff, [{ code: "diff-text-truncated", severity: "warning", message: "sampled" }]), + { sensitiveData: true } + ); + expect(truncated.sensitiveData?.introducedCheck).toBe("unavailable-diff-truncated"); + expect(truncated.findings.map((entry) => entry.code)).not.toContain("sensitive-data-flow-introduced"); + expect(renderVerifyMarkdown(truncated)).toContain("could not be identified"); + + const off = verifyPlan(plan("src/auth/session.ts"), verifyRepo([file("src/auth/session.ts", sessionAfter)], ["src/auth/session.ts"], sessionDiff)); + expect(off.sensitiveData).toBeUndefined(); + expect(off.findings.map((entry) => entry.code)).not.toContain("sensitive-data-flow-introduced"); + }); +});