From b5bd74e425fbf9c57c03d87864fd497ee0f7f212 Mon Sep 17 00:00:00 2001 From: Aryam Goyal Date: Mon, 23 Nov 2026 19:41:37 +0530 Subject: [PATCH 1/5] feat(action): preview contracts, reviewers, and architecture drift Adds three preview Action inputs backed by the existing Core engines: - contracts (plan and verify modes): exact-ref contract diff without checkout, a bounded "Contract changes" section, and the breaking-contract-count output. Breaking changes never fail the step. - reviewers (+ reviewers-history-authors): a bounded "Suggested reviewers" section for the changed paths. Names print without "@" and no review is requested. - architecture-drift: a bounded "Architecture drift" section from base/head Git objects (edges, cycles, policy violations, decision disagreements). Missing refs degrade to a warning and a notice. The JSON report contract is unchanged. Bundle rebuilt. Co-Authored-By: Claude Opus 5.5 --- action.yml | 36 + packages/action/action.yml | 36 + packages/action/dist/index.mjs | 867 +++++++++++++++++-- packages/action/src/review-sections.ts | 249 ++++++ packages/action/src/runner.ts | 102 ++- packages/action/src/scope-sections.ts | 4 +- packages/action/test/review-sections.test.ts | 243 ++++++ 7 files changed, 1456 insertions(+), 81 deletions(-) create mode 100644 packages/action/src/review-sections.ts create mode 100644 packages/action/test/review-sections.test.ts diff --git a/action.yml b/action.yml index 08a990e..378d9e2 100644 --- a/action.yml +++ b/action.yml @@ -98,6 +98,40 @@ inputs: A missing or invalid store degrades to a warning. Read-only: the Action never writes the store. required: false + contracts: + description: >- + Preview. Plan and verify modes. On pull requests with both base and head refs fetched, + compares OpenAPI, AsyncAPI, GraphQL, Protobuf, JSON Schema, and SQL migration contracts at + the two exact commits from Git objects without a checkout, with the same Core engine as + fixmap contracts diff, and adds a bounded "Contract changes" section (breaking, unknown, and + compatible counts plus the top changes with paths). Breaking changes are advisory and never + fail the step; only fail-on in verify mode does. Missing refs degrade to a warning. + required: false + default: "false" + reviewers: + description: >- + Preview. Plan mode only. Adds a bounded "Suggested reviewers" section for the changed paths + (or, without a diff, the ranked context files) from CODEOWNERS, annotation owners, + architecture-policy reviewers, and recent commit authors, with the same Core engine as + fixmap reviewers. Suggestions only: the Action never requests reviews and prints names + without "@", so nobody is notified. + required: false + default: "false" + reviewers-history-authors: + description: >- + Preview. With reviewers, set false to leave out commit-author suggestions and use only + CODEOWNERS, annotations, and policy, like fixmap reviewers --no-history-authors. + required: false + default: "true" + architecture-drift: + description: >- + Preview. Plan mode only. On pull requests with both base and head refs fetched, compares + the import architecture at the two exact commits from Git objects without a checkout, with + the same Core engine as fixmap history, and adds a bounded "Architecture drift" section + (added and removed edges, new cycles, policy violations, and decision disagreements). + Missing refs degrade to a warning. + required: false + default: "false" outputs: report: description: The bounded FixMap report, or verification, in the selected format. @@ -111,6 +145,8 @@ outputs: description: Number of changed files compared against the plan. Verify mode only. change-scope-affected-count: description: Preview. Number of affected paths in the change scope. Set only when change-scope-touch or change-scope-add is used. + breaking-contract-count: + description: Preview. Number of breaking contract changes between base and head. Set only when contracts is true and both refs were compared. branding: icon: map color: green diff --git a/packages/action/action.yml b/packages/action/action.yml index 98e7f06..fdcfea4 100644 --- a/packages/action/action.yml +++ b/packages/action/action.yml @@ -98,6 +98,40 @@ inputs: A missing or invalid store degrades to a warning. Read-only: the Action never writes the store. required: false + contracts: + description: >- + Preview. Plan and verify modes. On pull requests with both base and head refs fetched, + compares OpenAPI, AsyncAPI, GraphQL, Protobuf, JSON Schema, and SQL migration contracts at + the two exact commits from Git objects without a checkout, with the same Core engine as + fixmap contracts diff, and adds a bounded "Contract changes" section (breaking, unknown, and + compatible counts plus the top changes with paths). Breaking changes are advisory and never + fail the step; only fail-on in verify mode does. Missing refs degrade to a warning. + required: false + default: "false" + reviewers: + description: >- + Preview. Plan mode only. Adds a bounded "Suggested reviewers" section for the changed paths + (or, without a diff, the ranked context files) from CODEOWNERS, annotation owners, + architecture-policy reviewers, and recent commit authors, with the same Core engine as + fixmap reviewers. Suggestions only: the Action never requests reviews and prints names + without "@", so nobody is notified. + required: false + default: "false" + reviewers-history-authors: + description: >- + Preview. With reviewers, set false to leave out commit-author suggestions and use only + CODEOWNERS, annotations, and policy, like fixmap reviewers --no-history-authors. + required: false + default: "true" + architecture-drift: + description: >- + Preview. Plan mode only. On pull requests with both base and head refs fetched, compares + the import architecture at the two exact commits from Git objects without a checkout, with + the same Core engine as fixmap history, and adds a bounded "Architecture drift" section + (added and removed edges, new cycles, policy violations, and decision disagreements). + Missing refs degrade to a warning. + required: false + default: "false" outputs: report: description: The bounded FixMap report, or verification, in the selected format. @@ -111,6 +145,8 @@ outputs: description: Number of changed files compared against the plan. Verify mode only. change-scope-affected-count: description: Preview. Number of affected paths in the change scope. Set only when change-scope-touch or change-scope-add is used. + breaking-contract-count: + description: Preview. Number of breaking contract changes between base and head. Set only when contracts is true and both refs were compared. branding: icon: map color: green diff --git a/packages/action/dist/index.mjs b/packages/action/dist/index.mjs index c4d2b3d..4cda395 100644 --- a/packages/action/dist/index.mjs +++ b/packages/action/dist/index.mjs @@ -1,14 +1,14 @@ import { createRequire as __fixmapCreateRequire } from 'module'; const require = __fixmapCreateRequire(import.meta.url); // packages/action/src/runner.ts -import { randomUUID as randomUUID3 } from "node:crypto"; +import { randomUUID as randomUUID4 } from "node:crypto"; // packages/action/src/annotations.ts -import { realpath as realpath3, stat as stat3 } from "node:fs/promises"; -import { isAbsolute as isAbsolute3, relative as relative3, resolve as resolve5 } from "node:path"; +import { realpath as realpath3, stat as stat4 } from "node:fs/promises"; +import { isAbsolute as isAbsolute3, relative as relative4, resolve as resolve6 } from "node:path"; // packages/core/dist/plan.js -import { readFile as readFile2 } from "node:fs/promises"; +import { readFile as readFile3 } from "node:fs/promises"; import { join as join3, resolve as resolve3 } from "node:path"; // packages/core/dist/exclude.js @@ -1333,11 +1333,11 @@ function resolveComposerSymbol(project, symbol, repoPaths, suffixPaths) { for (const mapping of project.psr4) { if (!symbol.startsWith(mapping.prefix)) continue; - const relative4 = symbol.slice(mapping.prefix.length).replace(/\\/g, "/"); - if (!relative4) + const relative5 = symbol.slice(mapping.prefix.length).replace(/\\/g, "/"); + if (!relative5) continue; for (const root of mapping.roots) { - const candidate = [root, `${relative4}.php`].filter(Boolean).join("/"); + const candidate = [root, `${relative5}.php`].filter(Boolean).join("/"); if (repoPaths.has(candidate)) targets.add(candidate); } @@ -1637,23 +1637,23 @@ function buildRubyProjects(files) { if (/^\s*gem\s*(?:\(|\s)\s*["']rails["']/im.test(manifest.textSample)) railsEvidence.add(manifest.path); for (const file of scoped) { - const relative4 = root ? file.path.slice(root.length + 1) : file.path; - if (relative4.toLowerCase() === ".rspec" || /(?:^|\/)spec\/(?:spec_helper|rails_helper)\.rb$/i.test(relative4) || /_spec\.rb$/i.test(relative4)) { + const relative5 = root ? file.path.slice(root.length + 1) : file.path; + if (relative5.toLowerCase() === ".rspec" || /(?:^|\/)spec\/(?:spec_helper|rails_helper)\.rb$/i.test(relative5) || /_spec\.rb$/i.test(relative5)) { rspecEvidence.add(file.path); } - if (/(?:^|\/)test\/test_helper\.rb$/i.test(relative4) || /_test\.rb$/i.test(relative4) || /^(?:\s*require\s*\(?\s*["']minitest|\s*class\s+[^\n<]+<\s*(?:Minitest::Test|MiniTest::Unit)\b)/m.test(file.textSample)) { + if (/(?:^|\/)test\/test_helper\.rb$/i.test(relative5) || /_test\.rb$/i.test(relative5) || /^(?:\s*require\s*\(?\s*["']minitest|\s*class\s+[^\n<]+<\s*(?:Minitest::Test|MiniTest::Unit)\b)/m.test(file.textSample)) { minitestEvidence.add(file.path); } } const application = scoped.find((file) => { - const relative4 = root ? file.path.slice(root.length + 1) : file.path; - return relative4.toLowerCase() === "config/application.rb" && /\bclass\s+Application\s*<\s*Rails::Application\b/.test(file.textSample); + const relative5 = root ? file.path.slice(root.length + 1) : file.path; + return relative5.toLowerCase() === "config/application.rb" && /\bclass\s+Application\s*<\s*Rails::Application\b/.test(file.textSample); }); if (application) railsEvidence.add(application.path); const autoloadFiles = railsEvidence.size === 2 ? scoped.filter((file) => { - const relative4 = root ? file.path.slice(root.length + 1) : file.path; - return /^app\/(?!assets(?:\/|$)|javascript(?:\/|$)|views(?:\/|$))[^/]+\/.+\.rb$/i.test(relative4); + const relative5 = root ? file.path.slice(root.length + 1) : file.path; + return /^app\/(?!assets(?:\/|$)|javascript(?:\/|$)|views(?:\/|$))[^/]+\/.+\.rb$/i.test(relative5); }).map((file) => file.path).sort((left, right) => left.localeCompare(right)) : []; const rakefile = scoped.find((file) => file.path.split("/").pop()?.toLowerCase() === "rakefile"); const rakeTestPath = rakefile && /\b(?:Rake::TestTask|task\s*(?:\(|\s)\s*:test\b)/.test(rakefile.textSample) ? rakefile.path : void 0; @@ -1701,9 +1701,9 @@ function rubyTestCommandForProject(project, relatedTests = []) { const testPath = relatedMinitest[0] ?? project.minitestEvidence.find((path) => /_test\.rb$/i.test(path)); if (!testPath) return void 0; - const relative4 = project.root ? testPath.slice(project.root.length + 1) : testPath; + const relative5 = project.root ? testPath.slice(project.root.length + 1) : testPath; return { - command: scopedBundleCommand(project.root, `ruby -Itest ${relative4}`), + command: scopedBundleCommand(project.root, `ruby -Itest ${relative5}`), reason: `${testPath} provides executable Minitest evidence for ${project.path}`, scopeDir: project.root }; @@ -4469,9 +4469,9 @@ function assessAnnotations(store, repo, options) { const validated = validateAnnotationStore(store); const now = parseTimestamp(options.now, "assessment time"); const paths = new Set(repo.files.map((file) => normalizePath(file.path))); - const renames = new Map((options.renames ?? []).map((rename3) => { - const from = validateRelativePath(rename3.from, "rename source"); - const to = validateRelativePath(rename3.to, "rename target"); + const renames = new Map((options.renames ?? []).map((rename4) => { + const from = validateRelativePath(rename4.from, "rename source"); + const to = validateRelativePath(rename4.to, "rename target"); return [from, to]; })); return validated.annotations.map((annotation) => { @@ -5091,6 +5091,60 @@ function evaluateArchitecturePolicy(policy, input) { findings: findings.sort((a, b) => severityOrder(a.severity) - severityOrder(b.severity) || a.ruleId.localeCompare(b.ruleId) || a.paths.join("\0").localeCompare(b.paths.join("\0"))) }; } +function buildArchitectureSnapshot(repo, policy) { + const graph = buildImportGraph(repo.files); + const edges = [...graph.imports].flatMap(([from, targets]) => [...targets].map((to) => ({ from, to }))).sort(edgeOrder); + const cycles = findCycles(edges); + const paths = [...new Set(edges.flatMap((edge) => [edge.from, edge.to]))].sort(); + const coupling = paths.map((path) => { + const incoming = graph.importedBy.get(path)?.size ?? 0; + const outgoing = graph.imports.get(path)?.size ?? 0; + return { path, incoming, outgoing, total: incoming + outgoing }; + }); + const boundaryViolations = policy ? evaluateArchitecturePolicy(policy, { repo }).findings.flatMap((finding) => finding.code === "boundary-violation" && finding.paths[0] && finding.paths[1] ? [{ ruleId: finding.ruleId, from: finding.paths[0], to: finding.paths[1] }] : []).sort(violationOrder) : []; + const incompleteFiles = repo.files.filter((file) => languageAdapterForFile(file) && file.textSampleComplete === false).length; + const canonical = { + edges, + cycles, + coupling, + boundaryViolations, + truncated: { files: graph.truncatedFiles + incompleteFiles, edges: graph.truncatedEdges } + }; + return { + architectureSnapshotVersion: 1, + fingerprint: `architecture:${stableHash3(canonicalize2(canonical))}`, + sourceFingerprint: repoSourceFingerprint(repo), + ...canonical + }; +} +function compareArchitectureSnapshots(previous, current2, options = {}) { + if (previous.architectureSnapshotVersion !== 1 || current2.architectureSnapshotVersion !== 1) { + throw new Error("Unsupported architecture snapshot version."); + } + const previousEdges = new Map(previous.edges.map((edge) => [edgeKey(edge), edge])); + const currentEdges = new Map(current2.edges.map((edge) => [edgeKey(edge), edge])); + const previousCycles = new Map(previous.cycles.map((cycle) => [cycle.join("\0"), cycle])); + const currentCycles = new Map(current2.cycles.map((cycle) => [cycle.join("\0"), cycle])); + const previousViolations = new Map(previous.boundaryViolations.map((value) => [violationKey(value), value])); + const currentViolations = new Map(current2.boundaryViolations.map((value) => [violationKey(value), value])); + const previousCoupling = new Map(previous.coupling.map((value) => [value.path, value.total])); + const minimumDelta = options.couplingDelta ?? 2; + return { + fromFingerprint: previous.fingerprint, + toFingerprint: current2.fingerprint, + addedEdges: mapDifference(currentEdges, previousEdges).sort(edgeOrder), + removedEdges: mapDifference(previousEdges, currentEdges).sort(edgeOrder), + newCycles: mapDifference(currentCycles, previousCycles).sort(cycleOrder), + resolvedCycles: mapDifference(previousCycles, currentCycles).sort(cycleOrder), + newBoundaryViolations: mapDifference(currentViolations, previousViolations).sort(violationOrder), + resolvedBoundaryViolations: mapDifference(previousViolations, currentViolations).sort(violationOrder), + couplingGrowth: current2.coupling.flatMap((value) => { + const before = previousCoupling.get(value.path) ?? 0; + const delta = value.total - before; + return delta >= minimumDelta ? [{ path: value.path, before, after: value.total, delta }] : []; + }).sort((a, b) => b.delta - a.delta || a.path.localeCompare(b.path)) + }; +} function boundaryRule(value, index) { const rule = ruleRecord(value, "boundaries", index); return { @@ -5169,6 +5223,74 @@ function strings(value, label) { function matchesAny(path, patternsToMatch) { return patternsToMatch.some((pattern) => buildPathExcluder([pattern]).excludes(path)); } +function findCycles(edges) { + const adjacency = /* @__PURE__ */ new Map(); + for (const edge of edges) + adjacency.set(edge.from, [...adjacency.get(edge.from) ?? [], edge.to].sort()); + const nodes = [...new Set(edges.flatMap((edge) => [edge.from, edge.to]))].sort(); + const index = /* @__PURE__ */ new Map(); + const low = /* @__PURE__ */ new Map(); + const stack = []; + const onStack = /* @__PURE__ */ new Set(); + const cycles = []; + let next = 0; + const visit = (node) => { + index.set(node, next); + low.set(node, next); + next += 1; + stack.push(node); + onStack.add(node); + for (const neighbor of adjacency.get(node) ?? []) { + if (!index.has(neighbor)) { + visit(neighbor); + low.set(node, Math.min(low.get(node), low.get(neighbor))); + } else if (onStack.has(neighbor)) { + low.set(node, Math.min(low.get(node), index.get(neighbor))); + } + } + if (low.get(node) !== index.get(node)) + return; + const component = []; + let popped; + do { + popped = stack.pop(); + onStack.delete(popped); + component.push(popped); + } while (popped !== node); + component.sort(); + if (component.length > 1 || adjacency.get(component[0])?.includes(component[0])) + cycles.push(component); + }; + for (const node of nodes) + if (!index.has(node)) + visit(node); + return cycles.sort(cycleOrder); +} +function repoSourceFingerprint(repo) { + const unversioned = repo.files.find((file) => !file.contentFingerprint); + if (unversioned) + throw new Error(`Architecture snapshots require an exact content fingerprint for ${unversioned.path}.`); + const sources = repo.files.map((file) => `${file.path}\0${file.contentFingerprint}`).sort(); + return `repository:${stableHash3(sources.join("\0"))}`; +} +function mapDifference(left, right) { + return [...left].flatMap(([key, value]) => right.has(key) ? [] : [value]); +} +function edgeKey(edge) { + return `${edge.from}\0${edge.to}`; +} +function violationKey(value) { + return `${value.ruleId}\0${value.from}\0${value.to}`; +} +function edgeOrder(a, b) { + return a.from.localeCompare(b.from) || a.to.localeCompare(b.to); +} +function violationOrder(a, b) { + return a.ruleId.localeCompare(b.ruleId) || edgeOrder(a, b); +} +function cycleOrder(a, b) { + return a.join("\0").localeCompare(b.join("\0")); +} function severityOrder(value) { return value === "error" ? 0 : value === "warning" ? 1 : 2; } @@ -5188,6 +5310,21 @@ function array(value) { function isRecord4(value) { return typeof value === "object" && value !== null && !Array.isArray(value); } +function canonicalize2(value) { + if (Array.isArray(value)) + return `[${value.map(canonicalize2).join(",")}]`; + if (value && typeof value === "object") + return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, entry2]) => `${JSON.stringify(key)}:${canonicalize2(entry2)}`).join(",")}}`; + return JSON.stringify(value); +} +function stableHash3(value) { + let hash = 0xcbf29ce484222325n; + for (const byte of new TextEncoder().encode(value)) { + hash ^= BigInt(byte); + hash = BigInt.asUintN(64, hash * 0x100000001b3n); + } + return hash.toString(16).padStart(16, "0"); +} // packages/core/dist/report.js var MAX_REPORTED_TERMS = 8; @@ -6436,15 +6573,15 @@ function reportUnreadContent(diagnostics, files) { paths: affected.slice(0, 8).map((file) => file.path) }); } - const unread = files.filter((file) => file.isSource && file.textSampleComplete === false && file.textSampleSkipReason === "too-large"); - if (unread.length === 0) + const unread2 = files.filter((file) => file.isSource && file.textSampleComplete === false && file.textSampleSkipReason === "too-large"); + if (unread2.length === 0) return; - const sample = unread.slice().sort((a, b) => b.sizeBytes - a.sizeBytes).slice(0, 3).map((file) => `${file.path} (${Math.ceil(file.sizeBytes / 1e3).toLocaleString()} kB)`).join(", "); + const sample = unread2.slice().sort((a, b) => b.sizeBytes - a.sizeBytes).slice(0, 3).map((file) => `${file.path} (${Math.ceil(file.sizeBytes / 1e3).toLocaleString()} kB)`).join(", "); diagnostics.push({ code: "content-too-large", severity: "warning", - message: `${unread.length.toLocaleString()} source file${unread.length === 1 ? "" : "s"} exceeded the complete text window \u2014 largest: ${sample}${unread.length > 3 ? ", \u2026" : ""}. Files over ${(MAX_TEXT_SAMPLE_BYTES / 1e3).toLocaleString()} kB use bounded head and distributed retrieval samples; context and grounding remain incomplete.`, - paths: unread.slice(0, 8).map((file) => file.path) + message: `${unread2.length.toLocaleString()} source file${unread2.length === 1 ? "" : "s"} exceeded the complete text window \u2014 largest: ${sample}${unread2.length > 3 ? ", \u2026" : ""}. Files over ${(MAX_TEXT_SAMPLE_BYTES / 1e3).toLocaleString()} kB use bounded head and distributed retrieval samples; context and grounding remain incomplete.`, + paths: unread2.slice(0, 8).map((file) => file.path) }); } function reportSkippedSubmodules(diagnostics, gitLinks) { @@ -7016,6 +7153,9 @@ function normalizePath3(path) { // packages/core/dist/architecture-history.js import { execFile as execFile2, spawn } from "node:child_process"; +import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto"; +import { mkdir as mkdir2, readdir as readdir2, readFile as readFile2, rename as rename2, stat as stat2, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises"; +import { homedir as homedir2 } from "node:os"; import { dirname as dirname2, extname as extname2, isAbsolute as isAbsolute2, join as join2, relative as relative2, resolve as resolve2, sep as sep2 } from "node:path"; import { promisify as promisify2 } from "node:util"; var exec2 = promisify2(execFile2); @@ -7025,7 +7165,10 @@ var MAX_FILES = 25e3; var MAX_TEXT_SAMPLE_BYTES2 = 64e3; var MAX_BATCH_BYTES = 64 * 1024 * 1024; var MAX_BATCH_OUTPUT_BYTES = MAX_BATCH_BYTES + 2 * 1024 * 1024; +var ARCHITECTURE_CACHE_VERSION = 1; var ARCHITECTURE_CACHE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3; +var ARCHITECTURE_CACHE_FILE = /^architecture-v\d+-[a-f0-9]{40,64}-(?:policy|no-policy)\.json$/; +var ARCHITECTURE_CACHE_TEMP_FILE = /^architecture-v\d+-[a-f0-9]{40,64}-(?:policy|no-policy)\.json\.\d+-[0-9a-f-]{36}\.tmp$/; async function scanRepoAtRef(input) { const repoRoot = resolve2(input.repoRoot); const requestedRef = validateRef(input.ref); @@ -7076,9 +7219,141 @@ async function scanCommit(repoRoot, requestedRef, commit) { ...ignoreBytes ? { ignoreFile: ignoreBytes.toString("utf8") } : {} }; } +async function buildArchitectureSnapshotAtRef(input) { + const repoRoot = resolve2(input.repoRoot); + const requestedRef = validateRef(input.ref); + const commit = await resolveCommit(repoRoot, requestedRef); + const applyPolicy = input.applyRepositoryPolicy !== false; + const cachePath = input.useCache === false ? void 0 : architectureCachePath(repoRoot, commit, applyPolicy); + const cached = cachePath ? await readArchitectureCache(cachePath, commit, applyPolicy) : void 0; + if (cached) + return { requestedRef, commit, ...cached }; + const historical = await scanCommit(repoRoot, requestedRef, commit); + const policy = applyPolicy ? architecturePolicyFromRepo(historical.repo) : void 0; + const inventory = inventoryDecisionRecords(historical.repo); + const entry2 = { + snapshot: buildArchitectureSnapshot(historical.repo, policy), + // Only accepted records state intent. Proposed, rejected, superseded, and unlabeled + // records are history, and treating them as rules would invent disagreements. + decisionRules: inventory.records.filter((record3) => record3.status === "accepted").flatMap((record3) => (record3.dependencyRules ?? []).map((rule) => ({ + decisionId: record3.id, + decisionPath: record3.path, + decisionTitle: record3.title, + from: rule.from, + deny: rule.deny + }))), + decisionDiagnostics: inventory.diagnostics.filter((diagnostic) => diagnostic.code !== "decision-target-missing") + }; + if (cachePath) + await writeArchitectureCache(cachePath, commit, applyPolicy, entry2); + return { requestedRef, commit, ...entry2 }; +} +async function compareArchitectureRefs(input) { + const options = { + repoRoot: input.repoRoot, + ...input.applyRepositoryPolicy !== void 0 ? { applyRepositoryPolicy: input.applyRepositoryPolicy } : {}, + ...input.useCache !== void 0 ? { useCache: input.useCache } : {} + }; + const [from, to] = await Promise.all([ + buildArchitectureSnapshotAtRef({ ...options, ref: input.fromRef }), + buildArchitectureSnapshotAtRef({ ...options, ref: input.toRef }) + ]); + return { + from, + to, + drift: compareArchitectureSnapshots(from.snapshot, to.snapshot, { + ...input.couplingDelta !== void 0 ? { couplingDelta: input.couplingDelta } : {} + }), + decisionDisagreements: findDecisionDisagreements(from.snapshot, to) + }; +} +function findDecisionDisagreements(previous, current2) { + const earlier = new Set(previous.edges.map((edge) => `${edge.from}\0${edge.to}`)); + return current2.decisionRules.flatMap((rule) => { + const from = buildPathExcluder([rule.from]); + const deny = buildPathExcluder([rule.deny]); + return current2.snapshot.edges.filter((edge) => from.excludes(edge.from) && deny.excludes(edge.to)).map((edge) => ({ + decisionId: rule.decisionId, + decisionPath: rule.decisionPath, + decisionTitle: rule.decisionTitle, + rule: { from: rule.from, deny: rule.deny }, + edge: { from: edge.from, to: edge.to }, + introduced: !earlier.has(`${edge.from}\0${edge.to}`) + })); + }).sort((a, b) => a.decisionPath.localeCompare(b.decisionPath) || a.rule.from.localeCompare(b.rule.from) || a.rule.deny.localeCompare(b.rule.deny) || a.edge.from.localeCompare(b.edge.from) || a.edge.to.localeCompare(b.edge.to)); +} +function architectureCacheRoot() { + return resolve2(process.env.FIXMAP_CACHE_DIR ?? join2(process.env.LOCALAPPDATA ?? process.env.XDG_CACHE_HOME ?? join2(homedir2(), ".cache"), "fixmap", "scans")); +} +function architectureCachePath(repoRoot, commit, applyPolicy) { + const cacheRoot = architectureCacheRoot(); + const fold = (value) => process.platform === "win32" ? value.toLowerCase() : value; + const distance = relative2(fold(repoRoot), fold(cacheRoot)); + if (distance === "" || distance !== ".." && !distance.startsWith(`..${sep2}`) && !isAbsolute2(distance)) + return void 0; + return join2(cacheRoot, `architecture-v${ARCHITECTURE_CACHE_VERSION}-${commit}-${applyPolicy ? "policy" : "no-policy"}.json`); +} +async function readArchitectureCache(path, commit, applyPolicy) { + try { + const parsed2 = JSON.parse(await readFile2(path, "utf8")); + if (parsed2.architectureHistoryCacheVersion !== ARCHITECTURE_CACHE_VERSION || parsed2.commit !== commit || parsed2.applyPolicy !== applyPolicy || typeof parsed2.checksum !== "string") + return void 0; + if (parsed2.checksum !== checksum(JSON.stringify(parsed2.entry))) + return void 0; + return isArchitectureEntry(parsed2.entry) ? parsed2.entry : void 0; + } catch { + return void 0; + } +} +async function writeArchitectureCache(path, commit, applyPolicy, entry2) { + const temporaryPath = `${path}.${process.pid}-${randomUUID2()}.tmp`; + try { + await mkdir2(dirname2(path), { recursive: true }); + await pruneArchitectureCache(dirname2(path)); + const record3 = { + architectureHistoryCacheVersion: ARCHITECTURE_CACHE_VERSION, + commit, + applyPolicy, + checksum: checksum(JSON.stringify(entry2)), + entry: entry2 + }; + await writeFile2(temporaryPath, `${JSON.stringify(record3)} +`, { encoding: "utf8", flag: "wx" }); + await rename2(temporaryPath, path); + } catch { + try { + await unlink2(temporaryPath); + } catch { + } + } +} +async function pruneArchitectureCache(directory) { + try { + const now = Date.now(); + await Promise.all((await readdir2(directory, { withFileTypes: true })).filter((entry2) => entry2.isFile() && (ARCHITECTURE_CACHE_FILE.test(entry2.name) || ARCHITECTURE_CACHE_TEMP_FILE.test(entry2.name))).map(async (entry2) => { + const path = join2(directory, entry2.name); + try { + if (now - (await stat2(path)).mtimeMs > ARCHITECTURE_CACHE_MAX_AGE_MS) + await unlink2(path); + } catch { + } + })); + } catch { + } +} +function isArchitectureEntry(value) { + if (!isRecord6(value) || !isRecord6(value.snapshot) || !Array.isArray(value.decisionRules) || !Array.isArray(value.decisionDiagnostics)) + return false; + const snapshot = value.snapshot; + const edge = (entry2) => isRecord6(entry2) && typeof entry2.from === "string" && typeof entry2.to === "string"; + return snapshot.architectureSnapshotVersion === 1 && typeof snapshot.fingerprint === "string" && typeof snapshot.sourceFingerprint === "string" && Array.isArray(snapshot.edges) && snapshot.edges.every(edge) && Array.isArray(snapshot.cycles) && snapshot.cycles.every((cycle) => Array.isArray(cycle) && cycle.every((path) => typeof path === "string")) && Array.isArray(snapshot.coupling) && Array.isArray(snapshot.boundaryViolations) && isRecord6(snapshot.truncated) && value.decisionRules.every((rule) => isRecord6(rule) && ["decisionId", "decisionPath", "decisionTitle", "from", "deny"].every((key) => typeof rule[key] === "string")); +} function isRecord6(value) { return typeof value === "object" && value !== null && !Array.isArray(value); } +function checksum(value) { + return createHash2("sha256").update(value).digest("hex"); +} function historicalPackageScripts(files, diagnostics) { return files.filter((file) => file.path === "package.json" || file.path.endsWith("/package.json")).flatMap((manifest) => { if (manifest.textSampleComplete !== true) @@ -7558,14 +7833,14 @@ function positiveInteger2(value, fallback) { return value !== void 0 && Number.isSafeInteger(value) && value > 0 ? value : fallback; } function withTimeout(promise, timeoutMs, controller) { - return new Promise((resolve7, reject) => { + return new Promise((resolve8, reject) => { const timer = setTimeout(() => { controller.abort(); reject(new Error(`timed out after ${timeoutMs.toLocaleString()} ms`)); }, timeoutMs); promise.then((value) => { clearTimeout(timer); - resolve7(value); + resolve8(value); }, (error) => { clearTimeout(timer); reject(error); @@ -7726,7 +8001,7 @@ function normalizeAbsolutePattern(repoRoot, pattern) { } async function readIgnoreFile(repoRoot) { try { - return parseIgnoreFile(await readFile2(join3(repoRoot, ".fixmapignore"), "utf8")); + return parseIgnoreFile(await readFile3(join3(repoRoot, ".fixmapignore"), "utf8")); } catch { return []; } @@ -8044,9 +8319,9 @@ function renderVerifyMarkdown(result) { } // packages/core/dist/annotation-store.js -import { mkdir as mkdir2, open as open2, readFile as readFile3, realpath as realpath2, rename as rename2, rm, stat as stat2, lstat } from "node:fs/promises"; +import { mkdir as mkdir3, open as open2, readFile as readFile4, realpath as realpath2, rename as rename3, rm, stat as stat3, lstat } from "node:fs/promises"; import { resolve as resolve4 } from "node:path"; -import { randomUUID as randomUUID2 } from "node:crypto"; +import { randomUUID as randomUUID3 } from "node:crypto"; async function readAnnotationStore(repoRoot) { return readStore(await annotationRoot(repoRoot)); } @@ -8060,7 +8335,7 @@ async function updateAnnotationStore(repoRoot, update) { } async function annotationRoot(path) { const root = await realpath2(path); - if (!(await stat2(root)).isDirectory()) + if (!(await stat3(root)).isDirectory()) throw new Error("Annotation repository must be a directory."); return root; } @@ -8068,7 +8343,7 @@ async function readStore(repoRoot) { await assertStoreBoundary(repoRoot); const path = resolve4(repoRoot, ".fixmap", "annotations.json"); try { - return validateAnnotationStore(JSON.parse(await readFile3(path, "utf8"))); + return validateAnnotationStore(JSON.parse(await readFile4(path, "utf8"))); } catch (error) { if (isNodeError(error, "ENOENT")) return emptyAnnotationStore(); @@ -8079,10 +8354,10 @@ async function readStore(repoRoot) { } async function writeStore(repoRoot, store) { const directory = resolve4(repoRoot, ".fixmap"); - await mkdir2(directory, { recursive: true }); + await mkdir3(directory, { recursive: true }); await assertStoreBoundary(repoRoot); const target = resolve4(directory, "annotations.json"); - const temporary = resolve4(directory, `.annotations.${process.pid}.${randomUUID2()}.tmp`); + const temporary = resolve4(directory, `.annotations.${process.pid}.${randomUUID3()}.tmp`); const handle = await open2(temporary, "wx", 384); try { await handle.writeFile(`${JSON.stringify(validateAnnotationStore(store), null, 2)} @@ -8092,7 +8367,7 @@ async function writeStore(repoRoot, store) { await handle.close(); } try { - await rename2(temporary, target); + await rename3(temporary, target); } catch (error) { await rm(temporary, { force: true }); throw error; @@ -8101,7 +8376,7 @@ async function writeStore(repoRoot, store) { async function withStoreLock(repoRoot, operation) { await assertStoreBoundary(repoRoot); const directory = resolve4(repoRoot, ".fixmap"); - await mkdir2(directory, { recursive: true }); + await mkdir3(directory, { recursive: true }); await assertStoreBoundary(repoRoot); const lockPath = resolve4(directory, "annotations.lock"); let handle; @@ -8347,6 +8622,20 @@ function evidenceOrder(a, b) { function confidenceOrder(value) { return value === "high" ? 0 : value === "medium" ? 1 : 2; } +function withoutMentions(value) { + return value.replace(/(^|[^A-Za-z0-9_.+-])@+(?=[A-Za-z0-9])/g, "$1"); +} +function reviewRoutingWithoutMentions(result) { + return { + ...result, + suggestions: result.suggestions.map((suggestion) => ({ + ...suggestion, + reviewer: withoutMentions(suggestion.reviewer), + evidence: suggestion.evidence.map((entry2) => ({ ...entry2, detail: withoutMentions(entry2.detail) })) + })).sort((a, b) => confidenceOrder(a.confidence) - confidenceOrder(b.confidence) || a.reviewer.localeCompare(b.reviewer)), + diagnostics: result.diagnostics.map((entry2) => ({ ...entry2, message: withoutMentions(entry2.message) })) + }; +} // packages/core/dist/sandbox.js import { execFile as execFile3, spawn as spawn2 } from "node:child_process"; @@ -8877,6 +9166,112 @@ function inventoryContracts(sources, inheritedDiagnostics = []) { diagnostics: diagnostics.sort((a, b) => a.path.localeCompare(b.path) || a.code.localeCompare(b.code)) }; } +function compareContractInventories(previous, current2) { + if (previous.inventoryVersion !== 1 || current2.inventoryVersion !== 1) { + throw new Error("Unsupported contract inventory version."); + } + const changes = []; + const beforeById = uniqueSurfaceIndex(previous.surfaces, "previous"); + const afterById = uniqueSurfaceIndex(current2.surfaces, "current"); + const unavailableBefore = unavailableContractPaths(previous.diagnostics); + const unavailableAfter = unavailableContractPaths(current2.diagnostics); + for (const [id, before] of beforeById) { + const after = afterById.get(id); + if (!after) { + if (unavailableAfter.has(before.path)) { + changes.push(contractChange(before, void 0, "contract-unavailable", "unknown", `${before.kind} contract ${before.name} could not be read on the later side, so its compatibility is unknown.`)); + continue; + } + changes.push(contractChange(before, void 0, "contract-removed", "breaking", `Removed ${before.kind} contract ${before.name}.`)); + continue; + } + compareSurface(before, after, changes); + } + for (const [id, after] of afterById) { + if (!beforeById.has(id)) { + if (unavailableBefore.has(after.path)) { + changes.push(contractChange(void 0, after, "contract-unavailable", "unknown", `${after.kind} contract ${after.name} could not be read on the earlier side, so its compatibility is unknown.`)); + continue; + } + changes.push(contractChange(void 0, after, "contract-added", "compatible", `Added ${after.kind} contract ${after.name}.`)); + } + } + changes.sort((a, b) => severityOrder2(a.compatibility) - severityOrder2(b.compatibility) || a.path.localeCompare(b.path) || (a.entry ?? "").localeCompare(b.entry ?? "") || a.change.localeCompare(b.change)); + const breaking = changes.filter((change) => change.compatibility === "breaking").length; + const unknown = changes.filter((change) => change.compatibility === "unknown").length; + const compatible = changes.length - breaking - unknown; + return { + comparisonVersion: 1, + summary: changes.length === 0 ? "No supported contract surface changed." : `${changes.length} contract change${changes.length === 1 ? "" : "s"}: ${breaking} breaking, ${unknown} unknown, ${compatible} compatible.`, + changes, + diagnostics: deduplicateDiagnostics([...previous.diagnostics, ...current2.diagnostics]) + }; +} +function compareSurface(before, after, changes) { + const beforeEntries = new Map(before.entries.map((entry2) => [entry2.key, entry2])); + const afterEntries = new Map(after.entries.map((entry2) => [entry2.key, entry2])); + for (const [key, entry2] of beforeEntries) { + const current2 = afterEntries.get(key); + if (!current2) { + changes.push(contractChange(before, after, "entry-removed", removalCompatibility(entry2), `Removed ${describeEntry(entry2)}.`, entry2)); + } else if (entry2.signature !== current2.signature || entry2.required !== current2.required) { + const compatibility = changedCompatibility(entry2, current2); + const detail = entry2.signature === current2.signature ? `requiredness from ${entry2.required} to ${current2.required}` : `signature from ${entry2.signature} to ${current2.signature}`; + changes.push(contractChange(before, after, "entry-changed", compatibility, `${describeEntry(entry2)} changed ${detail}.`, current2, entry2.signature, current2.signature)); + } + } + for (const [key, entry2] of afterEntries) { + if (beforeEntries.has(key)) + continue; + const compatibility = additionCompatibility(entry2); + changes.push(contractChange(before, after, "entry-added", compatibility, additionReason(entry2), entry2)); + } +} +function contractChange(before, after, change, compatibility, reason2, entry2, beforeSignature, afterSignature) { + const surface = after ?? before; + const key = `${surface.id}\0${change}\0${entry2?.key ?? ""}\0${beforeSignature ?? ""}\0${afterSignature ?? ""}`; + return { + id: `contract-change:${stableHash4(key)}`, + contractId: surface.id, + contractKind: surface.kind, + path: surface.path, + change, + compatibility, + reason: reason2, + ...entry2 ? { entry: entry2.key } : {}, + ...beforeSignature !== void 0 ? { before: beforeSignature } : {}, + ...afterSignature !== void 0 ? { after: afterSignature } : {}, + evidence: { + ...before ? { beforeFingerprint: before.sourceFingerprint } : {}, + ...after ? { afterFingerprint: after.sourceFingerprint } : {} + } + }; +} +function removalCompatibility(entry2) { + return entry2.role === "migration" ? "unknown" : "breaking"; +} +function additionCompatibility(entry2) { + if (entry2.role === "migration") + return /^destructive:/.test(entry2.signature) ? "breaking" : "compatible"; + return entry2.required && (entry2.role === "argument" || entry2.role === "required-field") ? "breaking" : "compatible"; +} +function changedCompatibility(before, after) { + if (!before.required && after.required) + return "breaking"; + if (before.role === "migration") + return /^destructive:/.test(after.signature) ? "breaking" : "unknown"; + return "breaking"; +} +function describeEntry(entry2) { + return `${entry2.role.replace("-", " ")} ${entry2.key}`; +} +function additionReason(entry2) { + if (entry2.role === "migration") { + const [classification, ...statement] = entry2.signature.split(":"); + return `Added ${classification} migration statement: ${statement.join(":")}.`; + } + return `Added ${describeEntry(entry2)}${entry2.required ? " as required" : ""}.`; +} function parseContract(source) { const lower = source.path.toLowerCase(); if (lower.endsWith(".graphql") || lower.endsWith(".gql")) { @@ -9104,7 +9499,7 @@ function parseMigration(content) { const statements = content.split(";").map((statement) => statement.replace(/--[^\r\n]*/g, " ").replace(/\s+/g, " ").trim()).filter(Boolean); for (const statement of statements) { const destructive = /\bDROP\s+(?:TABLE|COLUMN|TYPE|INDEX|CONSTRAINT)\b|\bALTER\s+(?:TABLE\s+)?[^;]+\b(?:SET\s+NOT\s+NULL|TYPE\s+)\b|\bTRUNCATE\b/i.test(statement); - entries.push(entry(`migration:${stableHash3(statement.toLowerCase())}`, "migration", `${destructive ? "destructive" : "additive"}:${statement}`, false)); + entries.push(entry(`migration:${stableHash4(statement.toLowerCase())}`, "migration", `${destructive ? "destructive" : "additive"}:${statement}`, false)); } return { entries }; } @@ -9122,6 +9517,25 @@ function normalizeEntries(entries) { } return [...byKey.values()].sort((a, b) => a.key.localeCompare(b.key)); } +function uniqueSurfaceIndex(surfaces, label) { + const index = /* @__PURE__ */ new Map(); + for (const surface of surfaces) { + if (index.has(surface.id)) + throw new Error(`Duplicate ${label} contract surface: ${surface.id}`); + index.set(surface.id, surface); + } + return index; +} +function unavailableContractPaths(diagnostics) { + return new Set(diagnostics.filter((diagnostic) => diagnostic.code === "contract-parse-failed" || diagnostic.code === "contract-source-incomplete").map((diagnostic) => diagnostic.path)); +} +function deduplicateDiagnostics(diagnostics) { + const byKey = /* @__PURE__ */ new Map(); + for (const diagnostic of diagnostics) { + byKey.set(`${diagnostic.code}\0${diagnostic.path}\0${diagnostic.message}`, { ...diagnostic }); + } + return [...byKey.values()].sort((a, b) => a.path.localeCompare(b.path) || a.code.localeCompare(b.code)); +} function validateContractSource(source) { if (!source.path.trim() || source.path.includes("\0") || /^(?:[\\/]|[A-Za-z]:)/.test(source.path) || source.path.replace(/\\/g, "/").split("/").some((part) => !part || part === "." || part === "..")) { throw new Error(`Invalid contract source path: ${source.path}`); @@ -9159,7 +9573,10 @@ function parseJson(content) { function isRecord8(value) { return typeof value === "object" && value !== null && !Array.isArray(value); } -function stableHash3(value) { +function severityOrder2(value) { + return value === "breaking" ? 0 : value === "unknown" ? 1 : 2; +} +function stableHash4(value) { let hash = 0xcbf29ce484222325n; for (const byte of new TextEncoder().encode(value)) { hash ^= BigInt(byte); @@ -9878,12 +10295,12 @@ async function compareCapabilityRefs(input) { const to = capabilitySnapshot(historicalTo, id, input.asOf); const selected = comparePaths(from.map?.scope.selected ?? [], to.map?.scope.selected ?? []); const affected = comparePaths(from.map?.scope.affected ?? [], to.map?.scope.affected ?? []); - const contracts = compareEntities(from.map?.scope.contracts.map((entry2) => ({ id: entry2.id, fingerprint: `${entry2.sourceFingerprint}\0${canonicalize2(entry2.entries)}` })) ?? [], to.map?.scope.contracts.map((entry2) => ({ id: entry2.id, fingerprint: `${entry2.sourceFingerprint}\0${canonicalize2(entry2.entries)}` })) ?? []); + const contracts = compareEntities(from.map?.scope.contracts.map((entry2) => ({ id: entry2.id, fingerprint: `${entry2.sourceFingerprint}\0${canonicalize3(entry2.entries)}` })) ?? [], to.map?.scope.contracts.map((entry2) => ({ id: entry2.id, fingerprint: `${entry2.sourceFingerprint}\0${canonicalize3(entry2.entries)}` })) ?? []); const decisions = compareEntities(from.map?.scope.decisions.map((entry2) => ({ id: entry2.id, fingerprint: entry2.sourceFingerprint })) ?? [], to.map?.scope.decisions.map((entry2) => ({ id: entry2.id, fingerprint: entry2.sourceFingerprint })) ?? []); const testAssociations = compareEntities(from.testAssociations.map((entry2) => ({ id: entry2.path, fingerprint: entry2.sourceFingerprint })), to.testAssociations.map((entry2) => ({ id: entry2.path, fingerprint: entry2.sourceFingerprint }))); const reviewers = compareEntities(reviewerEntities(from.map), reviewerEntities(to.map)); const architectureFindings = compareEntities(findingEntities(from.map), findingEntities(to.map)); - const definitionChanged = canonicalize2(from.capability ?? null) !== canonicalize2(to.capability ?? null); + const definitionChanged = canonicalize3(from.capability ?? null) !== canonicalize3(to.capability ?? null); const totalChanges = [selected, affected, contracts, decisions, testAssociations, reviewers, architectureFindings].reduce((total, diff) => total + diff.added.length + diff.removed.length + diff.modified.length, definitionChanged ? 1 : 0); return { capabilityHistoryVersion: 1, @@ -9958,31 +10375,99 @@ function compareMaps(previous, current2) { function reviewerEntities(map) { return (map?.scope.reviewers ?? []).map((reviewer) => ({ id: reviewer.reviewer, - fingerprint: canonicalize2({ paths: reviewer.paths, evidence: reviewer.evidence }) + fingerprint: canonicalize3({ paths: reviewer.paths, evidence: reviewer.evidence }) })); } function findingEntities(map) { return (map?.scope.architectureFindings ?? []).map((finding) => ({ id: `${finding.ruleId}:${finding.code}:${finding.paths.join("|")}`, - fingerprint: canonicalize2(finding) + fingerprint: canonicalize3(finding) })); } -function canonicalize2(value) { +function canonicalize3(value) { if (Array.isArray(value)) - return `[${value.map(canonicalize2).join(",")}]`; + return `[${value.map(canonicalize3).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(([key, entry2]) => `${JSON.stringify(key)}:${canonicalize3(entry2)}`).join(",")}}`; } return JSON.stringify(value); } // packages/core/dist/contracts-repository.js import { execFile as execFile4 } from "node:child_process"; +import { relative as relative3, resolve as resolve5, sep as sep3 } from "node:path"; import { promisify as promisify4 } from "node:util"; var exec4 = promisify4(execFile4); var MAX_CONTRACT_BYTES = 2 * 1024 * 1024; var MAX_TREE_BYTES2 = 32 * 1024 * 1024; var MAX_TOTAL_BYTES = 64 * 1024 * 1024; +var STRUCTURED_EXTENSION = /\.(?:json|ya?ml)$/i; +async function inventoryContractsAtRef(input) { + const repoRoot = resolve5(input.repoRoot); + const requestedRef = validateRef(input.ref); + const commit = await resolveCommit(repoRoot, requestedRef); + const { stdout } = await exec4("git", ["ls-tree", "-r", "-z", "-l", "--full-tree", commit, "--"], { + cwd: repoRoot, + encoding: "utf8", + maxBuffer: MAX_TREE_BYTES2 + }); + const candidates = parseTree(stdout).filter((entry2) => entry2.mode !== "120000" && entry2.mode !== "160000").filter((entry2) => CONTRACT_PATH.test(entry2.path) || STRUCTURED_EXTENSION.test(entry2.path)); + const diagnostics = []; + const readable = []; + let totalBytes = 0; + for (const entry2 of candidates) { + if (entry2.size <= MAX_CONTRACT_BYTES && totalBytes + entry2.size <= MAX_TOTAL_BYTES) { + readable.push(entry2); + totalBytes += entry2.size; + } else if (CONTRACT_PATH.test(entry2.path)) { + diagnostics.push(unread(entry2.path)); + } + } + const blobs = await readBlobs(repoRoot, readable); + const sources = []; + for (const entry2 of readable) { + const byPath = CONTRACT_PATH.test(entry2.path); + const content = decodeUtf8(blobs.get(entry2.oid)); + if (content === void 0) { + if (byPath) + diagnostics.push(unread(entry2.path)); + continue; + } + if (!byPath && !isContractCandidate(entry2.path, content)) + continue; + sources.push({ path: entry2.path, content, fingerprint: `git:${entry2.oid}` }); + } + return { requestedRef, commit, inventory: inventoryContracts(sources, diagnostics) }; +} +async function compareContractRefs(input) { + const [from, to] = await Promise.all([ + inventoryContractsAtRef({ repoRoot: input.repoRoot, ref: input.fromRef }), + inventoryContractsAtRef({ repoRoot: input.repoRoot, ref: input.toRef }) + ]); + return { + contractDiffVersion: 1, + from: { requestedRef: from.requestedRef, commit: from.commit }, + to: { requestedRef: to.requestedRef, commit: to.commit }, + comparison: compareContractInventories(from.inventory, to.inventory) + }; +} +function decodeUtf8(bytes) { + if (!bytes) + return void 0; + try { + return new TextDecoder("utf-8", { fatal: true }).decode(bytes); + } catch { + return void 0; + } +} +function unread(path) { + return { + code: "contract-source-incomplete", + severity: "warning", + path, + message: `${path} looks like a contract, but it is larger than ${MAX_CONTRACT_BYTES / 1024 / 1024} MB, not UTF-8 text, or unreadable, so FixMap did not parse it.` + }; +} // packages/action/src/annotations.ts async function runAnnotationAction(input, repoRoot, allowWrite) { @@ -10026,9 +10511,9 @@ async function runAnnotationAction(input, repoRoot, allowWrite) { }); if ("path" in annotation.scope && annotation.scope.path) { const root = await realpath3(repoRoot); - const target = await realpath3(resolve5(root, annotation.scope.path)); - const inside = relative3(root, target); - if (!inside || isAbsolute3(inside) || inside === ".." || inside.startsWith("../") || inside.startsWith("..\\") || !(await stat3(target)).isFile()) { + const target = await realpath3(resolve6(root, annotation.scope.path)); + const inside = relative4(root, target); + if (!inside || isAbsolute3(inside) || inside === ".." || inside.startsWith("../") || inside.startsWith("..\\") || !(await stat4(target)).isFile()) { throw new Error("Annotation target must be an existing file inside the checkout."); } } @@ -10042,7 +10527,7 @@ function record2(value) { // packages/action/src/runner.ts import { appendFileSync, readFileSync, statSync } from "node:fs"; -import { resolve as resolve6 } from "node:path"; +import { resolve as resolve7 } from "node:path"; // packages/action/src/github.ts var FIXMAP_REPORT_MARKER = ""; @@ -10362,6 +10847,190 @@ function message(error) { return /[.…]$/.test(bounded) ? bounded : `${bounded}.`; } +// packages/action/src/review-sections.ts +function hasReviewSections(request) { + return request.contracts || request.reviewers || request.architectureDrift; +} +var REFS_NEEDED = "needs a pull request with both base and head refs. Fetch the base ref (for example `actions/checkout` with `fetch-depth: 0`) to compare."; +async function buildReviewSections(request, context) { + const sections = []; + const warnings = []; + let breakingContractCount; + if (request.contracts) { + const heading = "## Contract changes (preview)"; + if (!context.diffRefs) { + sections.push([heading, "", `Contract comparison ${REFS_NEEDED}`, ""].join("\n")); + warnings.push(`FixMap contract comparison ${REFS_NEEDED}`); + } else { + try { + const result = await (context.compareContractRefs ?? compareContractRefs)({ + repoRoot: context.repoRoot, + fromRef: context.diffRefs.baseRef, + toRef: context.diffRefs.headRef + }); + breakingContractCount = result.comparison.changes.filter((change) => change.compatibility === "breaking").length; + sections.push(renderContractSection(result)); + } catch (error) { + sections.push([heading, "", `Contract comparison unavailable: ${message(error)} ${REFS_NEEDED}`, ""].join("\n")); + warnings.push(`FixMap contract comparison unavailable: ${message(error)}`); + } + } + } + if (request.reviewers) { + const heading = "## Suggested reviewers (preview)"; + try { + const repo = await (context.scanRepo ?? scanRepo)({ + repoRoot: context.repoRoot, + useCache: context.useCache, + includeHistory: request.reviewersHistoryAuthors + }); + const scanError = repo.diagnostics.find((diagnostic) => diagnostic.severity === "error"); + if (scanError) throw new Error(scanError.message); + const result = routeReviewers(repo, { + changedPaths: context.changedPaths, + now: context.now, + includeHistoryAuthors: request.reviewersHistoryAuthors + }); + sections.push(renderReviewerSection(result)); + } catch (error) { + const detail = withoutMentions(message(error)); + sections.push([heading, "", `Reviewer suggestions unavailable: ${detail}`, ""].join("\n")); + warnings.push(`FixMap reviewer suggestions unavailable: ${detail}`); + } + } + if (request.architectureDrift) { + const heading = "## Architecture drift (preview)"; + if (!context.diffRefs) { + sections.push([heading, "", `Architecture drift ${REFS_NEEDED}`, ""].join("\n")); + warnings.push(`FixMap architecture drift ${REFS_NEEDED}`); + } else { + try { + const result = await (context.compareArchitectureRefs ?? compareArchitectureRefs)({ + repoRoot: context.repoRoot, + fromRef: context.diffRefs.baseRef, + toRef: context.diffRefs.headRef, + useCache: context.useCache + }); + sections.push(renderArchitectureDriftSection(result)); + } catch (error) { + sections.push([heading, "", `Architecture drift unavailable: ${message(error)} ${REFS_NEEDED}`, ""].join("\n")); + warnings.push(`FixMap architecture drift unavailable: ${message(error)}`); + } + } + } + return { + markdown: sections.join("\n"), + warnings, + ...breakingContractCount !== void 0 ? { breakingContractCount } : {} + }; +} +var COMPATIBILITY_ORDER = { breaking: 0, unknown: 1, compatible: 2 }; +function renderContractSection(result) { + const { changes } = result.comparison; + const count = (compatibility) => changes.filter((change) => change.compatibility === compatibility).length; + const lines = [ + "## Contract changes (preview)", + "", + // Reasons quote contract text, where a GraphQL directive such as `@deprecated` would mention someone. + withoutMentions(result.comparison.summary), + "", + `- Breaking: ${count("breaking").toLocaleString()}`, + `- Unknown: ${count("unknown").toLocaleString()}`, + `- Compatible: ${count("compatible").toLocaleString()}`, + "" + ]; + if (changes.length > 0) { + const ordered = [...changes].sort((a, b) => COMPATIBILITY_ORDER[a.compatibility] - COMPATIBILITY_ORDER[b.compatibility] || a.path.localeCompare(b.path)); + lines.push("Top changes:", ""); + lines.push(...ordered.slice(0, SECTION_PATH_LIMIT).map((change) => `- ${change.compatibility} ${markdownCode2(change.path)} (${change.contractKind}): ${withoutMentions(change.reason)}`)); + if (changes.length > SECTION_PATH_LIMIT) lines.push(`- \u2026and ${(changes.length - SECTION_PATH_LIMIT).toLocaleString()} more`); + lines.push(""); + } + if (result.comparison.diagnostics.length > 0) { + lines.push(`Contracts not compared: ${result.comparison.diagnostics.length.toLocaleString()}; run the CLI for details.`, ""); + } + lines.push( + `Base ${markdownCode2(result.from.requestedRef)} at ${markdownCode2(result.from.commit)}; head ${markdownCode2(result.to.requestedRef)} at ${markdownCode2(result.to.commit)}. Both sides were read from Git objects without a checkout. Breaking changes are advisory and never fail this step. Run \`fixmap contracts diff\` for the complete comparison.`, + "" + ); + return lines.join("\n"); +} +var EVIDENCE_LABEL = { + codeowners: "CODEOWNERS", + annotation: "annotation", + "architecture-policy": "architecture policy", + "git-history": "commit history" +}; +function renderReviewerSection(input) { + const result = reviewRoutingWithoutMentions(input); + const lines = [ + "## Suggested reviewers (preview)", + "", + "Suggestions only. FixMap does not request reviews or notify anyone, and a name is not evidence of identity, employment, or current availability.", + "" + ]; + if (result.changedPaths.length === 0) { + lines.push("No changed paths, so there is nothing to route.", ""); + } else { + const covered = new Set(result.suggestions.flatMap((suggestion) => suggestion.paths)); + const uncovered = result.changedPaths.filter((path) => !covered.has(path)); + lines.push( + `- Changed paths routed: ${result.changedPaths.length.toLocaleString()}`, + `- Suggested reviewers: ${result.suggestions.length.toLocaleString()}`, + `- Paths without reviewer evidence: ${uncovered.length.toLocaleString()}`, + "" + ); + if (result.suggestions.length > 0) { + for (const suggestion of result.suggestions.slice(0, SECTION_PATH_LIMIT)) { + const sources = [...new Set(suggestion.evidence.map((entry2) => EVIDENCE_LABEL[entry2.kind]))].join(", "); + const paths = suggestion.paths.slice(0, 3).map(markdownCode2).join(", "); + const more = suggestion.paths.length > 3 ? ` and ${(suggestion.paths.length - 3).toLocaleString()} more` : ""; + lines.push(`- ${markdownCode2(suggestion.reviewer)} (${suggestion.confidence}; ${sources}): ${paths}${more}`); + } + if (result.suggestions.length > SECTION_PATH_LIMIT) { + lines.push(`- \u2026and ${(result.suggestions.length - SECTION_PATH_LIMIT).toLocaleString()} more`); + } + lines.push(""); + } + } + const warnings = result.diagnostics.filter((entry2) => entry2.severity === "warning"); + if (warnings.length > 0) { + lines.push(...warnings.slice(0, SECTION_PATH_LIMIT).map((entry2) => `- warning (${markdownCode2(entry2.source)}): ${entry2.message}`), ""); + } + lines.push("Run `fixmap reviewers` for the per-path evidence.", ""); + return lines.join("\n"); +} +function renderArchitectureDriftSection(result) { + const { drift } = result; + const edge = (entry2) => `${markdownCode2(entry2.from)} -> ${markdownCode2(entry2.to)}`; + const lines = [ + "## Architecture drift (preview)", + "", + `- Added edges: ${drift.addedEdges.length.toLocaleString()}`, + `- Removed edges: ${drift.removedEdges.length.toLocaleString()}`, + `- New cycles: ${drift.newCycles.length.toLocaleString()} (resolved: ${drift.resolvedCycles.length.toLocaleString()})`, + `- New policy violations: ${drift.newBoundaryViolations.length.toLocaleString()} (resolved: ${drift.resolvedBoundaryViolations.length.toLocaleString()})`, + `- Decision disagreements: ${result.decisionDisagreements.length.toLocaleString()} (introduced here: ${result.decisionDisagreements.filter((entry2) => entry2.introduced).length.toLocaleString()})`, + "" + ]; + const list = (title, values, render) => { + if (values.length === 0) return; + lines.push(`${title}:`, "", ...values.slice(0, SECTION_PATH_LIMIT).map((value) => `- ${render(value)}`)); + if (values.length > SECTION_PATH_LIMIT) lines.push(`- \u2026and ${(values.length - SECTION_PATH_LIMIT).toLocaleString()} more`); + lines.push(""); + }; + list("New cycles", drift.newCycles, (cycle) => cycle.map(markdownCode2).join(" -> ")); + list("New policy violations", drift.newBoundaryViolations, (entry2) => `${markdownCode2(entry2.ruleId)}: ${edge(entry2)}`); + list("Decision disagreements", result.decisionDisagreements, (entry2) => `${markdownCode2(entry2.decisionPath)} denies ${markdownCode2(entry2.rule.from)} -> ${markdownCode2(entry2.rule.deny)}; ${edge(entry2.edge)} ${entry2.introduced ? "was introduced in this range" : "already existed at the base"}`); + list("Added edges", drift.addedEdges, edge); + list("Removed edges", drift.removedEdges, edge); + lines.push( + `Base ${markdownCode2(result.from.requestedRef)} at ${markdownCode2(result.from.commit)}; head ${markdownCode2(result.to.requestedRef)} at ${markdownCode2(result.to.commit)}. Both sides were read from Git objects without a checkout. Run \`fixmap history\` for the complete comparison.`, + "" + ); + return lines.join("\n"); +} + // packages/action/src/issue-source.ts var MAX_API_RESPONSE_CHARS = 1e6; var MAX_ISSUE_BODY_CHARS = 2e4; @@ -10485,12 +11154,29 @@ var TRUNCATION_FOOTER = "\n\n> FixMap report truncated to fit GitHub's 1 MiB ste var ACTION_OUTPUT_REPORT_LIMIT_BYTES = 900 * 1024; var OUTPUT_TRUNCATION_FOOTER = "\n\n[FixMap report truncated to fit the GitHub Actions output limit. Run FixMap locally with --output for a complete report.]\n"; var SCOPE_INPUTS = ["change-scope-touch", "change-scope-add", "capability"]; +function readReviewSectionRequest(env) { + const historyAuthors = readInput("reviewers-history-authors", env); + const request = { + contracts: parseBooleanInput("contracts", readInput("contracts", env)), + reviewers: parseBooleanInput("reviewers", readInput("reviewers", env)), + reviewersHistoryAuthors: historyAuthors === void 0 || parseBooleanInput("reviewers-history-authors", historyAuthors), + architectureDrift: parseBooleanInput("architecture-drift", readInput("architecture-drift", env)) + }; + const used = [ + request.contracts ? "contracts" : "", + request.reviewers ? "reviewers" : "", + request.reviewersHistoryAuthors ? "" : "reviewers-history-authors", + request.architectureDrift ? "architecture-drift" : "" + ].filter(Boolean); + return { ...request, used }; +} 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 readFile5 = dependencies.readFile ?? ((path) => readFileSync(path, "utf8")); const stdout = dependencies.stdout ?? ((text) => process.stdout.write(text)); 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)); + incompatible.push(...readReviewSectionRequest(env).used); for (const name of ["working-tree", "include-untracked", "no-cache"]) { if (parseBooleanInput(name, readInput(name, env))) incompatible.push(name); } @@ -10504,7 +11190,7 @@ async function runAction(env = process.env, dependencies = {}) { stdout(output2); if (env.GITHUB_STEP_SUMMARY) appendBoundedStepSummary(env.GITHUB_STEP_SUMMARY, withJsonDetails("# FixMap annotations\n\nLocal checkout operation only; no commit, push, or GitHub comment was made.", output2), dependencies, appendFile, stdout); if (env.GITHUB_OUTPUT) { - const delimiter = `fixmap_${(dependencies.uuid ?? randomUUID3)().replace(/-/g, "")}`; + const delimiter = `fixmap_${(dependencies.uuid ?? randomUUID4)().replace(/-/g, "")}`; appendFile(env.GITHUB_OUTPUT, `report<<${delimiter} ${output2} ${delimiter} @@ -10513,7 +11199,7 @@ ${delimiter} return; } if (readInput("annotation-request", env) || readInput("allow-annotation-write", env) === "true") throw new Error("Annotation inputs require mode: annotate."); - const event = readEvent(env.GITHUB_EVENT_PATH, readFile4); + const event = readEvent(env.GITHUB_EVENT_PATH, readFile5); const rawIssue = readInput("issue", env) || buildPullRequestIssueText(event); const diffSpec = readInput("diff", env); const workingTree = parseBooleanInput("working-tree", readInput("working-tree", env)); @@ -10529,19 +11215,25 @@ ${delimiter} if (includeUntracked && !workingTree) throw new Error("include-untracked requires working-tree."); if (workingTree && (diffSpec || baseRef || headRef)) throw new Error("Use either working-tree or diff/base/head, not both."); if (diffSpec && (baseRef || headRef)) throw new Error("Use either diff or base/head, not both."); + const reviewRequest = readReviewSectionRequest(env); + if (!reviewRequest.reviewersHistoryAuthors && !reviewRequest.reviewers) { + throw new Error("reviewers-history-authors: false requires reviewers: true."); + } + const diffRefs = event?.pull_request?.number && baseRef && headRef ? { baseRef, headRef } : void 0; if (mode === "verify") { const planOnly = [ readInput("limit", env) ? "limit" : "", readInput("exclude", env) ? "exclude" : "", readInput("issue", env) ? "issue" : "", - ...SCOPE_INPUTS.filter((name) => readInput(name, env)) + ...SCOPE_INPUTS.filter((name) => readInput(name, env)), + ...reviewRequest.used.filter((name) => name !== "contracts") ].filter(Boolean); if (planOnly.length > 0) { throw new Error( `FixMap verify mode does not use plan-only input${planOnly.length === 1 ? "" : "s"}: ${planOnly.join(", ")}. Remove them, or set mode: plan.` ); } - return runVerifyMode({ env, dependencies, readFile: readFile4, appendFile, stdout, format, failOn, diffSpec, baseRef, headRef, workingTree, includeUntracked, noCache }); + return runVerifyMode({ env, dependencies, readFile: readFile5, appendFile, stdout, format, failOn, diffSpec, baseRef, headRef, workingTree, includeUntracked, noCache, contracts: reviewRequest.contracts, diffRefs }); } if (failOn === "warning") throw new Error("fail-on: warning is a verify-mode input; remove it or set mode: verify."); const issueSource = rawIssue ? parseActionIssueSource(rawIssue) : void 0; @@ -10580,28 +11272,38 @@ ${delimiter} message: `Fetched ${issueSource.displayUrl} anonymously and used its title${fetchedIssue?.body ? " and body" : ""} as task context` + (fetchedIssue?.truncated ? "; the body was truncated to 20,000 characters, so later text did not inform the ranking." : ".") }); } + const now = (dependencies.now ?? (() => (/* @__PURE__ */ new Date()).toISOString()))(); const scopeSections = hasScopeSections(scopeRequest) ? await buildScopeSections(scopeRequest, { repoRoot, useCache: !noCache, - asOf: (dependencies.now ?? (() => (/* @__PURE__ */ new Date()).toISOString()))(), - ...event?.pull_request?.number && baseRef && headRef ? { diffRefs: { baseRef, headRef } } : {}, + asOf: now, + ...diffRefs ? { diffRefs } : {}, ...dependencies.scanRepo ? { scanRepo: dependencies.scanRepo } : {}, ...dependencies.compareCapabilityRefs ? { compareCapabilityRefs: dependencies.compareCapabilityRefs } : {} }) : void 0; - for (const warning of scopeSections?.warnings ?? []) stdout(`::warning::${warning} + const reviewSections = hasReviewSections(reviewRequest) ? await buildReviewSections(reviewRequest, { + repoRoot, + useCache: !noCache, + now, + changedPaths: report.changedFiles.length > 0 ? report.changedFiles : report.contextFiles.map((file) => file.path), + ...diffRefs ? { diffRefs } : {}, + ...reviewSectionDependencies(dependencies) + }) : void 0; + for (const warning of [...scopeSections?.warnings ?? [], ...reviewSections?.warnings ?? []]) stdout(`::warning::${warning} `); const planMarkdown = renderMarkdownReport(report); - const markdown = scopeSections ? `${planMarkdown.trimEnd()} + const extraMarkdown = [scopeSections?.markdown, reviewSections?.markdown].filter(Boolean).join("\n"); + const markdown = extraMarkdown ? `${planMarkdown.trimEnd()} -${scopeSections.markdown}` : planMarkdown; +${extraMarkdown}` : planMarkdown; const output = format === "json" ? renderJsonReport(report) : markdown; stdout(output); if (env.GITHUB_STEP_SUMMARY) { appendBoundedStepSummary(env.GITHUB_STEP_SUMMARY, format === "json" ? withJsonDetails(markdown, output) : markdown, dependencies, appendFile, stdout); } if (env.GITHUB_OUTPUT) { - appendFile(env.GITHUB_OUTPUT, renderActionOutputs(output, report, dependencies.uuid ?? randomUUID3) + (scopeSections?.changeScopeAffectedCount !== void 0 ? `change-scope-affected-count=${scopeSections.changeScopeAffectedCount} -` : "")); + appendFile(env.GITHUB_OUTPUT, renderActionOutputs(output, report, dependencies.uuid ?? randomUUID4) + (scopeSections?.changeScopeAffectedCount !== void 0 ? `change-scope-affected-count=${scopeSections.changeScopeAffectedCount} +` : "") + breakingContractOutput(reviewSections)); } const token = readInput("github-token", env) || env.GITHUB_TOKEN; const commentAuthor = readInput("comment-author", env); @@ -10610,8 +11312,8 @@ ${scopeSections.markdown}` : planMarkdown; const comment = format === "json" ? `\`\`\`json ${output.trimEnd()} \`\`\` -${scopeSections ? ` -${scopeSections.markdown}` : ""}` : markdown; +${extraMarkdown ? ` +${extraMarkdown}` : ""}` : markdown; await upsertPullRequestComment(token, event, comment, commentAuthor, env, dependencies.createClient); } catch (error) { if (!isPermissionDeniedError(error)) { @@ -10635,6 +11337,17 @@ function parseMode(value) { } throw new Error(`Invalid mode input ${JSON.stringify(value)}; expected plan or verify.`); } +function reviewSectionDependencies(dependencies) { + return { + ...dependencies.scanRepo ? { scanRepo: dependencies.scanRepo } : {}, + ...dependencies.compareContractRefs ? { compareContractRefs: dependencies.compareContractRefs } : {}, + ...dependencies.compareArchitectureRefs ? { compareArchitectureRefs: dependencies.compareArchitectureRefs } : {} + }; +} +function breakingContractOutput(sections) { + return sections?.breakingContractCount !== void 0 ? `breaking-contract-count=${sections.breakingContractCount} +` : ""; +} async function runVerifyMode(context) { const reportPath = readInput("report-path", context.env); if (!reportPath) { @@ -10666,14 +11379,30 @@ async function runVerifyMode(context) { includeUntracked: context.includeUntracked, useCache: !context.noCache, includeHistory: true, - internalExclude: [resolve6(repoRoot, reportPath)] + internalExclude: [resolve7(repoRoot, reportPath)] }); const diffFailure = repo.diagnostics.find((diagnostic) => diagnostic.code === "diff-unavailable"); if (diffFailure) { throw new Error(`${diffFailure.message} Verification needs a resolvable diff.`); } const result = verifyPlan(report, repo); - const markdown = renderVerifyMarkdown(result); + const contractSections = context.contracts ? await buildReviewSections( + { contracts: true, reviewers: false, reviewersHistoryAuthors: true, architectureDrift: false }, + { + repoRoot, + useCache: !context.noCache, + now: (context.dependencies.now ?? (() => (/* @__PURE__ */ new Date()).toISOString()))(), + changedPaths: [], + ...context.diffRefs ? { diffRefs: context.diffRefs } : {}, + ...reviewSectionDependencies(context.dependencies) + } + ) : void 0; + for (const warning of contractSections?.warnings ?? []) context.stdout(`::warning::${warning} +`); + const verifyMarkdown = renderVerifyMarkdown(result); + const markdown = contractSections ? `${verifyMarkdown.trimEnd()} + +${contractSections.markdown}` : verifyMarkdown; const output = context.format === "json" ? `${JSON.stringify(result, null, 2)} ` : markdown; context.stdout(output); @@ -10683,7 +11412,7 @@ async function runVerifyMode(context) { if (context.env.GITHUB_OUTPUT) { context.appendFile( context.env.GITHUB_OUTPUT, - renderVerifyOutputs(output, result, context.dependencies.uuid ?? randomUUID3) + renderVerifyOutputs(output, result, context.dependencies.uuid ?? randomUUID4) + breakingContractOutput(contractSections) ); } if (result.findings.some( @@ -10694,7 +11423,7 @@ async function runVerifyMode(context) { ); } } -function renderVerifyOutputs(reportText, result, uuid = randomUUID3) { +function renderVerifyOutputs(reportText, result, uuid = randomUUID4) { const delimiter = `fixmap_${uuid().replaceAll("-", "")}`; const fittedReport = fitOutputReport(reportText); const terminated = fittedReport.endsWith("\n") ? fittedReport : `${fittedReport} @@ -10739,7 +11468,7 @@ function parseBooleanInput(name, value) { if (/^(?:false|0|no)$/i.test(value)) return false; throw new Error(`${name} must be true or false.`); } -function renderActionOutputs(reportText, report, uuid = randomUUID3) { +function renderActionOutputs(reportText, report, uuid = randomUUID4) { const delimiter = `fixmap_${uuid().replaceAll("-", "")}`; const fittedReport = fitOutputReport(reportText); const terminatedReport = fittedReport.endsWith("\n") ? fittedReport : `${fittedReport} @@ -10837,12 +11566,12 @@ function readInput(name, env) { const value = env[githubName] || env[shellSafeName]; return value?.trim() || void 0; } -function readEvent(eventPath, readFile4) { +function readEvent(eventPath, readFile5) { if (!eventPath) { return void 0; } try { - return JSON.parse(readFile4(eventPath)); + return JSON.parse(readFile5(eventPath)); } catch (error) { const detail = error instanceof Error ? error.message : String(error); throw new Error(`FixMap could not read the GitHub event payload: ${detail}`); diff --git a/packages/action/src/review-sections.ts b/packages/action/src/review-sections.ts new file mode 100644 index 0000000..f6fe7e8 --- /dev/null +++ b/packages/action/src/review-sections.ts @@ -0,0 +1,249 @@ +import { + compareArchitectureRefs, + compareContractRefs, + reviewRoutingWithoutMentions, + routeReviewers, + scanRepo, + withoutMentions, + type ArchitectureRefComparison, + type ContractChange, + type ContractRefComparison, + type ReviewRoutingResult +} from "@aryam/fixmap-core"; +import { SECTION_PATH_LIMIT, markdownCode, message } from "./scope-sections.js"; + +export type ReviewSectionRequest = { + contracts: boolean; + reviewers: boolean; + /** Mirrors `fixmap reviewers --no-history-authors` when false. */ + reviewersHistoryAuthors: boolean; + architectureDrift: boolean; +}; + +export type ReviewSectionContext = { + repoRoot: string; + useCache: boolean; + now: string; + /** Paths reviewers are routed for: the report's changed files, else its context files. */ + changedPaths: readonly string[]; + /** Present only on pull requests whose base and head refs are both known. */ + diffRefs?: { baseRef: string; headRef: string }; + scanRepo?: typeof scanRepo; + compareContractRefs?: typeof compareContractRefs; + compareArchitectureRefs?: typeof compareArchitectureRefs; +}; + +export type ReviewSections = { + markdown: string; + warnings: string[]; + breakingContractCount?: number; +}; + +export function hasReviewSections(request: ReviewSectionRequest): boolean { + return request.contracts || request.reviewers || request.architectureDrift; +} + +const REFS_NEEDED = + "needs a pull request with both base and head refs. Fetch the base ref (for example `actions/checkout` with `fetch-depth: 0`) to compare."; + +/** + * Runs the same Core engines as `fixmap contracts diff`, `fixmap reviewers`, and + * `fixmap history`. Everything is read-only: both refs are read from Git objects without a + * checkout, nobody is asked to review, and no failure here fails the job. + */ +export async function buildReviewSections(request: ReviewSectionRequest, context: ReviewSectionContext): Promise { + const sections: string[] = []; + const warnings: string[] = []; + let breakingContractCount: number | undefined; + + if (request.contracts) { + const heading = "## Contract changes (preview)"; + if (!context.diffRefs) { + sections.push([heading, "", `Contract comparison ${REFS_NEEDED}`, ""].join("\n")); + warnings.push(`FixMap contract comparison ${REFS_NEEDED}`); + } else { + try { + const result = await (context.compareContractRefs ?? compareContractRefs)({ + repoRoot: context.repoRoot, + fromRef: context.diffRefs.baseRef, + toRef: context.diffRefs.headRef + }); + breakingContractCount = result.comparison.changes.filter((change) => change.compatibility === "breaking").length; + sections.push(renderContractSection(result)); + } catch (error) { + sections.push([heading, "", `Contract comparison unavailable: ${message(error)} ${REFS_NEEDED}`, ""].join("\n")); + warnings.push(`FixMap contract comparison unavailable: ${message(error)}`); + } + } + } + + if (request.reviewers) { + const heading = "## Suggested reviewers (preview)"; + try { + const repo = await (context.scanRepo ?? scanRepo)({ + repoRoot: context.repoRoot, + useCache: context.useCache, + includeHistory: request.reviewersHistoryAuthors + }); + const scanError = repo.diagnostics.find((diagnostic) => diagnostic.severity === "error"); + if (scanError) throw new Error(scanError.message); + const result = routeReviewers(repo, { + changedPaths: context.changedPaths, + now: context.now, + includeHistoryAuthors: request.reviewersHistoryAuthors + }); + sections.push(renderReviewerSection(result)); + } catch (error) { + const detail = withoutMentions(message(error)); + sections.push([heading, "", `Reviewer suggestions unavailable: ${detail}`, ""].join("\n")); + warnings.push(`FixMap reviewer suggestions unavailable: ${detail}`); + } + } + + if (request.architectureDrift) { + const heading = "## Architecture drift (preview)"; + if (!context.diffRefs) { + sections.push([heading, "", `Architecture drift ${REFS_NEEDED}`, ""].join("\n")); + warnings.push(`FixMap architecture drift ${REFS_NEEDED}`); + } else { + try { + const result = await (context.compareArchitectureRefs ?? compareArchitectureRefs)({ + repoRoot: context.repoRoot, + fromRef: context.diffRefs.baseRef, + toRef: context.diffRefs.headRef, + useCache: context.useCache + }); + sections.push(renderArchitectureDriftSection(result)); + } catch (error) { + sections.push([heading, "", `Architecture drift unavailable: ${message(error)} ${REFS_NEEDED}`, ""].join("\n")); + warnings.push(`FixMap architecture drift unavailable: ${message(error)}`); + } + } + } + + return { + markdown: sections.join("\n"), + warnings, + ...(breakingContractCount !== undefined ? { breakingContractCount } : {}) + }; +} + +const COMPATIBILITY_ORDER = { breaking: 0, unknown: 1, compatible: 2 } as const; + +export function renderContractSection(result: ContractRefComparison): string { + const { changes } = result.comparison; + const count = (compatibility: ContractChange["compatibility"]) => + changes.filter((change) => change.compatibility === compatibility).length; + const lines = [ + "## Contract changes (preview)", + "", + // Reasons quote contract text, where a GraphQL directive such as `@deprecated` would mention someone. + withoutMentions(result.comparison.summary), + "", + `- Breaking: ${count("breaking").toLocaleString()}`, + `- Unknown: ${count("unknown").toLocaleString()}`, + `- Compatible: ${count("compatible").toLocaleString()}`, + "" + ]; + if (changes.length > 0) { + const ordered = [...changes].sort((a, b) => + COMPATIBILITY_ORDER[a.compatibility] - COMPATIBILITY_ORDER[b.compatibility] || a.path.localeCompare(b.path)); + lines.push("Top changes:", ""); + lines.push(...ordered.slice(0, SECTION_PATH_LIMIT).map((change) => + `- ${change.compatibility} ${markdownCode(change.path)} (${change.contractKind}): ${withoutMentions(change.reason)}`)); + if (changes.length > SECTION_PATH_LIMIT) lines.push(`- …and ${(changes.length - SECTION_PATH_LIMIT).toLocaleString()} more`); + lines.push(""); + } + if (result.comparison.diagnostics.length > 0) { + lines.push(`Contracts not compared: ${result.comparison.diagnostics.length.toLocaleString()}; run the CLI for details.`, ""); + } + lines.push( + `Base ${markdownCode(result.from.requestedRef)} at ${markdownCode(result.from.commit)}; head ${markdownCode(result.to.requestedRef)} at ${markdownCode(result.to.commit)}. ` + + "Both sides were read from Git objects without a checkout. Breaking changes are advisory and never fail this step. " + + "Run `fixmap contracts diff` for the complete comparison.", + "" + ); + return lines.join("\n"); +} + +const EVIDENCE_LABEL = { + codeowners: "CODEOWNERS", + annotation: "annotation", + "architecture-policy": "architecture policy", + "git-history": "commit history" +} as const; + +/** Names print without `@` and nothing here requests a review, so nobody is notified. */ +export function renderReviewerSection(input: ReviewRoutingResult): string { + const result = reviewRoutingWithoutMentions(input); + const lines = [ + "## Suggested reviewers (preview)", + "", + "Suggestions only. FixMap does not request reviews or notify anyone, and a name is not evidence of identity, employment, or current availability.", + "" + ]; + if (result.changedPaths.length === 0) { + lines.push("No changed paths, so there is nothing to route.", ""); + } else { + const covered = new Set(result.suggestions.flatMap((suggestion) => suggestion.paths)); + const uncovered = result.changedPaths.filter((path) => !covered.has(path)); + lines.push( + `- Changed paths routed: ${result.changedPaths.length.toLocaleString()}`, + `- Suggested reviewers: ${result.suggestions.length.toLocaleString()}`, + `- Paths without reviewer evidence: ${uncovered.length.toLocaleString()}`, + "" + ); + if (result.suggestions.length > 0) { + for (const suggestion of result.suggestions.slice(0, SECTION_PATH_LIMIT)) { + const sources = [...new Set(suggestion.evidence.map((entry) => EVIDENCE_LABEL[entry.kind]))].join(", "); + const paths = suggestion.paths.slice(0, 3).map(markdownCode).join(", "); + const more = suggestion.paths.length > 3 ? ` and ${(suggestion.paths.length - 3).toLocaleString()} more` : ""; + lines.push(`- ${markdownCode(suggestion.reviewer)} (${suggestion.confidence}; ${sources}): ${paths}${more}`); + } + if (result.suggestions.length > SECTION_PATH_LIMIT) { + lines.push(`- …and ${(result.suggestions.length - SECTION_PATH_LIMIT).toLocaleString()} more`); + } + lines.push(""); + } + } + const warnings = result.diagnostics.filter((entry) => entry.severity === "warning"); + if (warnings.length > 0) { + lines.push(...warnings.slice(0, SECTION_PATH_LIMIT).map((entry) => `- warning (${markdownCode(entry.source)}): ${entry.message}`), ""); + } + lines.push("Run `fixmap reviewers` for the per-path evidence.", ""); + return lines.join("\n"); +} + +export function renderArchitectureDriftSection(result: ArchitectureRefComparison): string { + const { drift } = result; + const edge = (entry: { from: string; to: string }) => `${markdownCode(entry.from)} -> ${markdownCode(entry.to)}`; + const lines = [ + "## Architecture drift (preview)", + "", + `- Added edges: ${drift.addedEdges.length.toLocaleString()}`, + `- Removed edges: ${drift.removedEdges.length.toLocaleString()}`, + `- New cycles: ${drift.newCycles.length.toLocaleString()} (resolved: ${drift.resolvedCycles.length.toLocaleString()})`, + `- New policy violations: ${drift.newBoundaryViolations.length.toLocaleString()} (resolved: ${drift.resolvedBoundaryViolations.length.toLocaleString()})`, + `- Decision disagreements: ${result.decisionDisagreements.length.toLocaleString()} (introduced here: ${result.decisionDisagreements.filter((entry) => entry.introduced).length.toLocaleString()})`, + "" + ]; + const list = (title: string, values: readonly T[], render: (value: T) => string) => { + if (values.length === 0) return; + lines.push(`${title}:`, "", ...values.slice(0, SECTION_PATH_LIMIT).map((value) => `- ${render(value)}`)); + if (values.length > SECTION_PATH_LIMIT) lines.push(`- …and ${(values.length - SECTION_PATH_LIMIT).toLocaleString()} more`); + lines.push(""); + }; + list("New cycles", drift.newCycles, (cycle) => cycle.map(markdownCode).join(" -> ")); + list("New policy violations", drift.newBoundaryViolations, (entry) => `${markdownCode(entry.ruleId)}: ${edge(entry)}`); + list("Decision disagreements", result.decisionDisagreements, (entry) => + `${markdownCode(entry.decisionPath)} denies ${markdownCode(entry.rule.from)} -> ${markdownCode(entry.rule.deny)}; ` + + `${edge(entry.edge)} ${entry.introduced ? "was introduced in this range" : "already existed at the base"}`); + list("Added edges", drift.addedEdges, edge); + list("Removed edges", drift.removedEdges, edge); + lines.push( + `Base ${markdownCode(result.from.requestedRef)} at ${markdownCode(result.from.commit)}; head ${markdownCode(result.to.requestedRef)} at ${markdownCode(result.to.commit)}. ` + + "Both sides were read from Git objects without a checkout. Run `fixmap history` for the complete comparison.", + "" + ); + return lines.join("\n"); +} diff --git a/packages/action/src/runner.ts b/packages/action/src/runner.ts index eb1f671..993d405 100644 --- a/packages/action/src/runner.ts +++ b/packages/action/src/runner.ts @@ -7,7 +7,9 @@ import { renderJsonReport, renderMarkdownReport, renderVerifyMarkdown, + compareArchitectureRefs, compareCapabilityRefs, + compareContractRefs, scanRepo, stripByteOrderMark, validateFixMapReport, @@ -28,6 +30,12 @@ import { splitPathListInput, type ScopeSectionRequest } from "./scope-sections.js"; +import { + buildReviewSections, + hasReviewSections, + type ReviewSectionRequest, + type ReviewSections +} from "./review-sections.js"; import { fetchActionIssue, parseActionIssueSource, @@ -54,11 +62,34 @@ export type ActionDependencies = { fetchIssue?: (source: ActionIssueSource) => Promise; scanRepo?: typeof scanRepo; compareCapabilityRefs?: typeof compareCapabilityRefs; + compareContractRefs?: typeof compareContractRefs; + compareArchitectureRefs?: typeof compareArchitectureRefs; now?: () => string; }; const SCOPE_INPUTS = ["change-scope-touch", "change-scope-add", "capability"] as const; +/** + * Boolean preview inputs default to "false" (and reviewers-history-authors to "true") in + * action.yml, so GitHub always sets them; only values that change behavior count as "used". + */ +function readReviewSectionRequest(env: NodeJS.ProcessEnv): ReviewSectionRequest & { used: string[] } { + const historyAuthors = readInput("reviewers-history-authors", env); + const request: ReviewSectionRequest = { + contracts: parseBooleanInput("contracts", readInput("contracts", env)), + reviewers: parseBooleanInput("reviewers", readInput("reviewers", env)), + reviewersHistoryAuthors: historyAuthors === undefined || parseBooleanInput("reviewers-history-authors", historyAuthors), + architectureDrift: parseBooleanInput("architecture-drift", readInput("architecture-drift", env)) + }; + const used = [ + request.contracts ? "contracts" : "", + request.reviewers ? "reviewers" : "", + request.reviewersHistoryAuthors ? "" : "reviewers-history-authors", + request.architectureDrift ? "architecture-drift" : "" + ].filter(Boolean); + return { ...request, used }; +} + export async function runAction( env: NodeJS.ProcessEnv = process.env, dependencies: ActionDependencies = {} @@ -68,6 +99,7 @@ export async function runAction( const stdout = dependencies.stdout ?? ((text) => process.stdout.write(text)); 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)); + incompatible.push(...readReviewSectionRequest(env).used); for (const name of ["working-tree", "include-untracked", "no-cache"]) { if (parseBooleanInput(name, readInput(name, env))) incompatible.push(name); } @@ -103,6 +135,12 @@ export async function runAction( if (includeUntracked && !workingTree) throw new Error("include-untracked requires working-tree."); if (workingTree && (diffSpec || baseRef || headRef)) throw new Error("Use either working-tree or diff/base/head, not both."); if (diffSpec && (baseRef || headRef)) throw new Error("Use either diff or base/head, not both."); + const reviewRequest = readReviewSectionRequest(env); + if (!reviewRequest.reviewersHistoryAuthors && !reviewRequest.reviewers) { + throw new Error("reviewers-history-authors: false requires reviewers: true."); + } + // Base-vs-head sections compare exact commits, so they run only on pull requests with both refs. + const diffRefs = event?.pull_request?.number && baseRef && headRef ? { baseRef, headRef } : undefined; // Verify closes the plan-edit-verify loop for workflows that never touch the CLI or MCP: // a first job saves the plan as an artifact, a later run on `synchronize` checks the @@ -114,7 +152,8 @@ export async function runAction( readInput("limit", env) ? "limit" : "", readInput("exclude", env) ? "exclude" : "", readInput("issue", env) ? "issue" : "", - ...SCOPE_INPUTS.filter((name) => readInput(name, env)) + ...SCOPE_INPUTS.filter((name) => readInput(name, env)), + ...reviewRequest.used.filter((name) => name !== "contracts") ].filter(Boolean); if (planOnly.length > 0) { throw new Error( @@ -122,7 +161,7 @@ export async function runAction( "Remove them, or set mode: plan." ); } - return runVerifyMode({ env, dependencies, readFile, appendFile, stdout, format, failOn, diffSpec, baseRef, headRef, workingTree, includeUntracked, noCache }); + return runVerifyMode({ env, dependencies, readFile, appendFile, stdout, format, failOn, diffSpec, baseRef, headRef, workingTree, includeUntracked, noCache, contracts: reviewRequest.contracts, diffRefs }); } if (failOn === "warning") throw new Error("fail-on: warning is a verify-mode input; remove it or set mode: verify."); @@ -174,21 +213,33 @@ export async function runAction( (fetchedIssue?.truncated ? "; the body was truncated to 20,000 characters, so later text did not inform the ranking." : ".") }); } + const now = (dependencies.now ?? (() => new Date().toISOString()))(); const scopeSections = hasScopeSections(scopeRequest) ? await buildScopeSections(scopeRequest, { repoRoot, useCache: !noCache, - asOf: (dependencies.now ?? (() => new Date().toISOString()))(), - ...(event?.pull_request?.number && baseRef && headRef ? { diffRefs: { baseRef, headRef } } : {}), + asOf: now, + ...(diffRefs ? { diffRefs } : {}), ...(dependencies.scanRepo ? { scanRepo: dependencies.scanRepo } : {}), ...(dependencies.compareCapabilityRefs ? { compareCapabilityRefs: dependencies.compareCapabilityRefs } : {}) }) : undefined; - for (const warning of scopeSections?.warnings ?? []) stdout(`::warning::${warning}\n`); + const reviewSections = hasReviewSections(reviewRequest) + ? await buildReviewSections(reviewRequest, { + repoRoot, + useCache: !noCache, + now, + changedPaths: report.changedFiles.length > 0 ? report.changedFiles : report.contextFiles.map((file) => file.path), + ...(diffRefs ? { diffRefs } : {}), + ...reviewSectionDependencies(dependencies) + }) + : undefined; + for (const warning of [...scopeSections?.warnings ?? [], ...reviewSections?.warnings ?? []]) stdout(`::warning::${warning}\n`); const planMarkdown = renderMarkdownReport(report); // The preview sections join the readable report only; the JSON report keeps the FixMapReport // contract that verify mode and downstream tools validate. - const markdown = scopeSections ? `${planMarkdown.trimEnd()}\n\n${scopeSections.markdown}` : planMarkdown; + const extraMarkdown = [scopeSections?.markdown, reviewSections?.markdown].filter(Boolean).join("\n"); + const markdown = extraMarkdown ? `${planMarkdown.trimEnd()}\n\n${extraMarkdown}` : planMarkdown; const output = format === "json" ? renderJsonReport(report) : markdown; stdout(output); @@ -202,7 +253,8 @@ export async function runAction( if (env.GITHUB_OUTPUT) { appendFile(env.GITHUB_OUTPUT, renderActionOutputs(output, report, dependencies.uuid ?? randomUUID) + - (scopeSections?.changeScopeAffectedCount !== undefined ? `change-scope-affected-count=${scopeSections.changeScopeAffectedCount}\n` : "")); + (scopeSections?.changeScopeAffectedCount !== undefined ? `change-scope-affected-count=${scopeSections.changeScopeAffectedCount}\n` : "") + + breakingContractOutput(reviewSections)); } const token = readInput("github-token", env) || env.GITHUB_TOKEN; @@ -210,7 +262,7 @@ export async function runAction( if (token) { try { const comment = format === "json" - ? `\`\`\`json\n${output.trimEnd()}\n\`\`\`\n${scopeSections ? `\n${scopeSections.markdown}` : ""}` + ? `\`\`\`json\n${output.trimEnd()}\n\`\`\`\n${extraMarkdown ? `\n${extraMarkdown}` : ""}` : markdown; await upsertPullRequestComment(token, event, comment, commentAuthor, env, dependencies.createClient); } catch (error) { @@ -250,8 +302,22 @@ type VerifyModeContext = { workingTree: boolean; includeUntracked: boolean; noCache: boolean; + contracts: boolean; + diffRefs: { baseRef: string; headRef: string } | undefined; }; +function reviewSectionDependencies(dependencies: ActionDependencies) { + return { + ...(dependencies.scanRepo ? { scanRepo: dependencies.scanRepo } : {}), + ...(dependencies.compareContractRefs ? { compareContractRefs: dependencies.compareContractRefs } : {}), + ...(dependencies.compareArchitectureRefs ? { compareArchitectureRefs: dependencies.compareArchitectureRefs } : {}) + }; +} + +function breakingContractOutput(sections: ReviewSections | undefined): string { + return sections?.breakingContractCount !== undefined ? `breaking-contract-count=${sections.breakingContractCount}\n` : ""; +} + async function runVerifyMode(context: VerifyModeContext): Promise { const reportPath = readInput("report-path", context.env); if (!reportPath) { @@ -294,7 +360,23 @@ async function runVerifyMode(context: VerifyModeContext): Promise { } const result = verifyPlan(report, repo); - const markdown = renderVerifyMarkdown(result); + // Contract changes are advisory here too: only verify findings decide whether the step fails. + const contractSections = context.contracts + ? await buildReviewSections( + { contracts: true, reviewers: false, reviewersHistoryAuthors: true, architectureDrift: false }, + { + repoRoot, + useCache: !context.noCache, + now: (context.dependencies.now ?? (() => new Date().toISOString()))(), + changedPaths: [], + ...(context.diffRefs ? { diffRefs: context.diffRefs } : {}), + ...reviewSectionDependencies(context.dependencies) + } + ) + : undefined; + for (const warning of contractSections?.warnings ?? []) context.stdout(`::warning::${warning}\n`); + const verifyMarkdown = renderVerifyMarkdown(result); + const markdown = contractSections ? `${verifyMarkdown.trimEnd()}\n\n${contractSections.markdown}` : verifyMarkdown; const output = context.format === "json" ? `${JSON.stringify(result, null, 2)}\n` : markdown; context.stdout(output); @@ -305,7 +387,7 @@ async function runVerifyMode(context: VerifyModeContext): Promise { if (context.env.GITHUB_OUTPUT) { context.appendFile( context.env.GITHUB_OUTPUT, - renderVerifyOutputs(output, result, context.dependencies.uuid ?? randomUUID) + renderVerifyOutputs(output, result, context.dependencies.uuid ?? randomUUID) + breakingContractOutput(contractSections) ); } diff --git a/packages/action/src/scope-sections.ts b/packages/action/src/scope-sections.ts index 29f098d..1505669 100644 --- a/packages/action/src/scope-sections.ts +++ b/packages/action/src/scope-sections.ts @@ -255,7 +255,7 @@ function repositoryId(value: string): string { } /** Same code-span rendering as Core's report renderer, so repository paths cannot break out. */ -function markdownCode(value: string): string { +export function markdownCode(value: string): string { const longestRun = Math.max(0, ...[...value.matchAll(/`+/g)].map((match) => match[0].length)); const fence = "`".repeat(longestRun + 1); const pad = /^[` ]|[` ]$/.test(value) ? " " : ""; @@ -267,7 +267,7 @@ function escapeMarkdown(value: string): string { } /** Git failures carry multi-line stderr; one bounded line keeps the comment readable. */ -function message(error: unknown): string { +export function message(error: unknown): string { const text = (error instanceof Error ? error.message : String(error)).replace(/\s+/g, " ").trim(); const bounded = text.length > 300 ? `${text.slice(0, 299)}…` : text; return /[.…]$/.test(bounded) ? bounded : `${bounded}.`; diff --git a/packages/action/test/review-sections.test.ts b/packages/action/test/review-sections.test.ts new file mode 100644 index 0000000..ffd17c1 --- /dev/null +++ b/packages/action/test/review-sections.test.ts @@ -0,0 +1,243 @@ +import { execFileSync } from "node:child_process"; +import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { FixMapReport } from "@aryam/fixmap-core"; +import { GitHubRequestError } from "../src/github.js"; +import { runAction, type ActionDependencies } from "../src/runner.js"; + +const baseReport: FixMapReport = { + summary: "Mapped the change.", + contextFiles: [], + testRoutes: [], + risks: [], + changedFiles: [], + diagnostics: [] +}; + +const roots: string[] = []; +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }))); +}); + +async function repoWith(files: Record): Promise { + const root = await mkdtemp(join(tmpdir(), "fixmap-action-review-")); + roots.push(root); + git(root, "init", "-q", "-b", "main"); + await writeFiles(root, files); + commit(root, "base"); + return root; +} + +async function writeFiles(root: string, files: Record): Promise { + for (const [path, contents] of Object.entries(files)) { + await mkdir(dirname(join(root, path)), { recursive: true }); + await writeFile(join(root, path), contents); + } +} + +function git(root: string, ...args: string[]): string { + return execFileSync("git", ["-c", "user.name=FixMap Test", "-c", "user.email=test@example.invalid", "-c", "commit.gpgsign=false", ...args], { + cwd: root, + encoding: "utf8" + }).trim(); +} + +function commit(root: string, message: string): string { + git(root, "add", "-A"); + git(root, "commit", "-q", "-m", message); + return git(root, "rev-parse", "HEAD"); +} + +/** Commits `head` on a feature branch and returns both commits; HEAD stays on the feature branch. */ +async function pullRequest(base: Record, head: Record, remove: string[] = []) { + const root = await repoWith(base); + const baseCommit = git(root, "rev-parse", "HEAD"); + git(root, "checkout", "-q", "-b", "feature"); + await writeFiles(root, head); + for (const path of remove) git(root, "rm", "-q", path); + const headCommit = commit(root, "feature"); + return { root, baseCommit, headCommit }; +} + +type Run = { stdout: string; summary: string; outputs: string; comment: string | undefined }; + +async function run(root: string, env: NodeJS.ProcessEnv, overrides: ActionDependencies = {}, report: Partial = {}): Promise { + let stdout = ""; + const writes = new Map(); + let comment: string | undefined; + await runAction({ + INPUT_ISSUE: "change the module", + INPUT_NO_CACHE: "true", + GITHUB_STEP_SUMMARY: "summary.md", + GITHUB_OUTPUT: "output.txt", + ...env + }, { + appendFile: (path, contents) => writes.set(path, (writes.get(path) ?? "") + contents), + buildReport: vi.fn(async () => ({ ...structuredClone(baseReport), ...report })), + createClient: () => ({ + upsertPullRequestComment: async (input: { markdown: string }) => { comment = input.markdown; } + }) as never, + cwd: () => root, + fileSize: () => 0, + now: () => "2026-11-22T00:00:00.000Z", + readFile: (path) => { + if (path === "event.json") return JSON.stringify({ pull_request: { number: 9, title: "Change" } }); + if (path === "plan.json") return JSON.stringify(baseReport); + throw new Error(`unexpected read of ${path}`); + }, + stdout: (text) => { stdout += text; }, + uuid: () => "stable", + ...overrides + }); + return { stdout, summary: writes.get("summary.md") ?? "", outputs: writes.get("output.txt") ?? "", comment }; +} + +/** A pull request run against exact base and head commits. */ +function prEnv(baseCommit: string, extra: NodeJS.ProcessEnv): NodeJS.ProcessEnv { + return { + GITHUB_EVENT_PATH: "event.json", + GITHUB_REPOSITORY: "owner/demo", + INPUT_ISSUE: "", + INPUT_BASE: baseCommit, + INPUT_HEAD: "HEAD", + ...extra + }; +} + +const usersApi = (operations: string) => `openapi: 3.0.3\ninfo:\n title: Users\n version: "1"\npaths:\n /users:\n${operations}`; +const getAndPost = " get: {}\n post: {}\n"; + +// Real Git repositories and scans run several times slower on Windows runners than locally. +describe("Action review sections (preview)", { timeout: 30_000 }, () => { + it("leaves the report, outputs, and scans unchanged when no preview input is set", async () => { + const scanRepo = vi.fn(); + const compareContractRefs = vi.fn(); + const compareArchitectureRefs = vi.fn(); + const result = await run("C:/unused", { + // action.yml defaults that GitHub always passes. + INPUT_CONTRACTS: "false", + INPUT_REVIEWERS: "false", + INPUT_REVIEWERS_HISTORY_AUTHORS: "true", + INPUT_ARCHITECTURE_DRIFT: "false" + }, { scanRepo: scanRepo as never, compareContractRefs: compareContractRefs as never, compareArchitectureRefs: compareArchitectureRefs as never }); + expect(scanRepo).not.toHaveBeenCalled(); + expect(compareContractRefs).not.toHaveBeenCalled(); + expect(compareArchitectureRefs).not.toHaveBeenCalled(); + expect(result.summary).not.toMatch(/Contract changes|Suggested reviewers|Architecture drift/); + expect(result.outputs).not.toContain("breaking-contract-count"); + expect(result.outputs).toMatch(/test-route-count=0\n$/); + }); + + it("adds contract changes and the breaking count from an exact-ref diff without checkout", async () => { + const { root, baseCommit, headCommit } = await pullRequest( + { "specs/users-api.yml": usersApi(getAndPost) }, + { "specs/users-api.yml": usersApi(" get: {}\n") } + ); + const result = await run(root, prEnv(baseCommit, { INPUT_CONTRACTS: "true", INPUT_GITHUB_TOKEN: "token" })); + expect(result.summary).toContain("## Contract changes (preview)"); + expect(result.summary).toContain("- Breaking: 1"); + expect(result.summary).toMatch(/- breaking `specs\/users-api\.yml` \(openapi\): /); + expect(result.summary).toContain(`head \`HEAD\` at \`${headCommit}\``); + expect(result.summary).toContain("never fail this step"); + expect(result.outputs).toContain("breaking-contract-count=1\n"); + expect(result.comment).toContain("## Contract changes (preview)"); + expect(git(root, "rev-parse", "--abbrev-ref", "HEAD")).toBe("feature"); + expect(git(root, "status", "--porcelain")).toBe(""); + }); + + it("adds contract changes in verify mode without failing on breaking changes", async () => { + const { root, baseCommit } = await pullRequest( + { "specs/users-api.yml": usersApi(getAndPost) }, + { "specs/users-api.yml": usersApi(" get: {}\n") } + ); + const result = await run(root, prEnv(baseCommit, { INPUT_MODE: "verify", INPUT_REPORT_PATH: "plan.json", INPUT_CONTRACTS: "true" })); + expect(result.summary).toContain("## Contract changes (preview)"); + expect(result.outputs).toContain("breaking-contract-count=1\n"); + expect(result.outputs).toContain("finding-count="); + }); + + it("degrades missing refs to a warning for contracts and architecture drift", async () => { + const root = await repoWith({ "src/a.ts": "export const a = 1;\n" }); + const missing = await run(root, prEnv("origin/missing-base", { INPUT_CONTRACTS: "true", INPUT_ARCHITECTURE_DRIFT: "true" })); + expect(missing.summary).toMatch(/Contract comparison unavailable: .+ Fetch the base ref/); + expect(missing.summary).toMatch(/Architecture drift unavailable: .+ Fetch the base ref/); + expect(missing.stdout).toContain("::warning::FixMap contract comparison unavailable:"); + expect(missing.stdout).toContain("::warning::FixMap architecture drift unavailable:"); + expect(missing.outputs).not.toContain("breaking-contract-count"); + expect(missing.summary).toContain("Mapped the change."); + + // No pull request event: there is no exact base/head pair to compare. + const noPr = await run(root, { INPUT_CONTRACTS: "true", INPUT_ARCHITECTURE_DRIFT: "true" }); + expect(noPr.summary).toContain("Contract comparison needs a pull request with both base and head refs."); + expect(noPr.stdout).toContain("::warning::FixMap architecture drift needs a pull request with both base and head refs."); + }); + + it("suggests reviewers without any @ mention and never requests a review", async () => { + const root = await repoWith({ + ".github/CODEOWNERS": "* @org/everyone\n/src/auth.ts @security-team\n", + "src/auth.ts": "export const auth = 1;\n" + }); + let requested = false; + const result = await run(root, { GITHUB_EVENT_PATH: "event.json", GITHUB_REPOSITORY: "owner/demo", INPUT_GITHUB_TOKEN: "token", INPUT_REVIEWERS: "true" }, { + createClient: () => ({ + upsertPullRequestComment: async () => undefined, + requestReviewers: async () => { requested = true; } + }) as never + }, { changedFiles: ["src/auth.ts"] }); + expect(result.summary).toContain("## Suggested reviewers (preview)"); + expect(result.summary).toContain("- Changed paths routed: 1"); + expect(result.summary).toMatch(/- `security-team` \(high; CODEOWNERS\): `src\/auth\.ts`/); + expect(result.summary).toContain("`FixMap Test`"); + expect(result.summary).not.toMatch(/(^|[^A-Za-z0-9_.+-])@[A-Za-z0-9]/m); + expect(result.stdout).not.toMatch(/(^|[^A-Za-z0-9_.+-])@[A-Za-z0-9]/m); + expect(requested).toBe(false); + }); + + it("leaves out commit authors when reviewers-history-authors is false", async () => { + const root = await repoWith({ ".github/CODEOWNERS": "/src/auth.ts @security-team\n", "src/auth.ts": "export const auth = 1;\n" }); + const result = await run(root, { INPUT_REVIEWERS: "true", INPUT_REVIEWERS_HISTORY_AUTHORS: "false" }, {}, { changedFiles: ["src/auth.ts"] }); + expect(result.summary).toContain("`security-team`"); + expect(result.summary).not.toContain("FixMap Test"); + await expect(run(root, { INPUT_REVIEWERS_HISTORY_AUTHORS: "false" })).rejects.toThrow(/requires reviewers: true/); + }); + + it("adds architecture drift with added edges and new cycles from Git objects", async () => { + const { root, headCommit } = await pullRequest( + { "src/a.ts": "export const a = 1;\n", "src/b.ts": "export const b = 1;\n" }, + { "src/a.ts": 'import { b } from "./b";\nexport const a = b;\n', "src/b.ts": 'import { a } from "./a";\nexport const b = a;\n' } + ); + const result = await run(root, prEnv(git(root, "rev-parse", "main"), { INPUT_ARCHITECTURE_DRIFT: "true" })); + expect(result.summary).toContain("## Architecture drift (preview)"); + expect(result.summary).toContain("- Added edges: 2"); + expect(result.summary).toContain("- New cycles: 1 (resolved: 0)"); + expect(result.summary).toContain("- `src/a.ts` -> `src/b.ts`"); + expect(result.summary).toContain(`at \`${headCommit}\``); + expect(git(root, "status", "--porcelain")).toBe(""); + }); + + it("keeps the sections when a read-only token cannot comment", async () => { + const { root, baseCommit } = await pullRequest( + { "specs/users-api.yml": usersApi(getAndPost) }, + { "specs/users-api.yml": usersApi(" get: {}\n") } + ); + const result = await run(root, prEnv(baseCommit, { INPUT_CONTRACTS: "true", INPUT_GITHUB_TOKEN: "token" }), { + createClient: () => ({ + upsertPullRequestComment: async () => { throw new GitHubRequestError("GitHub API request failed (403).", 403, "Resource not accessible by integration", false); } + }) as never + }); + expect(result.stdout).toContain("::warning::FixMap could not comment on the pull request"); + expect(result.summary).toContain("## Contract changes (preview)"); + expect(result.outputs).toContain("breaking-contract-count=1\n"); + }); + + it("rejects plan-only previews in verify mode and every preview in annotate mode", async () => { + const root = await repoWith({ "src/a.ts": "export const a = 1;\n" }); + await expect(run(root, { INPUT_MODE: "verify", INPUT_ISSUE: "", INPUT_REPORT_PATH: "plan.json", INPUT_BASE: "main", INPUT_REVIEWERS: "true", INPUT_ARCHITECTURE_DRIFT: "true" })) + .rejects.toThrow(/plan-only inputs: reviewers, architecture-drift/); + await expect(run(root, { INPUT_MODE: "annotate", INPUT_ISSUE: "", INPUT_NO_CACHE: "", INPUT_ANNOTATION_REQUEST: "{}", INPUT_CONTRACTS: "true" })) + .rejects.toThrow(/annotate mode does not accept analysis inputs: contracts/); + await expect(run(root, { INPUT_CONTRACTS: "maybe" })).rejects.toThrow(/contracts must be true or false/); + }); +}); From 62175bad6f97aa0c061d88795fd8981d171ca9a5 Mon Sep 17 00:00:00 2001 From: Aryam Goyal Date: Mon, 23 Nov 2026 19:48:46 +0530 Subject: [PATCH 2/5] feat: plan alternatives and MCP capability editing (preview) Add preview fixmap alternatives (--input, or --report with an explicit --graph-fingerprint), a saved-report adapter, side-by-side Markdown trade-offs without a winner, and the read-only fixmap_alternatives MCP tool. fixmap_capability gains action create|update|remove routed through the CLI write path (lock, atomic replace, containment, link refusal). Co-Authored-By: Claude Opus 5.5 --- packages/cli/README.md | 4 +- packages/cli/src/alternatives-command.ts | 305 ++++++++++++++++++ packages/cli/src/cli-runner.ts | 11 + packages/cli/src/mcp.ts | 110 ++++++- .../cli/test/alternatives-command.test.ts | 142 ++++++++ packages/cli/test/cli-runner.test.ts | 4 +- packages/cli/test/mcp.test.ts | 135 +++++++- packages/core/src/feature-catalog.ts | 3 +- 8 files changed, 704 insertions(+), 10 deletions(-) create mode 100644 packages/cli/src/alternatives-command.ts create mode 100644 packages/cli/test/alternatives-command.test.ts diff --git a/packages/cli/README.md b/packages/cli/README.md index 593d4a4..10e59a7 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -164,10 +164,11 @@ For long task text, use `--issue-file task.md`, pipe it directly to `fixmap plan - **Graph export** — use `fixmap graph` to export the evidence-backed Impact Graph as portable Mermaid or versioned JSON while preserving relationship direction. - **Change scope** — use `fixmap change-scope --touch [--add ]` to expand only caller-selected product work surfaces over bounded dependencies/dependents, then join existing tests, contracts, decisions, reviewers, and policy evidence. Missing additions remain unresolved; no product semantics are inferred. - **Reviewer suggestions** (preview) — use `fixmap reviewers --diff | --working-tree | --report ` to list suggested reviewers per changed path from CODEOWNERS (last matching rule wins, with the source line), annotation owners, architecture policy, and `.mailmap`-canonical commit authors. `--no-history-authors` drops commit authors. Names print without `@` so nobody is notified; FixMap never requests reviews or infers availability. MCP: `fixmap_reviewers`. -- **Product capabilities** — use `fixmap capability create|update|remove` to maintain a locked, atomic `.fixmap/capabilities.json` of human names, explicit anchors, and bounds; use `fixmap capability ` or `fixmap capabilities` to rebuild/show current evidence. `fixmap capability diff ..` compares exact immutable Git objects without checkout mutation. Generated conclusions are never stored. +- **Product capabilities** — use `fixmap capability create|update|remove` to maintain a locked, atomic `.fixmap/capabilities.json` of human names, explicit anchors, and bounds; use `fixmap capability ` or `fixmap capabilities` to rebuild/show current evidence. `fixmap capability diff ..` compares exact immutable Git objects without checkout mutation. Generated conclusions are never stored. MCP: `fixmap_capability` reads by default and writes through the same locked path with `action: "create" | "update" | "remove"`. - **Cross-repository workspace** — use `fixmap workspace --config --seed ` to resolve local Node, Python, and Maven package providers and trace downstream consumers with versioned identity, manifest, import, and submodule evidence. - **Repository Q&A** — use `fixmap ask --report --question ` to answer structural context, impact, test, risk, policy, ADR, and annotation questions from bounded report evidence with citations and explicit unknowns. - **Migration planner** — use `fixmap migrate --input ` to validate and render dependency phases, blast radius, compatibility, verification, and rollback without executing or applying the plan. +- **Plan alternatives** (preview) — use `fixmap alternatives --input `, or `--report ` twice or more with `--graph-fingerprint `, to compare 2-20 plans for the same graph state side by side on edits, blast radius, contract compatibility, policy, tests, reversibility, and uncertainty. FixMap states each trade-off from the evidence and never picks a winner by score. MCP: `fixmap_alternatives`. - **Reverse documentation** — use `fixmap reverse-docs --input ` to create review-only module or architecture drafts from exact structural evidence without writing the requested destination. - **Architecture history** — use `fixmap history --repo . --from --to ` to compare immutable committed snapshots without checkout or worktree mutation. It also reports decision disagreements: edges at `--to` that break an import rule stated by an accepted decision record in `fixmap-deny-imports` frontmatter (one `from-pattern -> denied-pattern` per item). Snapshots are cached per exact commit outside the repository; `--no-cache` rebuilds them. - **Historical plans (preview)** — `fixmap plan --issue --at ` ranks against the repository as it was at that commit, read from Git objects without checking out or changing the worktree. @@ -226,6 +227,7 @@ fixmap graph Export the Impact Graph as Mermaid or JSON fixmap workspace Map package dependencies and impact across local repositories fixmap ask Answer report-only structural questions with citations fixmap migrate Build a dependency-ordered, review-only migration plan +fixmap alternatives Compare alternative plans side by side without picking a winner fixmap reverse-docs Draft review-only documentation from exact structural evidence fixmap history Compare architecture at two committed refs without checkout fixmap supply-chain Import normalized external scanner and SBOM evidence diff --git a/packages/cli/src/alternatives-command.ts b/packages/cli/src/alternatives-command.ts new file mode 100644 index 0000000..63f515d --- /dev/null +++ b/packages/cli/src/alternatives-command.ts @@ -0,0 +1,305 @@ +import { writeFile } from "node:fs/promises"; +import { basename, resolve } from "node:path"; +import { + comparePlanAlternatives, + createGraphIdentity, + validateFixMapReport, + type AlternativePlanComparison, + type FixMapReport, + type PlanAlternative, + type PlanAlternativeAssessment +} from "@aryam/fixmap-core"; +import { describeInputReadError, readDecodedTextFile } from "./decode-input.js"; + +export const ALTERNATIVES_USAGE = `Usage: + fixmap alternatives --input [--format markdown|json] [--output ] + fixmap alternatives --report --report --graph-fingerprint [options] + +Compares 2-20 alternative plans for the same graph state side by side: intended edits, impact, +contract and total blast radius, contract compatibility, policy errors and warnings, planned tests, +reversibility and uncertainty. FixMap never picks a winner or folds the axes into a score; it lists +each trade-off with the evidence behind it and names the plans no other plan beats on every axis. + +Options: + --input Version-1 input: {"alternativesInputVersion": 1, "alternatives": [...]} + --report Saved FixMap JSON plan to compare (repeatable; may be mixed with --input) + --graph-fingerprint Graph state every --report was planned against, such as the commit SHA. + A saved plan does not record it, so you state it. + --format markdown (default) or json + --output Write the comparison to a file instead of stdout +`; + +export type AlternativesSource = { + /** Version-1 input object, or a path to a JSON file holding one. */ + input?: unknown; + /** Saved FixMap JSON plan report paths. */ + reports?: string[]; + graphFingerprint?: string; +}; + +type Dependencies = { + stdout?: (text: string) => void; + stderr?: (text: string) => void; + writeOutput?: (path: string, contents: string) => Promise; +}; + +export async function runAlternativesCommand(args: string[], dependencies: Dependencies = {}): Promise { + const stdout = dependencies.stdout ?? ((text: string) => process.stdout.write(text)); + const stderr = dependencies.stderr ?? ((text: string) => process.stderr.write(text)); + if (args.includes("--help") || args.includes("-h")) { stdout(ALTERNATIVES_USAGE); return 0; } + let parsed: ReturnType; + try { + parsed = parseArgs(args); + } catch (error) { + stderr(`${message(error)}\n\n${ALTERNATIVES_USAGE}`); + return 1; + } + const inputs = [parsed.input, ...parsed.reports].filter((path): path is string => Boolean(path)); + if (parsed.output && inputs.some((path) => samePath(resolve(path), resolve(parsed.output!)))) { + stderr("alternatives --output must not overwrite an input file.\n"); + return 1; + } + try { + const comparison = compareAlternativesFromSources(parsed); + const rendered = parsed.format === "json" ? `${JSON.stringify(comparison, null, 2)}\n` : renderAlternativesMarkdown(comparison); + if (parsed.output) await (dependencies.writeOutput ?? ((path, contents) => writeFile(path, contents, "utf8")))(parsed.output, rendered); + else stdout(rendered); + return 0; + } catch (error) { + stderr(`Could not compare plan alternatives: ${message(error)}\n`); + return 1; + } +} + +/** Shared by the CLI and MCP: loads every source, then lets Core validate and compare them. */ +export function compareAlternativesFromSources(source: AlternativesSource): AlternativePlanComparison { + const reports = source.reports ?? []; + if (source.input === undefined && reports.length === 0) throw new Error("Provide an alternatives input, saved plan reports, or both."); + if (reports.length > 0 && !source.graphFingerprint) { + throw new Error("Comparing saved plans requires a graph fingerprint (for example the commit SHA they were planned at); a saved plan does not record one."); + } + if (reports.length === 0 && source.graphFingerprint) throw new Error("A graph fingerprint applies only to saved plan reports."); + const alternatives: PlanAlternative[] = []; + if (source.input !== undefined) { + const raw = typeof source.input === "string" ? readJson(source.input, "alternatives input") : source.input; + alternatives.push(...parseAlternativesInput(raw)); + } + const used = new Set(alternatives.map((alternative) => alternative.id)); + for (const path of reports) { + const report = loadPlanReport(path); + const alternative = planAlternativeFromReport(report, { id: uniqueId(idFromPath(path), used), graphFingerprint: source.graphFingerprint! }); + used.add(alternative.id); + alternatives.push(alternative); + } + return comparePlanAlternatives(alternatives); +} + +export function parseAlternativesInput(value: unknown): PlanAlternative[] { + if (!isRecord(value) || value.alternativesInputVersion !== 1) throw new Error("Alternatives input alternativesInputVersion must be 1."); + if (!Array.isArray(value.alternatives)) throw new Error("Alternatives input alternatives must be an array."); + return value.alternatives as PlanAlternative[]; +} + +/** + * Report adapter. A saved plan carries ranked files, impact, test routes, risks and policy findings but + * no graph state, contract diff or rollback plan, so each mapping below uses only what the report says. + */ +export function planAlternativeFromReport(report: FixMapReport, options: { id: string; graphFingerprint: string }): PlanAlternative { + const editPaths = [...new Set(report.impact?.seeds.length ? report.impact.seeds : report.contextFiles.map((file) => file.path))]; + if (editPaths.length === 0) throw new Error(`Plan ${options.id} has no ranked context files or impact seeds to treat as intended edits.`); + const edits = new Set(editPaths); + const impactByPath = new Map((report.impact?.files ?? []).map((file) => [file.path, file])); + const breaking = new Map(); + for (const finding of report.policy?.findings ?? []) { + if (finding.code !== "breaking-contract") continue; + for (const path of finding.paths) if (!breaking.has(path)) breaking.set(path, finding.message); + } + const tests = report.testRoutes.filter((route) => route.kind === "test").map((route) => { + const covers = new Set(); + for (const path of route.relatedFiles) { + if (edits.has(path)) covers.add(path); + for (const evidence of impactByPath.get(path)?.evidence ?? []) { + if ((evidence.kind === "test-route" || evidence.kind === "imported-by") && edits.has(evidence.seed)) covers.add(evidence.seed); + } + } + return { command: bounded(route.command), covers: [...covers].map(fileIdentity), reason: bounded(route.reason) }; + }); + const uncertainties: PlanAlternative["uncertainties"] = report.risks.map((risk, index) => ({ + id: `risk-${index + 1}`, + severity: risk.severity, + detail: bounded(`${risk.area}: ${risk.reason}`) + })); + if (report.analysis?.grounding.specificity === "vague") { + uncertainties.push({ id: "vague-task", severity: "high", detail: "The task named nothing FixMap could anchor to a file or identifier." }); + } + const unresolved = report.analysis?.grounding.unresolvedIdentifiers ?? []; + if (unresolved.length > 0) { + uncertainties.push({ id: "unresolved-identifiers", severity: "medium", detail: bounded(`Identifiers not found in the repository: ${unresolved.join(", ")}`) }); + } + return { + planAlternativeVersion: 1, + id: options.id, + graphFingerprint: options.graphFingerprint, + edits: editPaths.map(fileIdentity), + impacts: [...impactByPath.keys()].filter((path) => !edits.has(path)).map(fileIdentity), + contracts: [...breaking].map(([path, reason]) => ({ identity: fileIdentity(path), compatibility: "breaking" as const, reason: bounded(reason) })), + policyFindings: (report.policy?.findings ?? []).map((finding) => ({ ruleId: safeId(finding.ruleId), severity: finding.severity, message: bounded(finding.message) })), + tests, + // Source edits can be reverted in version control; a plan records nothing about deploys or data, so this stays partial. + reversibility: { + mode: "partial", + reason: "A saved plan does not record deploy, data or migration effects; only the source edits are known to be revertible.", + rollbackSteps: ["Revert the planned edits in version control."] + }, + uncertainties + }; +} + +type Direction = "lower" | "higher"; +const AXES: Array<{ axis: string; label: string; direction: Direction; value: (entry: PlanAlternativeAssessment) => number | string }> = [ + { axis: "edit-identities", label: "Intended edits", direction: "lower", value: (entry) => entry.metrics.editIdentities }, + { axis: "impact-identities", label: "Impact identities", direction: "lower", value: (entry) => entry.metrics.impactIdentities }, + { axis: "contract-identities", label: "Contract identities", direction: "lower", value: (entry) => entry.metrics.contractIdentities }, + { axis: "blast-radius-identities", label: "Total blast radius", direction: "lower", value: (entry) => entry.metrics.totalBlastRadiusIdentities }, + { axis: "breaking-contracts", label: "Breaking contracts", direction: "lower", value: (entry) => entry.metrics.breakingContracts }, + { axis: "unknown-contracts", label: "Unknown contracts", direction: "lower", value: (entry) => entry.metrics.unknownContracts }, + { axis: "policy-errors", label: "Policy errors", direction: "lower", value: (entry) => entry.metrics.policyErrors }, + { axis: "policy-warnings", label: "Policy warnings", direction: "lower", value: (entry) => entry.metrics.policyWarnings }, + { axis: "planned-tests", label: "Planned tests", direction: "higher", value: (entry) => entry.metrics.plannedTests }, + { axis: "covered-edit-identities", label: "Edits with test coverage", direction: "higher", value: (entry) => entry.metrics.coveredEditIdentities }, + { axis: "uncovered-edits", label: "Edits without test coverage", direction: "lower", value: (entry) => entry.metrics.uncoveredEditIdentities.length }, + { axis: "reversibility", label: "Reversibility", direction: "higher", value: (entry) => entry.metrics.reversibility }, + { axis: "high-uncertainties", label: "High uncertainties", direction: "lower", value: (entry) => entry.metrics.highUncertainties }, + { axis: "medium-uncertainties", label: "Medium uncertainties", direction: "lower", value: (entry) => entry.metrics.mediumUncertainties } +]; + +export function renderAlternativesMarkdown(comparison: AlternativePlanComparison): string { + const ids = comparison.alternatives.map((entry) => entry.id); + const lines = [ + "# FixMap plan alternatives", + "", + `Graph fingerprint: ${code(comparison.graphFingerprint)}`, + `Comparison fingerprint: ${code(comparison.fingerprint)}`, + "", + "FixMap does not pick a winner. Each axis is compared on its own; which trade-off matters is your call.", + "", + "## Side by side", + "", + `| Axis | ${ids.map(code).join(" | ")} |`, + `| --- | ${ids.map(() => "---").join(" | ")} |`, + ...AXES.map((axis) => `| ${axis.label} (${axis.direction} is better) | ${comparison.alternatives.map((entry) => String(axis.value(entry))).join(" | ")} |`), + "", + "## Trade-offs", + "" + ]; + for (const pair of comparison.pairwise) { + const leftBetter: string[] = []; + const rightBetter: string[] = []; + for (const difference of pair.differences) { + const axis = AXES.find((entry) => entry.axis === difference.axis); + if (!axis) continue; + // Each line reads from the better plan's side: " vs ". + if (better(axis.direction, difference.left, difference.right)) leftBetter.push(`${axis.label.toLowerCase()} (${difference.left} vs ${difference.right})`); + else rightBetter.push(`${axis.label.toLowerCase()} (${difference.right} vs ${difference.left})`); + } + if (leftBetter.length === 0 && rightBetter.length === 0) { + lines.push(`- ${code(pair.left)} and ${code(pair.right)} are equal on every compared axis.`); + continue; + } + lines.push(`- ${code(pair.left)} vs ${code(pair.right)}:`); + lines.push(` - ${code(pair.left)} is better on ${leftBetter.length > 0 ? leftBetter.join(", ") : "no axis"}.`); + lines.push(` - ${code(pair.right)} is better on ${rightBetter.length > 0 ? rightBetter.join(", ") : "no axis"}.`); + } + lines.push( + "", + `Not beaten on every axis by another plan: ${comparison.nonDominatedAlternatives.map(code).join(", ")}.`, + "Planned-test and coverage counts are shown but do not decide this; more tests are not automatically better.", + "", + "## Evidence", + "" + ); + for (const entry of comparison.alternatives) { + lines.push(`### ${code(entry.id)}`, ""); + for (const evidence of entry.evidence) { + const identities = evidence.identities && evidence.identities.length > 0 && evidence.axis !== "edits" && evidence.axis !== "impact" + ? ` ${evidence.axis === "tests" ? "Uncovered" : "Identities"}: ${evidence.identities.slice(0, 10).map(code).join(", ")}${evidence.identities.length > 10 ? `, and ${evidence.identities.length - 10} more` : ""}.` + : ""; + lines.push(`- **${evidence.axis}**: ${evidence.detail}${identities}`); + } + lines.push(""); + } + lines.push("> Review-only comparison. FixMap did not execute, apply or rank these plans."); + return `${lines.join("\n")}\n`; +} + +function better(direction: Direction, left: string | number, right: string | number): boolean { + if (typeof left === "string" || typeof right === "string") { + const rank = (value: string | number) => (value === "full" ? 2 : value === "partial" ? 1 : 0); + return rank(left) > rank(right); + } + return direction === "lower" ? left < right : left > right; +} + +function parseArgs(args: string[]) { + const reports: string[] = []; + const singles = new Map(); + for (let index = 0; index < args.length; index += 1) { + const raw = args[index]!; + const equals = raw.match(/^(--[a-z-]+)=(.*)$/); + const flag = equals?.[1] ?? raw; + if (!["--input", "--report", "--graph-fingerprint", "--format", "--output"].includes(flag)) throw new Error(`Unknown alternatives option: ${raw}`); + const value = equals?.[2] ?? args[++index]; + if (typeof value !== "string" || !value.trim() || (!equals && value.startsWith("--"))) throw new Error(`${flag} requires a value.`); + if (flag === "--report") reports.push(value.trim()); + else if (singles.has(flag)) throw new Error(`Pass ${flag} only once.`); + else singles.set(flag, value.trim()); + } + const format = (singles.get("--format") ?? "markdown").toLowerCase(); + if (format !== "markdown" && format !== "json") throw new Error("--format must be markdown or json."); + const input = singles.get("--input"); + if (!input && reports.length === 0) throw new Error("alternatives requires --input or --report (repeatable)."); + const graphFingerprint = singles.get("--graph-fingerprint"); + const output = singles.get("--output"); + return { + format: format as "markdown" | "json", + reports, + ...(input ? { input } : {}), + ...(graphFingerprint ? { graphFingerprint } : {}), + ...(output ? { output } : {}) + }; +} + +function loadPlanReport(path: string): FixMapReport { + const loaded = validateFixMapReport(readJson(path, "plan report"), `"${path}"`); + if (!loaded.success) throw new Error(loaded.message); + return loaded.report; +} + +function readJson(path: string, label: string): unknown { + let text: string; + try { + text = readDecodedTextFile(path); + } catch (error) { + throw new Error(`Could not read ${label} ${describeInputReadError(path, error)}`); + } + try { + return JSON.parse(text) as unknown; + } catch { + throw new Error(`${label} "${path}" is not valid JSON.`); + } +} + +function fileIdentity(path: string): string { return createGraphIdentity({ workspace: "local", kind: "file", key: path }); } +function idFromPath(path: string): string { return safeId(basename(path).replace(/\.json$/i, "")); } +function safeId(value: string): string { + return value.replace(/[^A-Za-z0-9._:-]+/g, "-").replace(/^[^A-Za-z0-9]+/, "").slice(0, 120) || "plan"; +} +function uniqueId(base: string, used: Set): string { + if (!used.has(base)) return base; + for (let suffix = 2; ; suffix += 1) if (!used.has(`${base}-${suffix}`)) return `${base}-${suffix}`; +} +function bounded(value: string): string { return value.trim().slice(0, 1_000) || "Not stated in the plan."; } +function code(value: string): string { return `\`${value.replaceAll("`", "'")}\``; } +function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } +function samePath(left: string, right: string): boolean { return process.platform === "win32" ? left.toLowerCase() === right.toLowerCase() : left === right; } +function message(error: unknown): string { return error instanceof Error ? error.message : String(error); } diff --git a/packages/cli/src/cli-runner.ts b/packages/cli/src/cli-runner.ts index 7fea78c..10548ab 100644 --- a/packages/cli/src/cli-runner.ts +++ b/packages/cli/src/cli-runner.ts @@ -114,6 +114,7 @@ Usage: fixmap workspace --config .fixmap/workspace.json --seed auth --format json fixmap ask --report plan.json --question "Which tests should I run?" fixmap migrate --input migration.json --format markdown + fixmap alternatives --report plan-a.json --report plan-b.json --graph-fingerprint fixmap reverse-docs --input reverse-docs.json --format markdown fixmap history --repo . --from v0.9.0 --to HEAD fixmap contracts diff v0.9.0..HEAD @@ -144,6 +145,7 @@ Commands: workspace Preview: Map package dependencies and impact across local repositories ask Preview: Answer structural questions from a saved report with citations migrate Preview: Build a dependency-ordered, review-only migration plan + alternatives Preview: Compare alternative plans side by side without picking a winner reverse-docs Preview: Draft review-only documentation from exact structural evidence history Preview: Compare architecture at two committed Git refs without checkout contracts Preview: List API/schema contracts or diff them across Git refs without checkout @@ -555,6 +557,15 @@ export async function runCli(args: string[], dependencies: CliDependencies = {}) }); } + if (args[0] === "alternatives") { + const { runAlternativesCommand } = await import("./alternatives-command.js"); + return runAlternativesCommand(args.slice(1), { + stdout, + stderr, + ...(dependencies.writeReport ? { writeOutput: dependencies.writeReport } : {}) + }); + } + if (args[0] === "reverse-docs") { const { runReverseDocsCommand } = await import("./reverse-docs-command.js"); return runReverseDocsCommand(args.slice(1), { diff --git a/packages/cli/src/mcp.ts b/packages/cli/src/mcp.ts index d775a70..f7017d5 100644 --- a/packages/cli/src/mcp.ts +++ b/packages/cli/src/mcp.ts @@ -51,6 +51,7 @@ import { runWorkspaceCommand } from "./workspace-command.js"; import { runChangeScopeCommand } from "./change-scope-command.js"; import { runReviewersCommand } from "./reviewers-command.js"; import { runCapabilitiesCommand, runCapabilityCommand } from "./capability-command.js"; +import { compareAlternativesFromSources, renderAlternativesMarkdown } from "./alternatives-command.js"; import { runContractsCommand } from "./contracts-command.js"; import { buildReportForRepository, @@ -341,11 +342,22 @@ const CAPABILITY_TOOL = { title: "FixMap capability", description: "Preview (may change before v0.10.0): List human-owned product capabilities, rebuild one current capability map, or compare it across exact Git refs from .fixmap/capabilities.json. " + + "With action create, update, or remove it writes .fixmap/capabilities.json through the same locked, atomic, symlink-refusing path as fixmap capability; use an action only when the user asks for that change. " + "The store contains explicit names, anchors, and bounds only; no generated conclusions, API, LLM, semantic inference, or account.", + annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false }, inputSchema: { type: "object" as const, properties: { - id: { type: "string", description: "Capability id to show; omit to list definitions" }, + action: { type: "string", enum: ["create", "update", "remove"], description: "Change the store; omit to read" }, + id: { type: "string", description: "Capability id to show or change; omit to list definitions" }, + name: { type: "string", description: "Human-facing capability name (create/update)" }, + touch: { type: "array", items: { type: "string" }, description: "Existing implementation anchors (create/update)" }, + add: { type: "array", items: { type: "string" }, description: "Planned path anchors; missing paths stay unresolved (create/update)" }, + direction: { type: "string", enum: ["dependencies", "dependents", "both"], description: "Traversal direction (create/update)" }, + depth: { type: "integer", minimum: 0, maximum: 8, description: "Maximum traversal depth (create/update)" }, + maxNodes: { type: "integer", minimum: 1, maximum: 2000, description: "Maximum selected plus affected nodes (create/update)" }, + workspace: { type: "string", description: "Store workspace identity when creating the first capability" }, + repository: { type: "string", description: "Store repository identity when creating the first capability" }, from: { type: "string", description: "Earlier exact Git ref; requires id and to" }, to: { type: "string", description: "Later exact Git ref; requires id and from" }, repo: { type: "string", description: "Local checkout path (defaults to the MCP server repository)" }, @@ -356,6 +368,29 @@ const CAPABILITY_TOOL = { } }; +const ALTERNATIVES_TOOL = { + name: "fixmap_alternatives", + title: "FixMap plan alternatives", + description: + "Preview (may change before v0.10.0): Compare 2-20 alternative plans on the same exact graph fingerprint side by side: intended edits, impact, contract and total blast radius, contract compatibility, policy errors and warnings, planned tests, reversibility, and uncertainty. " + + "Provide a version-1 alternatives input, saved FixMap JSON plan paths with the graphFingerprint they were planned against, or both. " + + "It never picks a winner or scores plans; it states each trade-off from the evidence. Read-only.", + annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }, + inputSchema: { + type: "object" as const, + properties: { + input: { + description: "Version-1 alternatives input object or path to a local JSON input file", + anyOf: [{ type: "object" }, { type: "string" }] + }, + reports: { type: "array", items: { type: "string" }, description: "Paths to saved FixMap JSON plans, one alternative each" }, + graphFingerprint: { type: "string", description: "Graph state every report was planned against, such as the commit SHA; required with reports" }, + format: { type: "string", description: "Output format: markdown (default) or json, case-insensitive" } + }, + additionalProperties: false + } +}; + const ASK_TOOL = { name: "fixmap_ask", title: "FixMap ask", @@ -572,7 +607,7 @@ export function createFixMapMcpServer( const server = new Server({ name: "fixmap", version: readVersion() }, { capabilities: { tools: {} } }); server.setRequestHandler(ListToolsRequestSchema, async () => ({ - tools: [PLAN_TOOL, CONTEXT_TOOL, GRAPH_TOOL, CHANGE_SCOPE_TOOL, REVIEWERS_TOOL, CAPABILITY_TOOL, WORKSPACE_TOOL, ASK_TOOL, MIGRATION_TOOL, REVERSE_DOCS_TOOL, HISTORY_TOOL, CONTRACTS_TOOL, SUPPLY_CHAIN_TOOL, RUNTIME_TOOL, VERIFY_TOOL, EXPLAIN_TOOL, COMPARE_TOOL, DOCTOR_TOOL, ANNOTATION_TOOL, OUTCOMES_TOOL, DOSSIER_TOOL] + tools: [PLAN_TOOL, CONTEXT_TOOL, GRAPH_TOOL, CHANGE_SCOPE_TOOL, REVIEWERS_TOOL, CAPABILITY_TOOL, WORKSPACE_TOOL, ASK_TOOL, MIGRATION_TOOL, ALTERNATIVES_TOOL, REVERSE_DOCS_TOOL, HISTORY_TOOL, CONTRACTS_TOOL, SUPPLY_CHAIN_TOOL, RUNTIME_TOOL, VERIFY_TOOL, EXPLAIN_TOOL, COMPARE_TOOL, DOCTOR_TOOL, ANNOTATION_TOOL, OUTCOMES_TOOL, DOSSIER_TOOL] })); server.setRequestHandler(CallToolRequestSchema, async (request) => { @@ -675,6 +710,36 @@ export function createFixMapMcpServer( const exitCode = await runReviewersCommand(commandArgs, { stdout: (value) => stdout.push(value), stderr: (value) => stderr.push(value) }); return { ...(exitCode === 0 ? {} : { isError: true }), content: [{ type: "text", text: exitCode === 0 ? stdout.join("") : stderr.join("") }] }; } + if (request.params.name === ALTERNATIVES_TOOL.name) { + const record = request.params.arguments as Record | undefined; + const invalid = (text: string) => ({ isError: true, content: [{ type: "text", text: `Invalid arguments: ${text}` }] }); + const unknown = Object.keys(record ?? {}).filter((key) => !["input", "reports", "graphFingerprint", "format"].includes(key)); + if (unknown.length > 0) return invalid(`unknown argument${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}.`); + const input = record?.input; + if (input !== undefined && !(typeof input === "string" && input.trim()) && (typeof input !== "object" || input === null || Array.isArray(input))) { + return invalid('"input" must be an alternatives object or a local JSON path.'); + } + const reports = validateStringList(record?.reports, "reports"); + if (!reports.success) return invalid(reports.message); + if (reports.values.length > 20) return invalid('"reports" accepts at most 20 paths.'); + const graphFingerprint = record?.graphFingerprint; + if (graphFingerprint !== undefined && (typeof graphFingerprint !== "string" || !graphFingerprint.trim())) return invalid('"graphFingerprint" must be a non-empty string.'); + const format = normalizeFormat(record?.format); + if (!format.success) return invalid(format.message); + try { + const comparison = compareAlternativesFromSources({ + ...(input !== undefined ? { input: typeof input === "string" ? input.trim() : input } : {}), + reports: reports.values, + ...(typeof graphFingerprint === "string" ? { graphFingerprint: graphFingerprint.trim() } : {}) + }); + return { content: [{ type: "text", text: format.value === "json" ? `${JSON.stringify(comparison, null, 2)}\n` : renderAlternativesMarkdown(comparison) }] }; + } catch (error) { + return { isError: true, content: [{ type: "text", text: `Could not compare plan alternatives: ${error instanceof Error ? error.message : String(error)}` }] }; + } + } + if (request.params.name === CAPABILITY_TOOL.name && (request.params.arguments as Record | undefined)?.action !== undefined) { + return runCapabilityMutationTool(request.params.arguments as Record, defaultRepo); + } if (request.params.name === CAPABILITY_TOOL.name) { const record = request.params.arguments as Record | undefined; const unknown = Object.keys(record ?? {}).filter((key) => !["id", "from", "to", "repo", "format", "noCache"].includes(key)); @@ -1442,6 +1507,47 @@ function validateStringList( return { success: true, values: candidate.map((entry) => String(entry).trim()) }; } +/** Same validation and errors as `fixmap capability create|update|remove`: arguments become CLI flags. */ +async function runCapabilityMutationTool(record: Record, defaultRepo: string) { + const invalid = (text: string) => ({ isError: true, content: [{ type: "text", text: `Invalid arguments: ${text}` }] }); + const action = record.action; + if (action !== "create" && action !== "update" && action !== "remove") return invalid('"action" must be create, update, or remove.'); + const allowed = action === "remove" + ? ["action", "id", "repo", "format"] + : ["action", "id", "name", "touch", "add", "direction", "depth", "maxNodes", "workspace", "repository", "repo", "format"]; + const unknown = Object.keys(record).filter((key) => !allowed.includes(key)); + if (unknown.length > 0) return invalid(`argument${unknown.length === 1 ? "" : "s"} not allowed for ${action}: ${unknown.join(", ")}.`); + if (typeof record.id !== "string" || !record.id.trim()) return invalid(`capability ${action} requires "id".`); + for (const key of ["name", "direction", "workspace", "repository", "repo"] as const) { + const value = record[key]; + if (value !== undefined && (typeof value !== "string" || !value.trim())) return invalid(`"${key}" must be a non-empty string.`); + } + for (const key of ["depth", "maxNodes"] as const) { + if (record[key] !== undefined && !Number.isSafeInteger(record[key])) return invalid(`"${key}" must be an integer.`); + } + if (typeof record.repo === "string" && /^https?:\/\//i.test(record.repo)) return invalid('"repo" must be a local checkout.'); + const touch = validateStringList(record.touch, "touch"); + if (!touch.success) return invalid(touch.message); + const add = validateStringList(record.add, "add"); + if (!add.success) return invalid(add.message); + const format = normalizeFormat(record.format); + if (!format.success) return invalid(format.message); + const commandArgs = [action, record.id.trim()]; + if (typeof record.name === "string") commandArgs.push("--name", record.name.trim()); + for (const path of touch.values) commandArgs.push("--touch", path); + for (const path of add.values) commandArgs.push("--add", path); + if (typeof record.direction === "string") commandArgs.push("--direction", record.direction.trim()); + if (record.depth !== undefined) commandArgs.push("--depth", String(record.depth)); + if (record.maxNodes !== undefined) commandArgs.push("--max-nodes", String(record.maxNodes)); + if (typeof record.workspace === "string") commandArgs.push("--workspace", record.workspace.trim()); + if (typeof record.repository === "string") commandArgs.push("--repository", record.repository.trim()); + commandArgs.push("--repo", typeof record.repo === "string" ? record.repo.trim() : defaultRepo, "--format", format.value ?? "markdown"); + const stdout: string[] = []; + const stderr: string[] = []; + const exitCode = await runCapabilityCommand(commandArgs, { stdout: (value) => stdout.push(value), stderr: (value) => stderr.push(value) }); + return { ...(exitCode === 0 ? {} : { isError: true }), content: [{ type: "text", text: exitCode === 0 ? stdout.join("") : stderr.join("") }] }; +} + function normalizeFormat(candidate: unknown): { success: true; value: "markdown" | "json" | undefined } | { success: false; message: string } { if (candidate === undefined) return { success: true, value: undefined }; if (typeof candidate !== "string") return { success: false, message: '"format" must be either "markdown" or "json".' }; diff --git a/packages/cli/test/alternatives-command.test.ts b/packages/cli/test/alternatives-command.test.ts new file mode 100644 index 0000000..2b05d0d --- /dev/null +++ b/packages/cli/test/alternatives-command.test.ts @@ -0,0 +1,142 @@ +import { mkdtemp, readFile, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { createGraphIdentity, type FixMapReport, type PlanAlternative } from "@aryam/fixmap-core"; +import { planAlternativeFromReport, runAlternativesCommand } from "../src/alternatives-command.js"; + +const file = (path: string) => createGraphIdentity({ workspace: "local", kind: "file", key: path }); + +function alternative(id: string, overrides: Partial = {}): PlanAlternative { + return { + planAlternativeVersion: 1, + id, + graphFingerprint: "graph:abcdef", + edits: [file("src/a.ts")], + impacts: [], + contracts: [], + policyFindings: [], + tests: [{ command: "npm test", covers: [file("src/a.ts")], reason: "covers a" }], + reversibility: { mode: "full", reason: "source only", rollbackSteps: ["git revert"] }, + uncertainties: [], + ...overrides + }; +} + +function report(overrides: Partial = {}): FixMapReport { + return { + reportVersion: 1, + summary: "Fix checkout", + contextFiles: [{ rank: 1, path: "src/checkout.ts", score: 10, confidence: "high", reasons: ["named in task"] }], + testRoutes: [{ command: "npm test -- checkout", kind: "test", reason: "tests import checkout", relatedFiles: ["test/checkout.test.ts"] }], + risks: [], + impact: { + seeds: ["src/checkout.ts"], + files: [{ path: "test/checkout.test.ts", score: 5, confidence: "high", evidence: [{ kind: "test-route", seed: "src/checkout.ts", reason: "routed test" }] }], + inspectionOrder: ["src/checkout.ts", "test/checkout.test.ts"], + history: { available: false, eligibleCommits: 0, shallow: false, truncated: false } + }, + changedFiles: [], + diagnostics: [], + ...overrides + }; +} + +function capture() { + const stdout: string[] = []; + const stderr: string[] = []; + return { stdout, stderr, io: { stdout: (value: string) => stdout.push(value), stderr: (value: string) => stderr.push(value) } }; +} + +async function writeJson(name: string, value: unknown): Promise { + const directory = await mkdtemp(join(tmpdir(), "fixmap-alternatives-")); + const path = join(directory, name); + await writeFile(path, JSON.stringify(value)); + return path; +} + +describe("fixmap alternatives", () => { + it("compares inputs side by side and states trade-offs without naming a winner", async () => { + const narrow = alternative("narrow", { uncertainties: [{ id: "u1", severity: "high", detail: "unverified caller" }] }); + const broad = alternative("broad", { + edits: [file("src/a.ts"), file("src/b.ts")], + tests: [{ command: "npm test", covers: [file("src/a.ts"), file("src/b.ts")], reason: "covers both" }] + }); + const input = await writeJson("alternatives.json", { alternativesInputVersion: 1, alternatives: [narrow, broad] }); + + const json = capture(); + expect(await runAlternativesCommand(["--input", input, "--format", "json"], json.io)).toBe(0); + const comparison = JSON.parse(json.stdout.join("")); + expect(comparison).toMatchObject({ alternativePlanComparisonVersion: 1, graphFingerprint: "graph:abcdef" }); + expect(comparison.alternatives.map((entry: { id: string }) => entry.id)).toEqual(["broad", "narrow"]); + expect(comparison.nonDominatedAlternatives).toEqual(["broad", "narrow"]); + + const markdown = capture(); + expect(await runAlternativesCommand(["--input", input], markdown.io)).toBe(0); + const text = markdown.stdout.join(""); + expect(text).toContain("FixMap does not pick a winner"); + expect(text).toContain("| Total blast radius (lower is better) | 2 | 1 |"); + expect(text).toContain("`broad` is better on edits with test coverage (2 vs 1), high uncertainties (0 vs 1)."); + expect(text).toContain("`narrow` is better on intended edits (1 vs 2), total blast radius (1 vs 2)."); + expect(text).not.toMatch(/recommend|winner is|best plan/i); + }); + + it("builds alternatives from saved plan reports with an explicit graph fingerprint", async () => { + const small = await writeJson("small.json", report()); + const wideReport = report({ + contextFiles: [ + { rank: 1, path: "src/checkout.ts", score: 10, confidence: "high", reasons: ["named"] }, + { rank: 2, path: "src/cart.ts", score: 8, confidence: "medium", reasons: ["imports"] } + ], + impact: undefined, + risks: [{ area: "payments", reason: "touches billing", severity: "high" }], + policy: { policyFingerprint: `git:${"a".repeat(40)}`, findings: [{ code: "breaking-contract", severity: "error", ruleId: "api-stability", message: "Public API changed", paths: ["src/cart.ts"], evidence: [] }] } + }); + const wide = await writeJson("wide.json", wideReport); + + const io = capture(); + expect(await runAlternativesCommand(["--report", small, "--report", wide, "--graph-fingerprint", "commit:0123456789", "--format", "json"], io.io), io.stderr.join("")).toBe(0); + const comparison = JSON.parse(io.stdout.join("")); + expect(comparison.graphFingerprint).toBe("commit:0123456789"); + const byId = Object.fromEntries(comparison.alternatives.map((entry: { id: string; metrics: unknown }) => [entry.id, entry.metrics])); + expect(byId.small).toMatchObject({ editIdentities: 1, impactIdentities: 1, coveredEditIdentities: 1, breakingContracts: 0, policyErrors: 0 }); + expect(byId.wide).toMatchObject({ editIdentities: 2, breakingContracts: 1, policyErrors: 1, highUncertainties: 1, coveredEditIdentities: 0 }); + expect(comparison.nonDominatedAlternatives).toEqual(["small"]); + + const adapted = planAlternativeFromReport(wideReport, { id: "wide", graphFingerprint: "commit:0123456789" }); + expect(adapted.contracts).toEqual([{ identity: file("src/cart.ts"), compatibility: "breaking", reason: "Public API changed" }]); + expect(adapted.reversibility.mode).toBe("partial"); + + const missing = capture(); + expect(await runAlternativesCommand(["--report", small, "--report", wide], missing.io)).toBe(1); + expect(missing.stderr.join("")).toContain("requires a graph fingerprint"); + }); + + it("rejects alternatives planned against different graph fingerprints", async () => { + const input = await writeJson("mismatch.json", { + alternativesInputVersion: 1, + alternatives: [alternative("a"), alternative("b", { graphFingerprint: "graph:other1" })] + }); + const io = capture(); + expect(await runAlternativesCommand(["--input", input], io.io)).toBe(1); + expect(io.stderr.join("")).toContain("same exact graph fingerprint"); + + const mixed = await writeJson("one.json", { alternativesInputVersion: 1, alternatives: [alternative("a")] }); + const plan = await writeJson("plan.json", report()); + const mixedIo = capture(); + expect(await runAlternativesCommand(["--input", mixed, "--report", plan, "--graph-fingerprint", "commit:different"], mixedIo.io)).toBe(1); + expect(mixedIo.stderr.join("")).toContain("same exact graph fingerprint"); + }); + + it("refuses to overwrite an input and rejects unknown options", async () => { + const input = await writeJson("alternatives.json", { alternativesInputVersion: 1, alternatives: [alternative("a"), alternative("b")] }); + const overwrite = capture(); + expect(await runAlternativesCommand(["--input", input, "--output", input], overwrite.io)).toBe(1); + expect(overwrite.stderr.join("")).toContain("must not overwrite"); + expect(JSON.parse(await readFile(input, "utf8")).alternativesInputVersion).toBe(1); + + const unknown = capture(); + expect(await runAlternativesCommand(["--input", input, "--score"], unknown.io)).toBe(1); + expect(unknown.stderr.join("")).toContain("Unknown alternatives option"); + }); +}); diff --git a/packages/cli/test/cli-runner.test.ts b/packages/cli/test/cli-runner.test.ts index 3f516b7..82f5f0d 100644 --- a/packages/cli/test/cli-runner.test.ts +++ b/packages/cli/test/cli-runner.test.ts @@ -200,7 +200,7 @@ describe("CLI argument handling", () => { const features = (JSON.parse(catalog.stdout.join("")) as { features: Array<{ name: string; preview?: true }> }).features; expect(features.filter((feature) => feature.preview).map((feature) => feature.name)).toEqual([ "Change scope", "Reviewer suggestions", "Product capabilities", "Cross-repository workspace", "Repository Q&A", "Migration planning", - "Reverse documentation", "Architecture history", "Historical plans", "Contract Guardian", "Supply-chain evidence", "Runtime evidence", "Evidence import", "Outcome feedback loop", "Change dossier", "Execution sandbox", + "Plan alternatives", "Reverse documentation", "Architecture history", "Historical plans", "Contract Guardian", "Supply-chain evidence", "Runtime evidence", "Evidence import", "Outcome feedback loop", "Change dossier", "Execution sandbox", "Local hybrid retrieval" ]); expect(features.find((feature) => feature.name === "Plan")?.preview).toBeUndefined(); @@ -208,7 +208,7 @@ describe("CLI argument handling", () => { const help = capture(); expect(await runCli(["--help"], help.dependencies)).toBe(0); const commands = help.stdout.join("").split("Commands:")[1]?.split("Options:")[0] ?? ""; - for (const command of ["change-scope", "reviewers", "editor", "capability", "capabilities", "workspace", "ask", "migrate", "reverse-docs", "history", "contracts", "supply-chain", "runtime", "sandbox"]) { + for (const command of ["change-scope", "reviewers", "editor", "capability", "capabilities", "workspace", "ask", "migrate", "alternatives", "reverse-docs", "history", "contracts", "supply-chain", "runtime", "sandbox"]) { expect(commands).toMatch(new RegExp(`\\n ${command} +Preview: `)); } for (const command of ["plan", "verify", "context", "graph", "annotate", "watch"]) { diff --git a/packages/cli/test/mcp.test.ts b/packages/cli/test/mcp.test.ts index 1dcae56..b397708 100644 --- a/packages/cli/test/mcp.test.ts +++ b/packages/cli/test/mcp.test.ts @@ -1,5 +1,5 @@ import { execFile, execFileSync } from "node:child_process"; -import { mkdtemp, mkdir, writeFile, rm, readFile } from "node:fs/promises"; +import { mkdtemp, mkdir, writeFile, rm, readFile, symlink } from "node:fs/promises"; import { createHash } from "node:crypto"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -220,7 +220,7 @@ describe("fixmap mcp server", () => { const { tools } = await client.listTools(); const preview = tools.filter((tool) => tool.description?.startsWith("Preview (may change before v0.10.0): ")).map((tool) => tool.name).sort(); expect(preview).toEqual([ - "fixmap_ask", "fixmap_capability", "fixmap_change_scope", "fixmap_contracts", "fixmap_dossier", "fixmap_history", "fixmap_migrate", + "fixmap_alternatives", "fixmap_ask", "fixmap_capability", "fixmap_change_scope", "fixmap_contracts", "fixmap_dossier", "fixmap_history", "fixmap_migrate", "fixmap_outcomes", "fixmap_reverse_docs", "fixmap_reviewers", "fixmap_runtime", "fixmap_supply_chain", "fixmap_workspace" ]); for (const finished of ["fixmap_plan", "fixmap_context", "fixmap_graph", "fixmap_verify", "fixmap_explain", "fixmap_compare", "fixmap_doctor"]) { @@ -418,7 +418,7 @@ describe("fixmap mcp server", () => { const tools = await client.listTools(); expect(tools.tools.map((tool) => tool.name)).toEqual([ - "fixmap_plan", "fixmap_context", "fixmap_graph", "fixmap_change_scope", "fixmap_reviewers", "fixmap_capability", "fixmap_workspace", "fixmap_ask", "fixmap_migrate", "fixmap_reverse_docs", "fixmap_history", "fixmap_contracts", "fixmap_supply_chain", "fixmap_runtime", "fixmap_verify", "fixmap_explain", "fixmap_compare", "fixmap_doctor", "fixmap_annotate", "fixmap_outcomes", "fixmap_dossier" + "fixmap_plan", "fixmap_context", "fixmap_graph", "fixmap_change_scope", "fixmap_reviewers", "fixmap_capability", "fixmap_workspace", "fixmap_ask", "fixmap_migrate", "fixmap_alternatives", "fixmap_reverse_docs", "fixmap_history", "fixmap_contracts", "fixmap_supply_chain", "fixmap_runtime", "fixmap_verify", "fixmap_explain", "fixmap_compare", "fixmap_doctor", "fixmap_annotate", "fixmap_outcomes", "fixmap_dossier" ]); const plan = tools.tools.find((tool) => tool.name === "fixmap_plan"); const verify = tools.tools.find((tool) => tool.name === "fixmap_verify"); @@ -445,7 +445,13 @@ describe("fixmap mcp server", () => { expect(changeScope?.description).toContain("does not interpret product requirements"); expect(changeScope?.inputSchema.additionalProperties).toBe(false); const capability = tools.tools.find((tool) => tool.name === "fixmap_capability"); - expect(Object.keys(capability?.inputSchema.properties ?? {}).sort()).toEqual(["id", "from", "to", "repo", "format", "noCache"].sort()); + expect(Object.keys(capability?.inputSchema.properties ?? {}).sort()).toEqual([ + "action", "id", "name", "touch", "add", "direction", "depth", "maxNodes", "workspace", "repository", "from", "to", "repo", "format", "noCache" + ].sort()); + expect(capability?.annotations).toMatchObject({ readOnlyHint: false, destructiveHint: true, openWorldHint: false }); + const alternatives = tools.tools.find((tool) => tool.name === "fixmap_alternatives"); + expect(Object.keys(alternatives?.inputSchema.properties ?? {}).sort()).toEqual(["input", "reports", "graphFingerprint", "format"].sort()); + expect(alternatives?.annotations).toMatchObject({ readOnlyHint: true, destructiveHint: false, openWorldHint: false }); expect(capability?.inputSchema.additionalProperties).toBe(false); const workspace = tools.tools.find((tool) => tool.name === "fixmap_workspace"); expect(Object.keys(workspace?.inputSchema.properties ?? {}).sort()).toEqual(["config", "seeds", "format", "noCache"].sort()); @@ -1325,3 +1331,124 @@ describe("MCP surface parity", () => { expect(parsePlanArguments({ issue: "https://github.com/o/r/pull/158.patch" }).success).toBe(false); }); }); + +describe("fixmap mcp alternatives and capability editing", () => { + const text = (result: { content?: unknown }) => (result.content as Array<{ text: string }>)[0]!.text; + const identity = (path: string) => createGraphIdentity({ workspace: "local", kind: "file", key: path }); + const alternative = (id: string, graphFingerprint = "graph:abcdef") => ({ + planAlternativeVersion: 1, id, graphFingerprint, + edits: [identity(`src/${id}.ts`)], impacts: [], contracts: [], policyFindings: [], + tests: [{ command: "npm test", covers: [identity(`src/${id}.ts`)], reason: "unit" }], + reversibility: { mode: "full", reason: "source only", rollbackSteps: ["git revert"] }, uncertainties: [] + }); + + it("compares alternatives from an input object and from saved plans, rejecting mismatched graphs", { timeout: 30_000 }, async () => { + const root = await createAuthFixture(); + const client = await connectClient(); + try { + const compared = await client.callTool({ name: "fixmap_alternatives", arguments: { + input: { alternativesInputVersion: 1, alternatives: [alternative("a"), alternative("b")] }, format: "json" + } }); + expect(compared.isError).toBeFalsy(); + expect(JSON.parse(text(compared))).toMatchObject({ alternativePlanComparisonVersion: 1, nonDominatedAlternatives: ["a", "b"] }); + + const mismatched = await client.callTool({ name: "fixmap_alternatives", arguments: { + input: { alternativesInputVersion: 1, alternatives: [alternative("a"), alternative("b", "graph:other1")] } + } }); + expect(mismatched.isError).toBe(true); + expect(text(mismatched)).toContain("same exact graph fingerprint"); + + const planned = await client.callTool({ name: "fixmap_plan", arguments: { issue: "sendResetEmail fails", repo: root, format: "json" } }); + await writeFile(join(root, "plan-a.json"), text(planned)); + await writeFile(join(root, "plan-b.json"), text(planned)); + const fromReports = await client.callTool({ name: "fixmap_alternatives", arguments: { + reports: [join(root, "plan-a.json"), join(root, "plan-b.json")], graphFingerprint: "commit:0123456789" + } }); + expect(fromReports.isError).toBeFalsy(); + expect(text(fromReports)).toContain("`plan-a` and `plan-b` are equal on every compared axis."); + const withoutGraph = await client.callTool({ name: "fixmap_alternatives", arguments: { reports: [join(root, "plan-a.json"), join(root, "plan-b.json")] } }); + expect(withoutGraph.isError).toBe(true); + expect(text(withoutGraph)).toContain("requires a graph fingerprint"); + } finally { + await client.close(); + await rm(root, { recursive: true, force: true }); + } + }); + + it("creates, updates, and removes capabilities through the CLI write path", { timeout: 30_000 }, async () => { + const root = await createAuthFixture(); + const client = await connectClient(); + const store = async () => JSON.parse(await readFile(join(root, ".fixmap", "capabilities.json"), "utf8")); + try { + const created = await client.callTool({ name: "fixmap_capability", arguments: { + action: "create", id: "password-recovery", name: "Password recovery", touch: ["src/auth/reset-password.ts"], repo: root + } }); + expect(created.isError).toBeFalsy(); + expect(text(created)).toContain("Created capability password-recovery in .fixmap/capabilities.json."); + expect((await store()).capabilities).toEqual([{ + id: "password-recovery", name: "Password recovery", anchors: [{ operation: "touch", path: "src/auth/reset-password.ts" }] + }]); + + const updated = await client.callTool({ name: "fixmap_capability", arguments: { + action: "update", id: "password-recovery", name: "Account recovery", depth: 1, repo: root, format: "json" + } }); + expect(updated.isError).toBeFalsy(); + expect(JSON.parse(text(updated)).capabilities[0]).toMatchObject({ name: "Account recovery", traversal: { maxDepth: 1 } }); + + const duplicate = await client.callTool({ name: "fixmap_capability", arguments: { + action: "create", id: "password-recovery", touch: ["src/auth/reset-password.ts"], repo: root + } }); + expect(duplicate.isError).toBe(true); + expect(text(duplicate)).toContain("already exists; use capability update"); + + const removeWithAnchors = await client.callTool({ name: "fixmap_capability", arguments: { + action: "remove", id: "password-recovery", touch: ["src/auth/reset-password.ts"], repo: root + } }); + expect(removeWithAnchors.isError).toBe(true); + expect(text(removeWithAnchors)).toContain("not allowed for remove: touch"); + + const removed = await client.callTool({ name: "fixmap_capability", arguments: { action: "remove", id: "password-recovery", repo: root } }); + expect(removed.isError).toBeFalsy(); + expect(text(removed)).toContain("Removed capability password-recovery"); + expect((await store()).capabilities).toEqual([]); + } finally { + await client.close(); + await rm(root, { recursive: true, force: true }); + } + }); + + it("refuses capability writes under a lock, with traversal anchors, or through a linked .fixmap", { timeout: 30_000 }, async () => { + const root = await createAuthFixture(); + const outside = await mkdtemp(join(tmpdir(), "fixmap-mcp-capability-outside-")); + const client = await connectClient(); + try { + const traversal = await client.callTool({ name: "fixmap_capability", arguments: { + action: "create", id: "escape", touch: ["../outside.ts"], repo: root + } }); + expect(traversal.isError).toBe(true); + expect(text(traversal)).toContain("Invalid capability anchor path: ../outside.ts"); + + await mkdir(join(root, ".fixmap"), { recursive: true }); + await writeFile(join(root, ".fixmap", "capabilities.lock"), "busy\n"); + const locked = await client.callTool({ name: "fixmap_capability", arguments: { + action: "create", id: "password-recovery", touch: ["src/auth/reset-password.ts"], repo: root + } }); + expect(locked.isError).toBe(true); + expect(text(locked)).toContain("Another FixMap capability update is in progress"); + await expect(readFile(join(root, ".fixmap", "capabilities.json"), "utf8")).rejects.toMatchObject({ code: "ENOENT" }); + + await rm(join(root, ".fixmap"), { recursive: true, force: true }); + await symlink(outside, join(root, ".fixmap"), process.platform === "win32" ? "junction" : "dir"); + const linked = await client.callTool({ name: "fixmap_capability", arguments: { + action: "create", id: "password-recovery", touch: ["src/auth/reset-password.ts"], repo: root + } }); + expect(linked.isError).toBe(true); + expect(text(linked)).toContain("resolves outside the repository"); + await expect(readFile(join(outside, "capabilities.json"), "utf8")).rejects.toMatchObject({ code: "ENOENT" }); + } finally { + await client.close(); + await rm(root, { recursive: true, force: true }); + await rm(outside, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/core/src/feature-catalog.ts b/packages/core/src/feature-catalog.ts index 160cb4e..0e9b9f8 100644 --- a/packages/core/src/feature-catalog.ts +++ b/packages/core/src/feature-catalog.ts @@ -21,6 +21,7 @@ export const FIXMAP_FEATURES: readonly FixMapFeature[] = [ { name: "Cross-repository workspace", preview: true, command: "fixmap workspace --config .fixmap/workspace.json --seed ", detail: "Resolve Node, Python, and Maven package identities across local checkouts, then trace provider-to-consumer impact with manifest and import evidence." }, { name: "Repository Q&A", preview: true, command: "fixmap ask --report --question ", detail: "Answer structural context, impact, test, risk, and rationale questions from report evidence only, with citations and explicit unknowns." }, { name: "Migration planning", preview: true, command: "fixmap migrate --input ", detail: "Validate an exact identity graph and explicit steps, then order compatibility windows, tests, rollback points, and blast radius without applying changes." }, + { name: "Plan alternatives", preview: true, command: "fixmap alternatives --input ", detail: "Compare 2-20 alternative plans on the same graph state, or saved Plan reports, side by side on edits, blast radius, contract compatibility, policy, tests, reversibility and uncertainty; trade-offs are stated from evidence and no winner is picked by score." }, { name: "Reverse documentation", preview: true, command: "fixmap reverse-docs --input ", detail: "Draft review-only module or architecture Markdown from exact file fingerprints, structural edges, and authored decisions without writing repository files." }, { name: "Architecture history", preview: true, command: "fixmap history --repo . --from --to ", detail: "Compare exact committed architecture snapshots without checking out either ref or changing the worktree, including decision disagreements with accepted ADR import rules and a per-commit snapshot cache." }, { name: "Historical plans", preview: true, command: "fixmap plan --issue --at ", detail: "Rank context files against the repository as it was at a committed ref, read from Git objects without checkout or worktree changes." }, @@ -36,7 +37,7 @@ export const FIXMAP_FEATURES: readonly FixMapFeature[] = [ { name: "Verify", command: "fixmap verify --report ", detail: "Compare the completed diff or working tree with the saved plan; add --fail-on warning for a strict CI gate." }, { name: "Validate", command: "fixmap validate ", detail: "Check a saved report against FixMap's structural compatibility contract." }, { name: "Doctor", command: "fixmap doctor", detail: "Diagnose stale local, global, PATH, and npx install shadows." }, - { name: "MCP", command: "fixmap mcp", detail: "Expose Plan, Context, Graph, Change Scope, Reviewers, Capability maps, Workspace, Ask, Migrate, Reverse Docs, History, Contracts, Supply Chain, Runtime, Outcomes, Dossiers, Explain, Compare, Verify, and Doctor over local stdio." }, + { name: "MCP", command: "fixmap mcp", detail: "Expose Plan, Context, Graph, Change Scope, Reviewers, Capability maps, Workspace, Ask, Migrate, Alternatives, Reverse Docs, History, Contracts, Supply Chain, Runtime, Outcomes, Dossiers, Explain, Compare, Verify, and Doctor over local stdio." }, { name: "Public tasks", command: "fixmap owner/repository#123", detail: "Fetch public GitHub issue or pull-request text anonymously and scan its repository in an isolated checkout." }, { name: "Repository sources", command: "--repo --ref ", detail: "Map a local checkout, file URL, directory archive, or a named branch or tag from a public GitHub repository." }, { name: "Task files", command: "--issue-file ", detail: "Read long task text from UTF-8, UTF-16, or stdin, including BOM-less UTF-16 from common Windows tools." }, From 65b8c9e69cd8b7487f81f3da8a1894545b2cdc45 Mon Sep 17 00:00:00 2001 From: Aryam Goyal Date: Mon, 23 Nov 2026 19:52:28 +0530 Subject: [PATCH 3/5] feat: sensitive-data and supply-chain evidence in Plan and Verify (preview) fixmap plan/verify --sensitive-data (MCP sensitiveData on fixmap_plan and fixmap_verify) attach lexical source-to-sink flows from the local fixmap-sensitive-data provider that touch the report's ranked, impact or changed paths: file, line, category and rule ids only, never matched values. Verify reconstructs each changed file's pre-change lines from the diff and adds an advisory (info) sensitive-data-flow-introduced finding for flows the diff added, including flows created by a new import. fixmap plan --supply-chain (MCP supplyChain) attaches findings from a validated normalized scanner/SBOM bundle for packages declared in manifests among the report's paths, with tool, database, document fingerprint and bundle SHA-256 provenance. Both are additive report fields checked by validateFixMapReport and listed as previews in the feature catalog. isRepositoryRelativePath and inlineProse moved to shared modules so the new validators and renderers reuse them. Co-Authored-By: Claude Opus 5.5 --- packages/action/dist/index.mjs | 1161 ++++++++++++----- packages/cli/src/cli-runner.ts | 28 +- packages/cli/src/mcp.ts | 40 +- packages/cli/src/repository-source.ts | 8 + packages/cli/src/supply-chain-command.ts | 17 +- packages/cli/test/cli-runner.test.ts | 49 +- packages/cli/test/mcp.test.ts | 73 +- packages/core/src/feature-catalog.ts | 2 + packages/core/src/index.ts | 6 +- packages/core/src/markdown.ts | 5 + packages/core/src/paths.ts | 10 + packages/core/src/plan.ts | 19 +- packages/core/src/report-evidence.ts | 17 +- packages/core/src/report-sensitive-data.ts | 278 ++++ packages/core/src/report-supply-chain.ts | 154 +++ packages/core/src/report.ts | 10 +- packages/core/src/sensitive-data.ts | 121 +- packages/core/src/types.ts | 11 +- packages/core/src/validate.ts | 20 +- packages/core/src/verify.ts | 26 +- .../core/test/report-sensitive-supply.test.ts | 278 ++++ 21 files changed, 1886 insertions(+), 447 deletions(-) create mode 100644 packages/core/src/report-sensitive-data.ts create mode 100644 packages/core/src/report-supply-chain.ts create mode 100644 packages/core/test/report-sensitive-supply.test.ts 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"); + }); +}); From a73939b66fa53df533d62b3d89ddae70aa4b8c4e Mon Sep 17 00:00:00 2001 From: Aryam Goyal Date: Mon, 23 Nov 2026 19:59:26 +0530 Subject: [PATCH 4/5] release: FixMap v0.9.6 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 12 + README.md | 2 +- apps/web/app/changelog/page.tsx | 23 +- apps/web/package.json | 2 +- .../releases/v0.10.0-implementation-ledger.md | 14 +- package-lock.json | 16 +- package.json | 2 +- packages/action/dist/index.mjs | 1191 ++++++++++++----- packages/action/package.json | 4 +- packages/cli/package.json | 4 +- packages/core/package.json | 2 +- server.json | 4 +- 12 files changed, 878 insertions(+), 398 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7be2e5a..c558a15 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,18 @@ Accuracy figures inside a released entry are the numbers measured **at that rele left as written. The current numbers live on the [evidence page](https://fixmap.aryam.me/evidence), which is generated from the recorded results rather than transcribed by hand. +## 0.9.6 - 2026-11-23 + +Every addition in this release is a preview: it works and is tested, but its output and options may change before v0.10.0. + +### Added + +- `fixmap plan --sensitive-data` and `fixmap verify --sensitive-data` (MCP `sensitiveData`) attach possible credential, token, personal-data, or payment source-to-sink flows that touch the report's files. Matched values are never printed, only locations and kinds. Verify adds an advisory when a change introduces a new flow. +- `fixmap plan --supply-chain ` (MCP `supplyChain`) attaches imported scanner or SBOM findings for packages declared in manifests among the report's files, with tool and database provenance. +- `fixmap alternatives` compares 2-20 alternative plans, or saved Plan reports, side by side on the same graph state without picking a winner. MCP: `fixmap_alternatives`. +- MCP `fixmap_capability` can now create, update, and remove product capabilities with the same validation and safe writes as the CLI. +- The GitHub Action accepts `contracts`, `reviewers`, `reviewers-history-authors`, and `architecture-drift` to add contract changes, suggested reviewers (never notified), and architecture drift to its pull request comment, and outputs `breaking-contract-count`. + ## 0.9.5 - 2026-11-22 Every addition in this release is a preview: it works and is tested, but its output and options may change before v0.10.0. diff --git a/README.md b/README.md index 4ba3190..4807c56 100644 --- a/README.md +++ b/README.md @@ -469,7 +469,7 @@ jobs: - uses: actions/checkout@v7 with: fetch-depth: 0 - - uses: aryamthecodebreaker/FixMap@v0.9.5 + - uses: aryamthecodebreaker/FixMap@v0.9.6 with: github-token: ${{ secrets.GITHUB_TOKEN }} ``` diff --git a/apps/web/app/changelog/page.tsx b/apps/web/app/changelog/page.tsx index 8a0b528..667c219 100644 --- a/apps/web/app/changelog/page.tsx +++ b/apps/web/app/changelog/page.tsx @@ -43,10 +43,31 @@ type Release = { }; const releases: Release[] = [ + { + version: "0.9.6", + date: "November 23, 2026", + label: "Latest release", + summary: "Five previews: possible sensitive-data flows and dependency scanner findings in plans, side-by-side plan alternatives, editing product areas from AI agents, and contract, reviewer, and architecture sections on pull requests.", + groups: [ + { + label: "Added", + items: [ + "fixmap plan --sensitive-data shows possible credential, token, personal-data, or payment flows near the files in a plan, without ever printing the values.", + "fixmap plan --supply-chain attaches findings from your dependency scanner for the packages those files use.", + "fixmap alternatives compares several possible plans side by side and states the trade-offs instead of picking a winner.", + "AI agents can create, update, and remove product areas over MCP.", + "The GitHub Action can add contract changes, suggested reviewers, and architecture drift to pull request comments, without notifying anyone." + ] + }, + { + label: "Improved", + items: ["All five are previews: they work and are tested, but may change before v0.10.0."] + } + ] + }, { version: "0.9.5", date: "November 22, 2026", - label: "Latest release", summary: "Six previews: other tools' findings in plans, API contract checks, architecture drift and historical plans, reviewer suggestions, saved outcomes and dossiers, and new GitHub Action sections.", groups: [ { diff --git a/apps/web/package.json b/apps/web/package.json index f379d4d..944cf9c 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -17,7 +17,7 @@ "typecheck": "tsc --noEmit" }, "dependencies": { - "@aryam/fixmap-core": "0.9.5", + "@aryam/fixmap-core": "0.9.6", "@phosphor-icons/react": "^2.1.10", "next": "16.4.6", "react": "19.2.7", diff --git a/docs/releases/v0.10.0-implementation-ledger.md b/docs/releases/v0.10.0-implementation-ledger.md index a0a15ce..cfdd61c 100644 --- a/docs/releases/v0.10.0-implementation-ledger.md +++ b/docs/releases/v0.10.0-implementation-ledger.md @@ -281,21 +281,21 @@ with one existing skip; the rebuilt Action artifact passes its freshness check. | Semantic index provenance | implemented | Local model bundles are fully hashed; runtime, dimensions, normalization, model identity, cache key, indexed/omitted scope, and disabled/failure behavior are recorded. The persistent cache is atomic, model-isolated, corruption-healing, and outside the repository. Candidate-scale performance evidence remains. Candidate-scale evidence 2026-11-22 (scripts/benchmark-semantic.mjs, all-MiniLM-L6-v2, @huggingface/transformers 3.8.1, CPU): 173 embedded files cost a 25.6 s cold first run and 1.7 s warm versus 0.94 s structural-only, with identical warm/cold rankings. A 1,000-candidate cold run exceeds the 120 s budget on CPU, so misses are now embedded in batches of 16 and every finished batch is persisted, letting repeated runs converge to a warm cache. | | Decision-relevant context optimization | planned | Context selection beats or ties the current pack at equal token budgets on frozen tasks without hiding omissions. | | Explicit-anchor change scope | in progress | A browser-safe Core engine and `fixmap change-scope` CLI/`fixmap_change_scope` MCP surfaces now expand caller-supplied touch/add paths through allowlisted import/dependent edges with stable file identities, cycle-safe BFS, mandatory depth/node bounds, and visible unresolved/truncated state. Existing test routes, contracts, ADRs, CODEOWNERS/annotations/history reviewers, and architecture findings join with provenance; unrelated malformed contract/ADR surfaces stay isolated. Markdown/JSON output reports exact declared/observed/derived/unresolved counts and generated outputs are self-excluded. Cross-repository traversal, runtime/CI joins, historical comparison, Action/editor parity, and held-out product-building fixtures remain. No LLM, API, account, or semantic product inference is permitted. 0.9.5 (2026-11-22, PR #687): GitHub Action parity via preview `change-scope-touch`/`change-scope-add` inputs and the `change-scope-affected-count` output. | -| Persistent product capability map | in progress | A strict versioned `.fixmap/capabilities.json` records human-owned capability names, explicit anchors, workspace/repository identity, and traversal bounds; unknown/generated conclusion fields fail validation. CLI create/update/remove uses repository-contained directory checks, a bounded stale lock, atomic temp-file replacement, and symlink/hardlink refusal. CLI and read-only MCP list/show rebuild current evidence with the exact store fingerprint. Core/CLI/MCP exact-ref diff reads immutable Git objects without checkout mutation and compares definition, selected/affected paths, content fingerprints, contracts, decisions, test associations, reviewers, and architecture findings while preserving absent-before state. Rename-aware identity continuity, MCP mutation, cross-repository evidence, Action/editor parity, and held-out fixtures remain. Exact declared/observed/derived/unresolved counts replace undefinable confidence percentages. 0.9.5 (PR #687): GitHub Action parity via the preview `capability` input, including the read-only base-vs-head capability diff. | +| Persistent product capability map | in progress | A strict versioned `.fixmap/capabilities.json` records human-owned capability names, explicit anchors, workspace/repository identity, and traversal bounds; unknown/generated conclusion fields fail validation. CLI create/update/remove uses repository-contained directory checks, a bounded stale lock, atomic temp-file replacement, and symlink/hardlink refusal. CLI and read-only MCP list/show rebuild current evidence with the exact store fingerprint. Core/CLI/MCP exact-ref diff reads immutable Git objects without checkout mutation and compares definition, selected/affected paths, content fingerprints, contracts, decisions, test associations, reviewers, and architecture findings while preserving absent-before state. Rename-aware identity continuity, MCP mutation, cross-repository evidence, Action/editor parity, and held-out fixtures remain. Exact declared/observed/derived/unresolved counts replace undefinable confidence percentages. 0.9.5 (PR #687): GitHub Action parity via the preview `capability` input, including the read-only base-vs-head capability diff. 0.9.6 (PR #696): MCP mutation (create/update/remove on `fixmap_capability`) through the same validated, atomic, lock-guarded CLI path. | ## System intelligence | Capability | Status | Acceptance evidence | | --- | --- | --- | | Cross-repository workspace model | in progress | Multiple checkouts plus Node, Python, and Maven packages, versions, submodules, manifest/import consumers, exact source derivations, stable graph identities, and explicit enrichment nodes/edges form one provenance-preserving graph. The versioned local `fixmap workspace` CLI and `fixmap_workspace` MCP workflows validate 1-32 relative checkouts, reject duplicate real roots and remote paths, scan four repositories concurrently without executing code, and traverse provider-to-consumer impact from repeatable seeds in deterministic Markdown/JSON. Action parity, service/catalog/registry discovery, aliases in config, cross-repository Context/Verify narration, and held-out evidence remain. | -| Contract Guardian | in progress | Core inventories exact-version OpenAPI, AsyncAPI, GraphQL, Protobuf, JSON Schema, and SQL migration surfaces; emits deterministic compatible/breaking/unknown deltas with before/after fingerprints; and converts contracts into hierarchically owned graph nodes. YAML schema details, public-language APIs, known-consumer edges, CLI/MCP/Action parity, and held-out evidence remain. 0.9.5 (PR #691): CLI `fixmap contracts` list/diff over exact refs without checkout, MCP `fixmap_contracts`, and YAML/JSON delta parity, with tests for malformed specs, unknown refs, and unchanged HEAD/status. Action parity and held-out evidence remain. | +| Contract Guardian | in progress | Core inventories exact-version OpenAPI, AsyncAPI, GraphQL, Protobuf, JSON Schema, and SQL migration surfaces; emits deterministic compatible/breaking/unknown deltas with before/after fingerprints; and converts contracts into hierarchically owned graph nodes. YAML schema details, public-language APIs, known-consumer edges, CLI/MCP/Action parity, and held-out evidence remain. 0.9.5 (PR #691): CLI `fixmap contracts` list/diff over exact refs without checkout, MCP `fixmap_contracts`, and YAML/JSON delta parity, with tests for malformed specs, unknown refs, and unchanged HEAD/status. Action parity and held-out evidence remain. 0.9.6 (2026-11-23, PR #695): GitHub Action parity via the preview `contracts` input and `breaking-contract-count` output; held-out evidence remains. | | ADR and rationale ingestion | implemented | Local ADR/PR-export ingestion preserves authored text, original and normalized status, dates, supersession references, exact fingerprints, and explicitly unverified local attribution without fetching. Workspace rationale/mention edges preserve identity and invalidation boundaries. Report, Context, Ask, Verify, change-scope, reverse-docs, and editor consumers retain evidence. Real CLI/Action/MCP parity and edit/exclusion/removal checks pass. Seven development documents across two conventions exposed repaired omissions; two additional same-repository documents passed field checks without parser changes (narrow validation, not broad generalization). Core checkpoint: 812 passed, one skipped. Exact implementation 0a9d6ab passes CI 34805930550 with four rationale process checks and external evaluation 34805930587. See docs/releases/decisions-acceptance.md. | | `fixmap annotate` | implemented | Durable Core/CLI/MCP/Action add/list/remove, declared file/symbol/service/contract scopes, owner/expiry, contained targets, atomic locking, and relevant Markdown/JSON/agent evidence are implemented. Real Git rename warnings preserve authored scope; bounded named-scope matching avoids substring pollution. The final focused sweep passes 36 tests across eight files. Packed cross-process lock/removal checks passed all four CI compatibility environments. Three pinned external workflows pass Core/CLI/Action and two separately frozen held-out JS/Python workflows pass Core/CLI/Action/MCP, including exact provenance and removal freshness. See `docs/releases/annotations-acceptance.md` and `docs/annotations.md` for evidence and explicit ownership/identity limits. Broader reviewer routing and enterprise authentication remain separate capabilities; final candidate-wide release gates still apply. | | Architecture policy | in progress | A bounded, versioned `.fixmap/policy.json` now enforces dependency boundaries, required test changes, required reviewers, and caller-supplied breaking-contract comparisons with exact policy provenance. Plan and Verify share the evaluator, machine-readable finding codes, Markdown/agent output, and evidence-backed Verify narration; contract baseline wiring, CLI authoring help, and held-out evidence remain. | -| Architecture drift | in progress | Core builds deterministic, exact-source architecture snapshots and compares added/removed import edges, cyclic components, boundary violations, and coupling growth. Historical-ref CLI integration, ADR disagreement, snapshot persistence, and held-out evidence remain. 0.9.5 (PR #690): historical-ref CLI integration and ADR disagreement reporting implemented, with per-commit snapshot caching; held-out evidence remains. | +| Architecture drift | in progress | Core builds deterministic, exact-source architecture snapshots and compares added/removed import edges, cyclic components, boundary violations, and coupling growth. Historical-ref CLI integration, ADR disagreement, snapshot persistence, and held-out evidence remain. 0.9.5 (PR #690): historical-ref CLI integration and ADR disagreement reporting implemented, with per-commit snapshot caching; held-out evidence remains. 0.9.6 (PR #695): GitHub Action parity via the preview `architecture-drift` input. | | Time-travel graph | in progress | Core resolves historical refs to immutable commit IDs, reads bounded exact Git blobs without checkout/worktree mutation, builds deterministic architecture snapshots, and compares two refs for drift. The `fixmap history` CLI and `fixmap_history` MCP tool now expose Markdown/JSON comparisons with both commit IDs, snapshot fingerprints, added/removed edges, new/resolved cycles and policy violations, and coupling growth. Argument bounds fail before Git, failures do not leak child commands, and integration tests prove HEAD/status remain unchanged. Historical Plan queries, snapshot caching, odd-path held-out fixtures, Action/editor parity, and performance evidence remain. 0.9.5 (PR #690): historical Plan queries (`fixmap plan --at `) and snapshot caching implemented; Action/editor parity and performance evidence remain. | -| Sensitive-data flow evidence | in progress | The built-in local `fixmap-sensitive-data` evidence provider emits bounded credential/token/PII/payment source indicators, logging/network/storage/analytics sink indicators, and same-file or direct-import structural relationships. Every file item is low confidence, carries exact content fingerprint, detector version and rule IDs, omits matched values/snippets, and declares that it is not a taint or complete security proof. Plan/Verify surfacing, language-aware flow refinement, adversarial evaluation, and SARIF remain. | -| Supply-chain evidence | in progress | Core validates a bounded version-1 normalized bundle of packages plus vulnerability, outdated-version, and license-policy findings; preserves external tool, tool/database version, timestamp, document SHA-256, confidence, advisory/fix/license provenance; and converts it to package-aware evidence relationships. The `fixmap supply-chain` CLI and `fixmap_supply_chain` MCP tool accept a versioned object/file, produce deterministic Markdown/JSON, reject traversal/unsafe URLs/input-output collisions, and explicitly state external-evidence-only, no FixMap vulnerability corpus/scanner execution/remediation authorization. CycloneDX/SPDX/OSV/Trivy adapters, signature/attestation verification, policy gates, Action/editor parity, and held-out evidence remain. | +| Sensitive-data flow evidence | in progress | The built-in local `fixmap-sensitive-data` evidence provider emits bounded credential/token/PII/payment source indicators, logging/network/storage/analytics sink indicators, and same-file or direct-import structural relationships. Every file item is low confidence, carries exact content fingerprint, detector version and rule IDs, omits matched values/snippets, and declares that it is not a taint or complete security proof. Plan/Verify surfacing, language-aware flow refinement, adversarial evaluation, and SARIF remain. 0.9.6 (PR #697): Plan and Verify surfacing (`--sensitive-data`, MCP `sensitiveData`), including a Verify advisory for newly introduced flows and no matched values in any output; language-aware refinement, adversarial evaluation, and SARIF remain. | +| Supply-chain evidence | in progress | Core validates a bounded version-1 normalized bundle of packages plus vulnerability, outdated-version, and license-policy findings; preserves external tool, tool/database version, timestamp, document SHA-256, confidence, advisory/fix/license provenance; and converts it to package-aware evidence relationships. The `fixmap supply-chain` CLI and `fixmap_supply_chain` MCP tool accept a versioned object/file, produce deterministic Markdown/JSON, reject traversal/unsafe URLs/input-output collisions, and explicitly state external-evidence-only, no FixMap vulnerability corpus/scanner execution/remediation authorization. CycloneDX/SPDX/OSV/Trivy adapters, signature/attestation verification, policy gates, Action/editor parity, and held-out evidence remain. 0.9.6 (PR #697): Plan surfacing via `fixmap plan --supply-chain` and MCP `supplyChain` with tool/database provenance. | ## Change intelligence @@ -304,10 +304,10 @@ with one existing skip; the rebuilt Action artifact passes its freshness check. | Impact-narrated Verify | in progress | Verify now emits a bounded plain-English narrative whose every statement is labeled observation or inference and retains machine-readable changed-file, import/co-change/test-route, risk-rule, annotation, ADR, or architecture-policy evidence with source fingerprints where applicable. CLI/MCP/Action snapshots, narrative quality evaluation, and reviewer-facing polish remain. | | Multi-agent conflict detection | in progress | Core compares up to 100 versioned change intents across explicit intended-edit, impact, and contract graph-identity zones; emits edit/edit errors, directional edit/impact and contract warnings, stale-baseline evidence, stable IDs, and deterministic ordering. Matching labels never imply identity; only reviewed alias/equivalence graph edges canonicalize zones, and unrelated work is not locked. CLI/MCP coordination transport, live intent lifecycle, symbol-range refinement, and held-out concurrency evidence remain. | | Migration planner | in progress | Core validates up to 500 explicit steps against one exact identity-graph fingerprint, topologically builds deterministic phases, and includes prerequisites, required compatibility strategy/exit criteria, verification commands/reasons, rollback triggers/actions, and edit/impact/contract blast radius. The `fixmap migrate` CLI and `fixmap_migrate` MCP tool accept a versioned local object/file, render deterministic Markdown/JSON, reject input/output collisions, never execute, and fail closed on cycles, missing identities, incomplete safety fields, and undeclared parallel edit/contract overlap. Report-to-step derivation, runtime gates, Action/editor parity, and held-out migrations remain. | -| Alternative-plan comparison | in progress | Core validates 2-20 alternatives on the same exact graph fingerprint and compares intended edits, impact/contract/unique blast radius, compatible/breaking/unknown contracts, policy errors/warnings, planned tests and edit coverage, reversibility evidence, and high/medium uncertainty. It retains axis evidence and a Pareto-style non-dominated frontier without inventing a winner or scalar score. Report adapters, Markdown/CLI/MCP rendering, cost/time evidence, and held-out decision-quality evaluation remain. | +| Alternative-plan comparison | in progress | Core validates 2-20 alternatives on the same exact graph fingerprint and compares intended edits, impact/contract/unique blast radius, compatible/breaking/unknown contracts, policy errors/warnings, planned tests and edit coverage, reversibility evidence, and high/medium uncertainty. It retains axis evidence and a Pareto-style non-dominated frontier without inventing a winner or scalar score. Report adapters, Markdown/CLI/MCP rendering, cost/time evidence, and held-out decision-quality evaluation remain. 0.9.6 (PR #696): report adapter from saved Plan reports, Markdown rendering, CLI `fixmap alternatives`, and read-only MCP `fixmap_alternatives`; cost/time evidence and held-out decision-quality evaluation remain. | | Outcome feedback loop | in progress | Core owns versioned, validated, removable outcome records that keep predicted paths, actual edits, command pass/fail/timeout/crash/unavailable evidence, and human/agent/external/unassessed task assessment separate. Calibration exposes correct predictions, false positives, misses, micro precision/recall, test and assessment counts, per-record evidence, and `automaticWeightChanges: false`. Atomic local persistence, CLI capture/removal, privacy/retention controls, longitudinal cohorts, and reviewed weight experiments remain. 0.9.5 (PR #688): atomic local persistence under `.fixmap/outcomes/`, CLI record/list/show/remove/calibrate/prune, `--redact`, and read-only MCP `fixmap_outcomes`; longitudinal cohorts and reviewed weight experiments remain. | | Change dossier | in progress | Core builds and validates a deterministic version-1 dossier linking request provenance, evidence-status assumptions, exact plan/graph references, ADR references, nullable diff state, command outcomes, observation/inference runtime evidence, reviews, and optional commit/PR/deployment/version identifiers. Confirmed/rejected assumptions and completed tests require evidence fingerprints; timestamps/paths are normalized; content mismatch fails fingerprint validation. Atomic local persistence, CLI lifecycle commands, external signatures/attestations, redaction, and cross-interface rendering remain. 0.9.5 (PR #688): atomic local persistence under `.fixmap/dossiers/`, CLI create/list/show/remove, `--redact`, and read-only MCP `fixmap_dossier`; external signatures and cross-interface rendering remain. | -| Ownership and review routing | in progress | Core combines the highest-precedence CODEOWNERS file with last-rule-wins matching, active annotation owners, architecture-policy reviewers, and up to 250 bounded non-merge commits with recorded author names. Suggestions retain exact source/commit fingerprints, paths and CODEOWNERS lines, confidence, diagnostics, and `availabilityInferred: false`; matching names are not treated as identity or employment evidence. CLI/MCP/Action surfaces, mailmap/team identity integration, blame-at-symbol granularity, privacy controls, and held-out routing quality remain. 0.9.5 (PR #689): CLI `fixmap reviewers`, MCP `fixmap_reviewers`, `.mailmap` canonicalization, `--no-history-authors`, and mention-free output; Action parity, blame-at-symbol granularity, and held-out routing quality remain. | +| Ownership and review routing | in progress | Core combines the highest-precedence CODEOWNERS file with last-rule-wins matching, active annotation owners, architecture-policy reviewers, and up to 250 bounded non-merge commits with recorded author names. Suggestions retain exact source/commit fingerprints, paths and CODEOWNERS lines, confidence, diagnostics, and `availabilityInferred: false`; matching names are not treated as identity or employment evidence. CLI/MCP/Action surfaces, mailmap/team identity integration, blame-at-symbol granularity, privacy controls, and held-out routing quality remain. 0.9.5 (PR #689): CLI `fixmap reviewers`, MCP `fixmap_reviewers`, `.mailmap` canonicalization, `--no-history-authors`, and mention-free output; Action parity, blame-at-symbol granularity, and held-out routing quality remain. 0.9.6 (PR #695): GitHub Action parity via preview `reviewers` and `reviewers-history-authors` inputs with mention-free output. | ## Runtime proof diff --git a/package-lock.json b/package-lock.json index d6d3c2b..1a87dd1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "fixmap-workspace", - "version": "0.9.5", + "version": "0.9.6", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "fixmap-workspace", - "version": "0.9.5", + "version": "0.9.6", "license": "MIT", "workspaces": [ "packages/*", @@ -30,7 +30,7 @@ "name": "@fixmap/web", "version": "0.0.0", "dependencies": { - "@aryam/fixmap-core": "0.9.5", + "@aryam/fixmap-core": "0.9.6", "@phosphor-icons/react": "^2.1.10", "next": "16.4.6", "react": "19.2.7", @@ -8944,18 +8944,18 @@ }, "packages/action": { "name": "@fixmap/action", - "version": "0.9.5", + "version": "0.9.6", "license": "MIT", "dependencies": { - "@aryam/fixmap-core": "0.9.5" + "@aryam/fixmap-core": "0.9.6" } }, "packages/cli": { "name": "@aryam/fixmap", - "version": "0.9.5", + "version": "0.9.6", "license": "MIT", "dependencies": { - "@aryam/fixmap-core": "0.9.5", + "@aryam/fixmap-core": "0.9.6", "@modelcontextprotocol/sdk": "1.32.0" }, "bin": { @@ -8967,7 +8967,7 @@ }, "packages/core": { "name": "@aryam/fixmap-core", - "version": "0.9.5", + "version": "0.9.6", "license": "MIT", "devDependencies": {}, "engines": { diff --git a/package.json b/package.json index fba022b..27b9216 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "fixmap-workspace", - "version": "0.9.5", + "version": "0.9.6", "private": true, "description": "Local-first repo intelligence for coding agents: ranked context, likely impact, test routes, risks, and repository benchmarks.", "license": "MIT", diff --git a/packages/action/dist/index.mjs b/packages/action/dist/index.mjs index 4cda395..926d4ab 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 = { @@ -5184,12 +5617,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; } @@ -5274,7 +5707,7 @@ function repoSourceFingerprint(repo) { return `repository:${stableHash3(sources.join("\0"))}`; } function mapDifference(left, right) { - return [...left].flatMap(([key, value]) => right.has(key) ? [] : [value]); + return [...left].flatMap(([key2, value]) => right.has(key2) ? [] : [value]); } function edgeKey(edge) { return `${edge.from}\0${edge.to}`; @@ -5307,14 +5740,14 @@ 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); } function canonicalize2(value) { if (Array.isArray(value)) return `[${value.map(canonicalize2).join(",")}]`; if (value && typeof value === "object") - return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, entry2]) => `${JSON.stringify(key)}:${canonicalize2(entry2)}`).join(",")}}`; + return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key2, entry2]) => `${JSON.stringify(key2)}:${canonicalize2(entry2)}`).join(",")}}`; return JSON.stringify(value); } function stableHash3(value) { @@ -5907,6 +6340,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", @@ -5951,9 +6386,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"]; } @@ -6232,7 +6664,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); @@ -6243,32 +6675,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) { @@ -6713,7 +7145,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, @@ -6728,10 +7160,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; @@ -6755,7 +7187,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")); @@ -7070,7 +7502,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) @@ -7099,13 +7531,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" }; } @@ -7342,13 +7774,13 @@ async function pruneArchitectureCache(directory) { } } function isArchitectureEntry(value) { - if (!isRecord6(value) || !isRecord6(value.snapshot) || !Array.isArray(value.decisionRules) || !Array.isArray(value.decisionDiagnostics)) + if (!isRecord8(value) || !isRecord8(value.snapshot) || !Array.isArray(value.decisionRules) || !Array.isArray(value.decisionDiagnostics)) return false; const snapshot = value.snapshot; - const edge = (entry2) => isRecord6(entry2) && typeof entry2.from === "string" && typeof entry2.to === "string"; - return snapshot.architectureSnapshotVersion === 1 && typeof snapshot.fingerprint === "string" && typeof snapshot.sourceFingerprint === "string" && Array.isArray(snapshot.edges) && snapshot.edges.every(edge) && Array.isArray(snapshot.cycles) && snapshot.cycles.every((cycle) => Array.isArray(cycle) && cycle.every((path) => typeof path === "string")) && Array.isArray(snapshot.coupling) && Array.isArray(snapshot.boundaryViolations) && isRecord6(snapshot.truncated) && value.decisionRules.every((rule) => isRecord6(rule) && ["decisionId", "decisionPath", "decisionTitle", "from", "deny"].every((key) => typeof rule[key] === "string")); + const edge = (entry2) => isRecord8(entry2) && typeof entry2.from === "string" && typeof entry2.to === "string"; + return snapshot.architectureSnapshotVersion === 1 && typeof snapshot.fingerprint === "string" && typeof snapshot.sourceFingerprint === "string" && Array.isArray(snapshot.edges) && snapshot.edges.every(edge) && Array.isArray(snapshot.cycles) && snapshot.cycles.every((cycle) => Array.isArray(cycle) && cycle.every((path) => typeof path === "string")) && Array.isArray(snapshot.coupling) && Array.isArray(snapshot.boundaryViolations) && isRecord8(snapshot.truncated) && value.decisionRules.every((rule) => isRecord8(rule) && ["decisionId", "decisionPath", "decisionTitle", "from", "deny"].every((key2) => typeof rule[key2] === "string")); } -function isRecord6(value) { +function isRecord8(value) { return typeof value === "object" && value !== null && !Array.isArray(value); } function checksum(value) { @@ -7362,7 +7794,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({ @@ -7520,7 +7952,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) { @@ -7534,12 +7966,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. */ @@ -7581,25 +8013,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 { @@ -7609,7 +8041,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); } }); @@ -7727,7 +8159,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; @@ -7759,7 +8191,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`; @@ -7776,7 +8208,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`; @@ -7789,7 +8221,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; @@ -7809,9 +8241,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)); @@ -7847,7 +8279,7 @@ function withTimeout(promise, timeoutMs, controller) { }); }); } -function isRecord7(candidate) { +function isRecord9(candidate) { return typeof candidate === "object" && candidate !== null && !Array.isArray(candidate); } @@ -7855,12 +8287,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, @@ -7875,6 +8303,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) { @@ -7907,6 +8342,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, @@ -8021,7 +8462,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])); @@ -8163,13 +8604,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) { @@ -8314,6 +8760,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")} `; } @@ -8734,23 +9182,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; @@ -8758,12 +9206,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) @@ -8783,8 +9231,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 = []; @@ -8816,21 +9264,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); @@ -8838,24 +9286,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; @@ -8875,43 +9323,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()); @@ -8938,10 +9386,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 = ""; @@ -8961,8 +9409,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)) @@ -8977,15 +9425,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; } @@ -8994,12 +9442,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) @@ -9010,11 +9458,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; @@ -9093,19 +9541,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]; @@ -9210,8 +9658,8 @@ function compareContractInventories(previous, current2) { function compareSurface(before, after, changes) { const beforeEntries = new Map(before.entries.map((entry2) => [entry2.key, entry2])); const afterEntries = new Map(after.entries.map((entry2) => [entry2.key, entry2])); - for (const [key, entry2] of beforeEntries) { - const current2 = afterEntries.get(key); + for (const [key2, entry2] of beforeEntries) { + const current2 = afterEntries.get(key2); if (!current2) { changes.push(contractChange(before, after, "entry-removed", removalCompatibility(entry2), `Removed ${describeEntry(entry2)}.`, entry2)); } else if (entry2.signature !== current2.signature || entry2.required !== current2.required) { @@ -9220,8 +9668,8 @@ function compareSurface(before, after, changes) { changes.push(contractChange(before, after, "entry-changed", compatibility, `${describeEntry(entry2)} changed ${detail}.`, current2, entry2.signature, current2.signature)); } } - for (const [key, entry2] of afterEntries) { - if (beforeEntries.has(key)) + for (const [key2, entry2] of afterEntries) { + if (beforeEntries.has(key2)) continue; const compatibility = additionCompatibility(entry2); changes.push(contractChange(before, after, "entry-added", compatibility, additionReason(entry2), entry2)); @@ -9229,9 +9677,9 @@ function compareSurface(before, after, changes) { } function contractChange(before, after, change, compatibility, reason2, entry2, beforeSignature, afterSignature) { const surface = after ?? before; - const key = `${surface.id}\0${change}\0${entry2?.key ?? ""}\0${beforeSignature ?? ""}\0${afterSignature ?? ""}`; + const key2 = `${surface.id}\0${change}\0${entry2?.key ?? ""}\0${beforeSignature ?? ""}\0${afterSignature ?? ""}`; return { - id: `contract-change:${stableHash4(key)}`, + id: `contract-change:${stableHash4(key2)}`, contractId: surface.id, contractKind: surface.kind, path: surface.path, @@ -9300,13 +9748,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) @@ -9332,7 +9780,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 } : {} @@ -9403,7 +9851,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}`)); } @@ -9503,8 +9951,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(); @@ -9560,17 +10008,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 severityOrder2(value) { @@ -9848,7 +10296,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 { @@ -9857,7 +10305,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)) @@ -9900,7 +10348,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"; }); @@ -9912,7 +10360,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"; }); @@ -9924,14 +10372,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}.` }; @@ -9940,12 +10388,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.` }; @@ -9957,24 +10405,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] }); @@ -9991,12 +10445,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); @@ -10010,13 +10464,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}.` }; @@ -10024,7 +10478,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); }); @@ -10036,21 +10490,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, @@ -10059,15 +10513,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)) { @@ -10079,7 +10533,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) { @@ -10088,13 +10542,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); } @@ -10102,7 +10549,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)) @@ -10114,7 +10561,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; } @@ -10131,7 +10578,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"); @@ -10196,7 +10643,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)) { @@ -10211,10 +10658,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 { @@ -10225,7 +10672,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") { @@ -10237,7 +10684,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; @@ -10272,11 +10719,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); } @@ -10360,15 +10807,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; } @@ -10388,7 +10835,7 @@ function canonicalize3(value) { if (Array.isArray(value)) return `[${value.map(canonicalize3).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)}:${canonicalize3(entry2)}`).join(",")}}`; + return `{${Object.entries(value).filter(([, entry2]) => entry2 !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([key2, entry2]) => `${JSON.stringify(key2)}:${canonicalize3(entry2)}`).join(",")}}`; } return JSON.stringify(value); } @@ -10480,7 +10927,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."); @@ -10499,7 +10946,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({ @@ -10799,7 +11246,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], @@ -10808,7 +11255,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}`); } @@ -10842,8 +11289,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}.`; } @@ -10927,16 +11374,16 @@ async function buildReviewSections(request, context) { var COMPATIBILITY_ORDER = { breaking: 0, unknown: 1, compatible: 2 }; function renderContractSection(result) { const { changes } = result.comparison; - const count = (compatibility) => changes.filter((change) => change.compatibility === compatibility).length; + const count2 = (compatibility) => changes.filter((change) => change.compatibility === compatibility).length; const lines = [ "## Contract changes (preview)", "", // Reasons quote contract text, where a GraphQL directive such as `@deprecated` would mention someone. withoutMentions(result.comparison.summary), "", - `- Breaking: ${count("breaking").toLocaleString()}`, - `- Unknown: ${count("unknown").toLocaleString()}`, - `- Compatible: ${count("compatible").toLocaleString()}`, + `- Breaking: ${count2("breaking").toLocaleString()}`, + `- Unknown: ${count2("unknown").toLocaleString()}`, + `- Compatible: ${count2("compatible").toLocaleString()}`, "" ]; if (changes.length > 0) { @@ -11173,7 +11620,7 @@ function readReviewSectionRequest(env) { async function runAction(env = process.env, dependencies = {}) { const appendFile = dependencies.appendFile ?? ((path, contents) => appendFileSync(path, contents)); const readFile5 = 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)); incompatible.push(...readReviewSectionRequest(env).used); @@ -11506,9 +11953,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/action/package.json b/packages/action/package.json index e947280..846fea0 100644 --- a/packages/action/package.json +++ b/packages/action/package.json @@ -1,6 +1,6 @@ { "name": "@fixmap/action", - "version": "0.9.5", + "version": "0.9.6", "description": "GitHub Action wrapper for FixMap pull request reports.", "private": true, "license": "MIT", @@ -11,6 +11,6 @@ "typecheck": "tsc -p tsconfig.json --noEmit" }, "dependencies": { - "@aryam/fixmap-core": "0.9.5" + "@aryam/fixmap-core": "0.9.6" } } diff --git a/packages/cli/package.json b/packages/cli/package.json index 2905c1a..bdc23e7 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@aryam/fixmap", - "version": "0.9.5", + "version": "0.9.6", "mcpName": "io.github.aryamthecodebreaker/fixmap", "description": "Local-first CLI and MCP server mapping tasks and diffs to ranked context, likely impact, tests, and risks.", "license": "MIT", @@ -46,7 +46,7 @@ "typecheck": "tsc -p tsconfig.json --noEmit" }, "dependencies": { - "@aryam/fixmap-core": "0.9.5", + "@aryam/fixmap-core": "0.9.6", "@modelcontextprotocol/sdk": "1.32.0" }, "engines": { diff --git a/packages/core/package.json b/packages/core/package.json index 0b272f3..58b333a 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@aryam/fixmap-core", - "version": "0.9.5", + "version": "0.9.6", "description": "Deterministic local-first repository scanner, context ranker, Impact Graph, and report renderer for coding agents.", "license": "MIT", "repository": { diff --git a/server.json b/server.json index ffa88c0..0670ff1 100644 --- a/server.json +++ b/server.json @@ -6,12 +6,12 @@ "url": "https://github.com/aryamthecodebreaker/FixMap", "source": "github" }, - "version": "0.9.5", + "version": "0.9.6", "packages": [ { "registryType": "npm", "identifier": "@aryam/fixmap", - "version": "0.9.5", + "version": "0.9.6", "transport": { "type": "stdio" }, From beaeaccaa906879ec44ddc0836cbbcfa3445b630 Mon Sep 17 00:00:00 2001 From: Aryam Goyal Date: Mon, 23 Nov 2026 20:02:12 +0530 Subject: [PATCH 5/5] fix: handle git exiting before cat-file reads every object id An unknown ref or the output cap could close git's stdin while the id list was still being written, raising an unhandled EPIPE (seen as a flaky contracts-repository failure in CI). The exit code already reports it. Co-Authored-By: Claude Opus 5.5 --- packages/action/dist/index.mjs | 1 + packages/core/src/architecture-history.ts | 2 ++ packages/core/test/architecture-history.test.ts | 15 ++++++++++++++- 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/packages/action/dist/index.mjs b/packages/action/dist/index.mjs index 926d4ab..1134f36 100644 --- a/packages/action/dist/index.mjs +++ b/packages/action/dist/index.mjs @@ -7856,6 +7856,7 @@ async function readBlobs(repoRoot, entries) { stdout.push(chunk); }); child.stderr.on("data", (chunk) => stderr.push(chunk)); + child.stdin.on("error", () => void 0); child.stdin.end(`${uniqueOids.join("\n")} `); const exitCode = await new Promise((resolveExit, reject) => { diff --git a/packages/core/src/architecture-history.ts b/packages/core/src/architecture-history.ts index 77e7360..7686b2f 100644 --- a/packages/core/src/architecture-history.ts +++ b/packages/core/src/architecture-history.ts @@ -365,6 +365,8 @@ export async function readBlobs(repoRoot: string, entries: readonly TreeEntry[]) else stdout.push(chunk); }); child.stderr.on("data", (chunk: Buffer) => stderr.push(chunk)); + // git can exit before reading every id (not a repository, or killed at the output cap); the exit code reports that. + child.stdin.on("error", () => undefined); child.stdin.end(`${uniqueOids.join("\n")}\n`); const exitCode = await new Promise((resolveExit, reject) => { child.once("error", reject); diff --git a/packages/core/test/architecture-history.test.ts b/packages/core/test/architecture-history.test.ts index 01aa357..b98e0b4 100644 --- a/packages/core/test/architecture-history.test.ts +++ b/packages/core/test/architecture-history.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { promisify } from "node:util"; import { afterEach, describe, expect, it } from "vitest"; -import { buildArchitectureSnapshotAtRef, compareArchitectureRefs, scanRepoAtRef } from "../src/architecture-history.js"; +import { buildArchitectureSnapshotAtRef, compareArchitectureRefs, readBlobs, scanRepoAtRef } from "../src/architecture-history.js"; const exec = promisify(execFile); const HISTORICAL_GIT_TEST_TIMEOUT = process.platform === "win32" ? 30_000 : 15_000; @@ -38,6 +38,19 @@ async function fixture(): Promise<{ root: string; before: string; after: string } describe("historical architecture", () => { + it("reports a git failure instead of crashing when git exits before reading every object id", async () => { + const root = await mkdtemp(join(tmpdir(), "fixmap-not-a-repo-")); + roots.push(root); + // More ids than a pipe buffer holds, so the write is still pending when git exits outside a repository. + const entries = Array.from({ length: 20_000 }, (_, index) => ({ + mode: "100644", + oid: index.toString(16).padStart(40, "0"), + size: 1, + path: `f${index}.ts` + })); + await expect(readBlobs(root, entries)).rejects.toThrow(/git cat-file failed/); + }, HISTORICAL_GIT_TEST_TIMEOUT); + it("reads exact blob identities at a ref without moving HEAD or changing the worktree", async () => { const { root, before, after } = await fixture(); const headBefore = (await exec("git", ["rev-parse", "HEAD"], { cwd: root })).stdout.trim();