@mitre/hdf-diff 3.7.1-rc.1 → 3.7.2-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["canonicalEffectiveStatus","extractCcis","extractCwes","extractGtitle","safeTitle","validatorsValidateComparison","parseCvssVector","parseCvssVectorUtil","formatFieldChanges"],"sources":["../src/status.ts","../src/summary.ts","../src/normalize.ts","../src/matching/exact-id.ts","../src/matching/mapped-id.ts","../src/matching/cci-match.ts","../src/matching/fuzzy-match.ts","../src/matching/srg-deterministic.ts","../src/matching/srg-cci-tiebreak.ts","../src/matching/vendor-fuzzy-title.ts","../src/matching/index.ts","../src/validate.ts","../src/diff.ts","../src/effective-checksum.ts","../src/change-event.ts","../src/event-stream-common.ts","../src/apply-events.ts","../src/fold-events.ts","../src/exit-codes.ts","../src/renderers/filter.ts","../src/renderers/json.ts","../src/renderers/markdown.ts","../src/renderers/terminal.ts","../src/renderers/csv.ts","../src/renderers/index.ts","../src/sbom.ts"],"sourcesContent":["import { computeEffectiveStatus as canonicalEffectiveStatus, parseTimestamp } from '@mitre/hdf-utilities';\nimport type { ChangeReason, RequirementState } from './types.js';\n\n/** Statuses that count as \"passing\" for fixed/regressed classification */\nconst PASSING_STATUSES = new Set(['passed']);\n\n/** Statuses that count as \"failing\" for fixed/regressed classification */\nconst FAILING_STATUSES = new Set(['failed', 'error', 'notReviewed']);\n\ninterface ResultLike {\n status: string;\n}\n\ninterface OverrideLike {\n status?: string;\n appliedAt?: string;\n expiresAt: string;\n}\n\n/**\n * Determine the effective status of a requirement from its results and\n * overrides, delegating to the canonical shared implementation in\n * `@mitre/hdf-utilities` (see status-determination.md):\n *\n * 1. the governing (most recent non-expired) status override's status\n * 2. else result roll-up error → error\n * 3. else impact === 0 → notApplicable\n * 4. else worst-wins roll-up of the results (empty → notReviewed)\n *\n * The stored effectiveStatus field is an output cache and is never read.\n */\nexport function computeEffectiveStatus(\n requirement: Record<string, unknown>,\n referenceTimestamp?: string,\n): string {\n const results = (requirement['results'] as ResultLike[] | undefined) ?? [];\n const overrides = (requirement['statusOverrides'] as OverrideLike[] | undefined) ?? [];\n return canonicalEffectiveStatus(\n {\n // A missing impact must not read as 0 (which would force notApplicable).\n impact: (requirement['impact'] as number | undefined) ?? Number.NaN,\n resultStatuses: results.map((r) => r.status),\n overrides: overrides.map((o) => ({\n status: o.status,\n appliedAt: o.appliedAt,\n expiresAt: o.expiresAt,\n })),\n },\n referenceTimestamp,\n );\n}\n\n/**\n * Classify why the status changed between two requirements.\n * Returns an array of change reasons (a status change can have multiple causes).\n */\nexport function classifyChangeReasons(\n oldReq: Record<string, unknown>,\n newReq: Record<string, unknown>,\n oldTimestamp?: string,\n newTimestamp?: string,\n): ChangeReason[] {\n const reasons: ChangeReason[] = [];\n\n // Check result status changes\n const oldResults = (oldReq['results'] as ResultLike[] | undefined) ?? [];\n const newResults = (newReq['results'] as ResultLike[] | undefined) ?? [];\n const oldResultStatuses = oldResults.map((r) => r.status).sort();\n const newResultStatuses = newResults.map((r) => r.status).sort();\n if (JSON.stringify(oldResultStatuses) !== JSON.stringify(newResultStatuses)) {\n reasons.push('resultChanged');\n }\n\n // Check override changes\n const oldOverrides = (oldReq['statusOverrides'] as OverrideLike[] | undefined) ?? [];\n const newOverrides = (newReq['statusOverrides'] as OverrideLike[] | undefined) ?? [];\n\n if (newOverrides.length > oldOverrides.length) {\n reasons.push('overrideAdded');\n } else if (newOverrides.length < oldOverrides.length) {\n reasons.push('overrideRemoved');\n }\n\n // Check for override expiration between scans. parseTimestamp keeps\n // zone-less scan timestamps host-independent (repo timestamp convention);\n // null means unparseable, so the check is skipped.\n if (oldTimestamp && newTimestamp && oldOverrides.length > 0) {\n const oldTime = parseTimestamp(oldTimestamp)?.getTime();\n const newTime = parseTimestamp(newTimestamp)?.getTime();\n if (oldTime !== undefined && newTime !== undefined) {\n for (const override of oldOverrides) {\n const expiresAt = parseTimestamp(override.expiresAt)?.getTime();\n if (expiresAt !== undefined && expiresAt > oldTime && expiresAt <= newTime) {\n reasons.push('overrideExpired');\n break; // Only report once\n }\n }\n }\n }\n\n // Check impact changes\n const oldImpact = oldReq['impact'] as number | undefined;\n const newImpact = newReq['impact'] as number | undefined;\n if (oldImpact !== newImpact) {\n reasons.push('impactChanged');\n }\n\n // Check disposition changes\n const oldDisposition = oldReq['disposition'] as string | undefined;\n const newDisposition = newReq['disposition'] as string | undefined;\n if (oldDisposition !== newDisposition) {\n reasons.push('dispositionChanged');\n }\n\n // Check effectiveImpact changes\n const oldEffectiveImpact = oldReq['effectiveImpact'] as number | undefined;\n const newEffectiveImpact = newReq['effectiveImpact'] as number | undefined;\n if (oldEffectiveImpact !== newEffectiveImpact) {\n reasons.push('effectiveImpactChanged');\n }\n\n // Check baseline metadata changes (tags, descriptions, title)\n const oldTags = JSON.stringify(oldReq['tags'] ?? {});\n const newTags = JSON.stringify(newReq['tags'] ?? {});\n const oldDescs = JSON.stringify(oldReq['descriptions'] ?? []);\n const newDescs = JSON.stringify(newReq['descriptions'] ?? []);\n const oldTitle = oldReq['title'] as string | undefined;\n const newTitle = newReq['title'] as string | undefined;\n\n if (oldTags !== newTags || oldDescs !== newDescs || oldTitle !== newTitle) {\n reasons.push('metadataChanged');\n }\n\n return reasons;\n}\n\n/**\n * Classify the overall diff status based on old and new effective statuses.\n *\n * - If old is failing and new is passing → 'fixed'\n * - If old is passing and new is failing → 'regressed'\n * - If statuses are equal → 'unchanged'\n * - Otherwise → 'updated'\n */\nexport function classifyDiffStatus(\n oldEffectiveStatus: string,\n newEffectiveStatus: string,\n): RequirementState {\n if (oldEffectiveStatus === newEffectiveStatus) {\n return 'unchanged';\n }\n\n const oldIsFailing = FAILING_STATUSES.has(oldEffectiveStatus);\n const newIsPassing = PASSING_STATUSES.has(newEffectiveStatus);\n const oldIsPassing = PASSING_STATUSES.has(oldEffectiveStatus);\n const newIsFailing = FAILING_STATUSES.has(newEffectiveStatus);\n\n if (oldIsFailing && newIsPassing) {\n return 'fixed';\n }\n if (oldIsPassing && newIsFailing) {\n return 'regressed';\n }\n\n return 'updated';\n}\n","import type { ComparisonSummary, RequirementDiff } from './types.js';\n\n/**\n * Compute summary counts from an array of RequirementDiff entries.\n */\nexport function computeSummary(requirements: RequirementDiff[]): ComparisonSummary {\n const summary: ComparisonSummary = {\n fixed: 0,\n regressed: 0,\n new: 0,\n absent: 0,\n unchanged: 0,\n updated: 0,\n total: requirements.length,\n matchedCount: 0,\n unmatchedOldCount: 0,\n unmatchedNewCount: 0,\n };\n\n for (const req of requirements) {\n switch (req.state) {\n case 'fixed':\n summary.fixed++;\n summary.matchedCount++;\n break;\n case 'regressed':\n summary.regressed++;\n summary.matchedCount++;\n break;\n case 'new':\n summary.new++;\n summary.unmatchedNewCount++;\n break;\n case 'absent':\n summary.absent++;\n summary.unmatchedOldCount++;\n break;\n case 'unchanged':\n summary.unchanged++;\n summary.matchedCount++;\n break;\n case 'updated':\n summary.updated++;\n summary.matchedCount++;\n break;\n }\n }\n\n return summary;\n}\n","/**\n * Normalize InSpec exec-json v1 format to HDF v2 structure for diffing.\n *\n * V1 uses: profiles[].controls[].results[].code_desc, source_location, start_time\n * V2 uses: baselines[].requirements[].results[].codeDesc, sourceLocation, startTime\n *\n * This module detects v1 documents and converts them in-memory to v2 shape\n * so the diff engine only needs to handle one format.\n */\n\nimport { parseTimestamp } from '@mitre/hdf-utilities';\n\ninterface V1Result {\n status: string;\n code_desc?: string;\n codeDesc?: string;\n run_time?: number;\n runTime?: number;\n start_time?: string;\n startTime?: string;\n message?: string;\n [key: string]: unknown;\n}\n\ninterface V1Control {\n id: string;\n title?: string;\n desc?: string;\n impact: number;\n tags?: Record<string, unknown>;\n refs?: unknown[];\n code?: string;\n source_location?: { ref?: string; line?: number };\n sourceLocation?: { ref?: string; line?: number };\n results?: V1Result[];\n [key: string]: unknown;\n}\n\ninterface V1Profile {\n name: string;\n title?: string;\n version?: string;\n sha256?: string;\n controls?: V1Control[];\n groups?: unknown[];\n supports?: unknown[];\n attributes?: unknown[];\n [key: string]: unknown;\n}\n\n/**\n * Detect whether a document is v1 (InSpec exec-json) format.\n * V1 has `profiles` at the top level; v2 has `baselines`.\n */\nexport function isV1Format(doc: Record<string, unknown>): boolean {\n return Array.isArray(doc['profiles']) && !Array.isArray(doc['baselines']);\n}\n\n/**\n * Normalize a document to v2-like structure. If already v2, returns as-is.\n * If v1, converts profiles→baselines, controls→requirements, and snake_case→camelCase.\n */\nexport function normalizeToV2(doc: Record<string, unknown>): Record<string, unknown> {\n if (!isV1Format(doc)) {\n return doc;\n }\n\n const profiles = doc['profiles'] as V1Profile[];\n const baselines = profiles.map(normalizeProfile);\n\n // Preserve timestamp from statistics if available\n const statistics = doc['statistics'] as Record<string, unknown> | undefined;\n\n return {\n baselines,\n statistics,\n timestamp: doc['timestamp'],\n };\n}\n\nfunction normalizeProfile(profile: V1Profile): Record<string, unknown> {\n const controls = profile.controls ?? [];\n const requirements = controls.map(normalizeControl);\n\n return {\n name: profile.name,\n title: profile.title,\n version: profile.version,\n checksum: profile.sha256 ? { algorithm: 'sha256', value: profile.sha256 } : undefined,\n groups: profile.groups ?? [],\n supports: profile.supports ?? [],\n inputs: profile.attributes ?? [],\n requirements,\n };\n}\n\nfunction normalizeControl(control: V1Control): Record<string, unknown> {\n const v1Results = control.results ?? [];\n const results = v1Results.map(normalizeResult);\n\n return {\n id: control.id,\n title: control.title,\n descriptions: control.desc\n ? [{ label: 'default', data: control.desc }]\n : [],\n impact: control.impact,\n tags: control.tags ?? {},\n refs: control.refs ?? [],\n code: control.code,\n sourceLocation: control.source_location ?? control.sourceLocation,\n results,\n };\n}\n\n/**\n * Map InSpec v1 result status values to HDF v2 Result_Status enum values.\n *\n * InSpec v1 uses: \"passed\", \"failed\", \"skipped\", \"error\"\n * HDF v2 uses: \"passed\", \"failed\", \"notApplicable\", \"notReviewed\", \"error\"\n *\n * \"skipped\" in InSpec means the test was not executed (typically because a\n * `describe.one_of` condition was not met, or `only_if` excluded it).\n * This maps to \"notReviewed\" in HDF v2 — the requirement was not assessed.\n */\nfunction normalizeResultStatus(v1Status: string): string {\n switch (v1Status) {\n case 'skipped':\n return 'notReviewed';\n default:\n return v1Status;\n }\n}\n\n/**\n * Normalize a timestamp string to RFC 3339 / ISO 8601 date-time format.\n *\n * InSpec v1 uses formats like \"2017-09-22 14:12:15 -0400\" which are not valid\n * RFC 3339. This function attempts to parse and re-format such timestamps.\n * If parsing fails, the original string is returned as-is.\n */\nfunction normalizeTimestamp(timestamp: string): string {\n // Already valid ISO 8601 (contains 'T')\n if (timestamp.includes('T')) {\n return timestamp;\n }\n\n // Parse InSpec format (\"YYYY-MM-DD HH:MM:SS +HHMM\") via the shared helper,\n // which reads a zone-less value as UTC rather than host-local.\n const parsed = parseTimestamp(timestamp);\n if (parsed) {\n return parsed.toISOString();\n }\n\n return timestamp;\n}\n\nfunction normalizeResult(result: V1Result): Record<string, unknown> {\n const rawStartTime = result.start_time ?? result.startTime ?? '';\n const normalized: Record<string, unknown> = {\n status: normalizeResultStatus(result.status),\n codeDesc: result.code_desc ?? result.codeDesc ?? '',\n startTime: rawStartTime ? normalizeTimestamp(rawStartTime) : rawStartTime,\n };\n\n // Only include optional fields when they have values\n const runTime = result.run_time ?? result.runTime;\n if (runTime !== undefined) {\n normalized['runTime'] = runTime;\n }\n if (result.message !== undefined) {\n normalized['message'] = result.message;\n }\n\n return normalized;\n}\n","import type { MatchStrategy, MatchResult } from './types.js';\n\n/**\n * Create an exact ID matching strategy.\n *\n * Matches requirements by their `id` field with exact string equality.\n * Confidence is always 1.0 for matches.\n */\nexport function createExactIdStrategy(): MatchStrategy {\n return {\n name: 'exactId',\n match(oldReqs: Record<string, unknown>[], newReqs: Record<string, unknown>[]): MatchResult {\n const result: MatchResult = {\n matched: [],\n unmatchedOld: [],\n unmatchedNew: [],\n };\n\n // Build a map of new requirements by id, detecting duplicates.\n // When multiple requirements share the same ID, the ID is ambiguous\n // and cannot be used for matching — all duplicates go to unmatchedNew.\n const newById = new Map<string, Record<string, unknown>>();\n const duplicateNewIds = new Set<string>();\n for (const req of newReqs) {\n const id = req['id'];\n if (typeof id === 'string') {\n if (newById.has(id)) {\n // Mark this ID as a duplicate — remove it from the map\n duplicateNewIds.add(id);\n newById.delete(id);\n } else if (!duplicateNewIds.has(id)) {\n newById.set(id, req);\n }\n }\n }\n\n // Build a map of old requirements by id, detecting duplicates.\n const oldById = new Map<string, Record<string, unknown>>();\n const duplicateOldIds = new Set<string>();\n for (const req of oldReqs) {\n const id = req['id'];\n if (typeof id === 'string') {\n if (oldById.has(id)) {\n duplicateOldIds.add(id);\n oldById.delete(id);\n } else if (!duplicateOldIds.has(id)) {\n oldById.set(id, req);\n }\n }\n }\n\n // Track which new reqs have been matched\n const matchedNewIds = new Set<string>();\n\n // Match old requirements against new by id (skip duplicate old IDs)\n for (const oldReq of oldReqs) {\n const id = oldReq['id'];\n if (typeof id !== 'string' || duplicateOldIds.has(id)) {\n result.unmatchedOld.push(oldReq);\n continue;\n }\n\n const newReq = newById.get(id);\n if (newReq) {\n result.matched.push({\n oldReq,\n newReq,\n strategy: 'exactId',\n confidence: 1.0,\n });\n matchedNewIds.add(id);\n } else {\n result.unmatchedOld.push(oldReq);\n }\n }\n\n // Collect unmatched new requirements (including all duplicates)\n for (const req of newReqs) {\n const id = req['id'];\n if (typeof id === 'string') {\n if (duplicateNewIds.has(id) || !matchedNewIds.has(id)) {\n result.unmatchedNew.push(req);\n }\n } else {\n result.unmatchedNew.push(req);\n }\n }\n\n return result;\n },\n };\n}\n","import type { MatchStrategy, MatchResult } from './types.js';\n\n/**\n * Create a mapped ID matching strategy.\n *\n * Translates old requirement IDs using a mapping table before matching.\n * Only matches requirements whose old ID appears in the mapping table and\n * whose mapped new ID exists in the new requirements.\n *\n * Confidence is 0.95 for mapped matches (slightly less than exact ID\n * because the match depends on the accuracy of the mapping table).\n */\nexport function createMappedIdStrategy(mapping: Record<string, string>): MatchStrategy {\n return {\n name: 'mappedId',\n match(oldReqs: Record<string, unknown>[], newReqs: Record<string, unknown>[]): MatchResult {\n const result: MatchResult = {\n matched: [],\n unmatchedOld: [],\n unmatchedNew: [],\n };\n\n // Build a map of new requirements by id, detecting duplicates.\n // When multiple requirements share the same ID, the ID is ambiguous\n // and cannot be used for matching — all duplicates go to unmatchedNew.\n const newById = new Map<string, Record<string, unknown>>();\n const duplicateNewIds = new Set<string>();\n for (const req of newReqs) {\n const id = req['id'];\n if (typeof id === 'string') {\n if (newById.has(id)) {\n duplicateNewIds.add(id);\n newById.delete(id);\n } else if (!duplicateNewIds.has(id)) {\n newById.set(id, req);\n }\n }\n }\n\n // Build a map of old requirements by id, detecting duplicates.\n const oldById = new Map<string, Record<string, unknown>>();\n const duplicateOldIds = new Set<string>();\n for (const req of oldReqs) {\n const id = req['id'];\n if (typeof id === 'string') {\n if (oldById.has(id)) {\n duplicateOldIds.add(id);\n oldById.delete(id);\n } else if (!duplicateOldIds.has(id)) {\n oldById.set(id, req);\n }\n }\n }\n\n // Track which new reqs have been matched\n const matchedNewIds = new Set<string>();\n\n // Try to match old requirements using the mapping table (skip duplicate old IDs)\n for (const oldReq of oldReqs) {\n const oldId = oldReq['id'];\n if (typeof oldId !== 'string' || duplicateOldIds.has(oldId)) {\n result.unmatchedOld.push(oldReq);\n continue;\n }\n\n const mappedNewId = mapping[oldId];\n if (mappedNewId === undefined) {\n result.unmatchedOld.push(oldReq);\n continue;\n }\n\n // Skip if the mapped new ID is a duplicate\n if (duplicateNewIds.has(mappedNewId)) {\n result.unmatchedOld.push(oldReq);\n continue;\n }\n\n const newReq = newById.get(mappedNewId);\n if (newReq && !matchedNewIds.has(mappedNewId)) {\n result.matched.push({\n oldReq,\n newReq,\n strategy: 'mappedId',\n confidence: 0.95,\n });\n matchedNewIds.add(mappedNewId);\n } else {\n result.unmatchedOld.push(oldReq);\n }\n }\n\n // Collect unmatched new requirements (including all duplicates)\n for (const req of newReqs) {\n const id = req['id'];\n if (typeof id === 'string') {\n if (duplicateNewIds.has(id) || !matchedNewIds.has(id)) {\n result.unmatchedNew.push(req);\n }\n } else {\n result.unmatchedNew.push(req);\n }\n }\n\n return result;\n },\n };\n}\n","import type { MatchStrategy, MatchResult } from './types.js';\n\n/**\n * Extract CCI identifiers from a requirement's tags.\n * Looks for `tags.cci` as an array of strings.\n */\nfunction extractCcis(req: Record<string, unknown>): string[] {\n const tags = req['tags'] as Record<string, unknown> | undefined;\n if (!tags) return [];\n const cci = tags['cci'];\n if (!Array.isArray(cci)) return [];\n return cci.filter((c): c is string => typeof c === 'string');\n}\n\n/**\n * Extract CWE identifiers from a requirement.\n *\n * Prefers the structured `req.cwe[]` field (introduced in Evaluated_Requirement\n * Wave 1) when present and non-empty. Falls back to `tags.cwe` for compatibility\n * with HDF files emitted before the structured field existed. `tags.cwe` may be\n * either an array of strings or a single string.\n *\n * Exported for reuse by sibling matchers (e.g. srg-cci-tiebreak) and to make\n * the preference order directly testable.\n */\nexport function extractCwes(req: Record<string, unknown>): string[] {\n const cwe = req['cwe'];\n if (Array.isArray(cwe)) {\n const filtered = cwe.filter((c): c is string => typeof c === 'string');\n if (filtered.length > 0) return filtered;\n }\n const tags = req['tags'] as Record<string, unknown> | undefined;\n if (!tags) return [];\n const tagCwe = tags['cwe'];\n if (Array.isArray(tagCwe)) {\n return tagCwe.filter((c): c is string => typeof c === 'string');\n }\n if (typeof tagCwe === 'string') {\n return [tagCwe];\n }\n return [];\n}\n\n/**\n * Build a key → [requirement-indices] map for unambiguous-pair lookup.\n */\nfunction indexByKey(\n reqs: Record<string, unknown>[],\n keys: (req: Record<string, unknown>) => string[],\n): Map<string, number[]> {\n const map = new Map<string, number[]>();\n for (let i = 0; i < reqs.length; i++) {\n for (const key of keys(reqs[i]!)) {\n const list = map.get(key);\n if (list) {\n list.push(i);\n } else {\n map.set(key, [i]);\n }\n }\n }\n return map;\n}\n\n/**\n * Pair indices by an unambiguous shared key (exactly 1 old + 1 new per key),\n * skipping any indices already claimed in `matchedOld` / `matchedNew`.\n */\nfunction pairUnambiguous(\n oldMap: Map<string, number[]>,\n newMap: Map<string, number[]>,\n matchedOld: Set<number>,\n matchedNew: Set<number>,\n): Array<{ oldIdx: number; newIdx: number }> {\n const pairs: Array<{ oldIdx: number; newIdx: number }> = [];\n const allKeys = new Set([...oldMap.keys(), ...newMap.keys()]);\n for (const key of allKeys) {\n const oldIndices = oldMap.get(key) ?? [];\n const newIndices = newMap.get(key) ?? [];\n if (oldIndices.length !== 1 || newIndices.length !== 1) continue;\n const oldIdx = oldIndices[0]!;\n const newIdx = newIndices[0]!;\n if (matchedOld.has(oldIdx) || matchedNew.has(newIdx)) continue;\n pairs.push({ oldIdx, newIdx });\n matchedOld.add(oldIdx);\n matchedNew.add(newIdx);\n }\n return pairs;\n}\n\n/**\n * Create a CCI-based matching strategy.\n *\n * Matches requirements that share the same CCI identifier in `tags.cci`.\n * Only produces a match when exactly one old requirement and exactly one\n * new requirement share a given CCI (unambiguous). Ambiguous CCIs (shared\n * by multiple old or multiple new requirements) are skipped, and those\n * requirements are left unmatched.\n *\n * As a fallback, also pairs unambiguous CWE matches (preferring the\n * structured `req.cwe[]` field over the legacy `tags.cwe`). This catches\n * CVE-ecosystem findings where CCI is absent but CWE is present.\n *\n * Confidence is 0.8 for CCI matches and 0.6 for CWE-fallback matches.\n */\nexport function createCciMatchStrategy(): MatchStrategy {\n return {\n name: 'cciMatch',\n match(oldReqs: Record<string, unknown>[], newReqs: Record<string, unknown>[]): MatchResult {\n const matchedOldIndices = new Set<number>();\n const matchedNewIndices = new Set<number>();\n const matched: MatchResult['matched'] = [];\n\n // Primary signal: CCI.\n const oldCciMap = indexByKey(oldReqs, extractCcis);\n const newCciMap = indexByKey(newReqs, extractCcis);\n for (const { oldIdx, newIdx } of pairUnambiguous(\n oldCciMap,\n newCciMap,\n matchedOldIndices,\n matchedNewIndices,\n )) {\n matched.push({\n oldReq: oldReqs[oldIdx]!,\n newReq: newReqs[newIdx]!,\n strategy: 'cciMatch',\n confidence: 0.8,\n });\n }\n\n // Fallback signal: CWE (structured field preferred over tags.cwe).\n // All reqs are indexed here; pairUnambiguous skips any already claimed by\n // CCI pairing via the matchedOld/NewIndices sets passed below.\n const oldCweMap = indexByKey(oldReqs, (r) => extractCwes(r));\n const newCweMap = indexByKey(newReqs, (r) => extractCwes(r));\n for (const { oldIdx, newIdx } of pairUnambiguous(\n oldCweMap,\n newCweMap,\n matchedOldIndices,\n matchedNewIndices,\n )) {\n matched.push({\n oldReq: oldReqs[oldIdx]!,\n newReq: newReqs[newIdx]!,\n strategy: 'cciMatch',\n confidence: 0.6,\n });\n }\n\n const unmatchedOld: Record<string, unknown>[] = [];\n for (let i = 0; i < oldReqs.length; i++) {\n if (!matchedOldIndices.has(i)) unmatchedOld.push(oldReqs[i]!);\n }\n const unmatchedNew: Record<string, unknown>[] = [];\n for (let i = 0; i < newReqs.length; i++) {\n if (!matchedNewIndices.has(i)) unmatchedNew.push(newReqs[i]!);\n }\n\n return { matched, unmatchedOld, unmatchedNew };\n },\n };\n}\n","import type { MatchStrategy, MatchResult } from './types.js';\n\n/** Common English stop words to exclude from tokenization */\nconst STOP_WORDS = new Set([\n 'a', 'an', 'the', 'is', 'are', 'was', 'were', 'be', 'been', 'being',\n 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'could',\n 'should', 'may', 'might', 'shall', 'can', 'to', 'of', 'in', 'for',\n 'on', 'with', 'at', 'by', 'from', 'as', 'into', 'through', 'during',\n 'before', 'after', 'above', 'below', 'between', 'out', 'off', 'over',\n 'under', 'again', 'further', 'then', 'once', 'and', 'but', 'or', 'nor',\n 'not', 'no', 'so', 'if', 'it', 'its', 'that', 'this', 'these', 'those',\n 'each', 'every', 'all', 'both', 'few', 'more', 'most', 'other', 'some',\n 'such', 'than', 'too', 'very', 'just', 'about',\n]);\n\n/**\n * Tokenize a title string into a set of meaningful tokens.\n *\n * - Lowercases the string\n * - Splits on whitespace and punctuation\n * - Filters out common stop words\n * - Returns unique tokens as a Set\n */\nexport function tokenize(text: string): Set<string> {\n if (!text) return new Set();\n\n const tokens = text\n .toLowerCase()\n .split(/[\\s\\-_/\\\\,.;:!?()[\\]{}\"']+/)\n .filter((t) => t.length > 0 && !STOP_WORDS.has(t));\n\n return new Set(tokens);\n}\n\n/**\n * Compute Jaccard similarity between two sets.\n * Returns |intersection| / |union|, or 0 if both sets are empty.\n */\nexport function jaccardSimilarity(a: Set<string>, b: Set<string>): number {\n if (a.size === 0 && b.size === 0) return 0.0;\n\n let intersectionSize = 0;\n // Iterate over the smaller set for efficiency\n const [smaller, larger] = a.size <= b.size ? [a, b] : [b, a];\n for (const item of smaller) {\n if (larger.has(item)) {\n intersectionSize++;\n }\n }\n\n const unionSize = a.size + b.size - intersectionSize;\n // Unreachable: if both sets are empty, we return above. If either is non-empty, unionSize > 0.\n // Guard kept for mathematical correctness.\n /* c8 ignore next */\n if (unionSize === 0) return 0.0;\n\n return intersectionSize / unionSize;\n}\n\n/**\n * Default minimum confidence threshold for fuzzy title matching.\n */\nconst DEFAULT_MIN_CONFIDENCE = 0.6;\n\n/**\n * Create a fuzzy title matching strategy.\n *\n * Matches requirements by token-based Jaccard similarity on the `title` field.\n * Uses greedy best-match: for each unmatched old requirement, finds the\n * best-matching unmatched new requirement above the confidence threshold.\n *\n * @param minConfidence Minimum Jaccard similarity to accept a match (default: 0.6)\n */\nexport function createFuzzyTitleStrategy(minConfidence?: number): MatchStrategy {\n const threshold = minConfidence ?? DEFAULT_MIN_CONFIDENCE;\n\n return {\n name: 'fuzzyTitle',\n match(oldReqs: Record<string, unknown>[], newReqs: Record<string, unknown>[]): MatchResult {\n const result: MatchResult = {\n matched: [],\n unmatchedOld: [],\n unmatchedNew: [],\n };\n\n // Pre-tokenize all titles\n const oldTokens: Array<{ idx: number; tokens: Set<string> }> = [];\n for (let i = 0; i < oldReqs.length; i++) {\n const title = oldReqs[i]!['title'];\n if (typeof title === 'string' && title.length > 0) {\n const tokens = tokenize(title);\n if (tokens.size > 0) {\n oldTokens.push({ idx: i, tokens });\n }\n }\n }\n\n const newTokens: Array<{ idx: number; tokens: Set<string> }> = [];\n for (let i = 0; i < newReqs.length; i++) {\n const title = newReqs[i]!['title'];\n if (typeof title === 'string' && title.length > 0) {\n const tokens = tokenize(title);\n if (tokens.size > 0) {\n newTokens.push({ idx: i, tokens });\n }\n }\n }\n\n // Track matched indices\n const matchedOldIndices = new Set<number>();\n const matchedNewIndices = new Set<number>();\n\n // Build a list of all potential matches with similarity scores\n const candidates: Array<{\n oldIdx: number;\n newIdx: number;\n similarity: number;\n }> = [];\n\n for (const old of oldTokens) {\n for (const nw of newTokens) {\n const sim = jaccardSimilarity(old.tokens, nw.tokens);\n if (sim >= threshold) {\n candidates.push({\n oldIdx: old.idx,\n newIdx: nw.idx,\n similarity: sim,\n });\n }\n }\n }\n\n // Sort by similarity descending (greedy best-match)\n candidates.sort((a, b) => b.similarity - a.similarity);\n\n // Greedily assign matches\n for (const candidate of candidates) {\n if (matchedOldIndices.has(candidate.oldIdx) || matchedNewIndices.has(candidate.newIdx)) {\n continue;\n }\n\n result.matched.push({\n oldReq: oldReqs[candidate.oldIdx]!,\n newReq: newReqs[candidate.newIdx]!,\n strategy: 'fuzzyTitle',\n confidence: candidate.similarity,\n });\n matchedOldIndices.add(candidate.oldIdx);\n matchedNewIndices.add(candidate.newIdx);\n }\n\n // Collect unmatched\n for (let i = 0; i < oldReqs.length; i++) {\n if (!matchedOldIndices.has(i)) {\n result.unmatchedOld.push(oldReqs[i]!);\n }\n }\n for (let i = 0; i < newReqs.length; i++) {\n if (!matchedNewIndices.has(i)) {\n result.unmatchedNew.push(newReqs[i]!);\n }\n }\n\n return result;\n },\n };\n}\n","import type { MatchStrategy, MatchResult, MatchPair } from './types.js';\n\n/**\n * Extract the SRG-OS ID from a requirement's tags.gtitle field.\n * Returns null if missing or not a string.\n */\nfunction extractGtitle(req: Record<string, unknown>): string | null {\n const tags = req['tags'] as Record<string, unknown> | undefined;\n if (!tags) return null;\n const gtitle = tags['gtitle'];\n if (typeof gtitle !== 'string' || gtitle === '') return null;\n return gtitle;\n}\n\n/**\n * Create a deterministic SRG matching strategy (Tier 1 of the delta pipeline).\n *\n * Matches requirements by exact `tags.gtitle` (SRG-OS requirement ID).\n *\n * For each gtitle shared between old and new:\n * - 1 old + 1 new → single MatchPair (confidence 1.0, relationship \"primary\")\n * - 1 new + N old → N MatchPairs (first old \"primary\", rest \"related\")\n * - N new + 1 old → N MatchPairs (first new \"primary\", rest \"related\")\n * - N:M (both > 1) → skip, leave for fallback strategies\n *\n * Requirements without a gtitle pass through as unmatched.\n */\nexport function createSrgDeterministicStrategy(): MatchStrategy {\n return {\n name: 'srgDeterministic',\n match(oldReqs: Record<string, unknown>[], newReqs: Record<string, unknown>[]): MatchResult {\n // Build gtitle → indices for old\n const oldGtitleMap = new Map<string, number[]>();\n for (let i = 0; i < oldReqs.length; i++) {\n const g = extractGtitle(oldReqs[i]!);\n if (g) {\n const list = oldGtitleMap.get(g);\n if (list) list.push(i);\n else oldGtitleMap.set(g, [i]);\n }\n }\n\n // Build gtitle → indices for new\n const newGtitleMap = new Map<string, number[]>();\n for (let i = 0; i < newReqs.length; i++) {\n const g = extractGtitle(newReqs[i]!);\n if (g) {\n const list = newGtitleMap.get(g);\n if (list) list.push(i);\n else newGtitleMap.set(g, [i]);\n }\n }\n\n const matched: MatchPair[] = [];\n const matchedOldIndices = new Set<number>();\n const matchedNewIndices = new Set<number>();\n // Track which old indices have been claimed as \"primary\"\n const claimedOldIndices = new Set<number>();\n\n for (const [gtitle, newIdxList] of newGtitleMap) {\n const oldIdxList = oldGtitleMap.get(gtitle);\n if (!oldIdxList || oldIdxList.length === 0) continue;\n\n const nc = newIdxList.length;\n const oc = oldIdxList.length;\n\n // N:M ambiguous — skip\n if (nc > 1 && oc > 1) continue;\n\n // Create match pairs\n for (const ni of newIdxList) {\n let primaryOldSet = false;\n for (const oi of oldIdxList) {\n let relationship: 'primary' | 'related';\n if (oc === 1) {\n // 1 old, possibly multiple new → claim tracking\n relationship = claimedOldIndices.has(oi) ? 'related' : 'primary';\n if (relationship === 'primary') claimedOldIndices.add(oi);\n } else {\n // Multiple old, 1 new → first old is primary\n relationship = primaryOldSet ? 'related' : 'primary';\n primaryOldSet = true;\n }\n\n matched.push({\n oldReq: oldReqs[oi]!,\n newReq: newReqs[ni]!,\n strategy: 'srgDeterministic',\n confidence: 1.0,\n relationship,\n });\n matchedOldIndices.add(oi);\n }\n matchedNewIndices.add(ni);\n }\n }\n\n // Collect unmatched\n const unmatchedOld: Record<string, unknown>[] = [];\n for (let i = 0; i < oldReqs.length; i++) {\n if (!matchedOldIndices.has(i)) unmatchedOld.push(oldReqs[i]!);\n }\n const unmatchedNew: Record<string, unknown>[] = [];\n for (let i = 0; i < newReqs.length; i++) {\n if (!matchedNewIndices.has(i)) unmatchedNew.push(newReqs[i]!);\n }\n\n return { matched, unmatchedOld, unmatchedNew };\n },\n };\n}\n","import type { MatchStrategy, MatchResult, MatchPair } from './types.js';\n\n/** Composite score weights matching SAF CLI's Tier 2. */\nconst CCI_WEIGHT = 0.7;\nconst TITLE_WEIGHT = 0.3;\n\n/**\n * Extract CCI identifiers from a requirement's tags.cci.\n */\nfunction extractCcis(req: Record<string, unknown>): Set<string> {\n const tags = req['tags'] as Record<string, unknown> | undefined;\n if (!tags) return new Set();\n const cci = tags['cci'];\n if (!Array.isArray(cci)) return new Set();\n return new Set(cci.filter((c): c is string => typeof c === 'string'));\n}\n\n/**\n * Extract CWE identifiers from a requirement.\n *\n * Prefers the structured `req.cwe[]` field (introduced in Evaluated_Requirement\n * Wave 1) when present and non-empty. Falls back to `tags.cwe` (array or string)\n * for compatibility with HDF files emitted before the structured field existed.\n *\n * Exported so callers and tests can verify the preference order directly.\n */\nexport function extractCwes(req: Record<string, unknown>): Set<string> {\n const cwe = req['cwe'];\n if (Array.isArray(cwe)) {\n const filtered = cwe.filter((c): c is string => typeof c === 'string');\n if (filtered.length > 0) return new Set(filtered);\n }\n const tags = req['tags'] as Record<string, unknown> | undefined;\n if (!tags) return new Set();\n const tagCwe = tags['cwe'];\n if (Array.isArray(tagCwe)) {\n return new Set(tagCwe.filter((c): c is string => typeof c === 'string'));\n }\n if (typeof tagCwe === 'string') {\n return new Set([tagCwe]);\n }\n return new Set();\n}\n\n/**\n * Extract tags.gtitle from a requirement.\n */\nfunction extractGtitle(req: Record<string, unknown>): string | null {\n const tags = req['tags'] as Record<string, unknown> | undefined;\n if (!tags) return null;\n const gtitle = tags['gtitle'];\n if (typeof gtitle !== 'string' || gtitle === '') return null;\n return gtitle;\n}\n\n/**\n * Extract title from a requirement.\n */\nfunction safeTitle(req: Record<string, unknown>): string {\n const title = req['title'];\n return typeof title === 'string' ? title : '';\n}\n\n/**\n * Jaccard similarity between two sets.\n */\nfunction cciJaccard(a: Set<string>, b: Set<string>): number {\n if (a.size === 0 && b.size === 0) return 0;\n let intersectionSize = 0;\n for (const x of a) {\n if (b.has(x)) intersectionSize++;\n }\n const unionSize = a.size + b.size - intersectionSize;\n return intersectionSize / unionSize;\n}\n\n/**\n * Simple whitespace-split token Jaccard similarity.\n */\nfunction tokenJaccard(a: string, b: string): number {\n const ta = new Set(\n a\n .toLowerCase()\n .split(/\\s+/)\n .filter((t) => t.length > 0),\n );\n const tb = new Set(\n b\n .toLowerCase()\n .split(/\\s+/)\n .filter((t) => t.length > 0),\n );\n if (ta.size === 0 || tb.size === 0) return 0;\n let intersectionSize = 0;\n for (const x of ta) {\n if (tb.has(x)) intersectionSize++;\n }\n const unionSize = ta.size + tb.size - intersectionSize;\n return intersectionSize / unionSize;\n}\n\n/**\n * Create an SRG CCI Tiebreak matching strategy (Tier 2 of the delta pipeline).\n *\n * Handles ambiguous SRG matches where multiple old or new requirements share\n * the same tags.gtitle. Uses a composite score of CCI Jaccard (70%) and\n * token Jaccard on titles (30%) to pick the best match.\n *\n * Only activates for gtitle groups with multiple candidates (>1 old or >1 new).\n * 1:1 matches are left for srgDeterministic (Tier 1).\n */\nexport function createSrgCciTiebreakStrategy(): MatchStrategy {\n return {\n name: 'srgCciTiebreak',\n match(oldReqs: Record<string, unknown>[], newReqs: Record<string, unknown>[]): MatchResult {\n // Build gtitle → indices\n const oldGtitleMap = new Map<string, number[]>();\n for (let i = 0; i < oldReqs.length; i++) {\n const g = extractGtitle(oldReqs[i]!);\n if (g) {\n const list = oldGtitleMap.get(g);\n if (list) list.push(i);\n else oldGtitleMap.set(g, [i]);\n }\n }\n\n const newGtitleMap = new Map<string, number[]>();\n for (let i = 0; i < newReqs.length; i++) {\n const g = extractGtitle(newReqs[i]!);\n if (g) {\n const list = newGtitleMap.get(g);\n if (list) list.push(i);\n else newGtitleMap.set(g, [i]);\n }\n }\n\n const matched: MatchPair[] = [];\n const matchedOldIndices = new Set<number>();\n const matchedNewIndices = new Set<number>();\n\n for (const [gtitle, newIdxList] of newGtitleMap) {\n const oldIdxList = oldGtitleMap.get(gtitle);\n if (!oldIdxList || oldIdxList.length === 0) continue;\n\n const nc = newIdxList.length;\n const oc = oldIdxList.length;\n\n // Only handle ambiguous cases (at least one side > 1)\n // 1:1 is handled by srgDeterministic\n if (nc === 1 && oc === 1) continue;\n\n // Greedy matching: process each new req, find best old candidate\n for (const ni of newIdxList) {\n if (matchedNewIndices.has(ni)) continue;\n\n const newCcis = extractCcis(newReqs[ni]!);\n const newTitle = safeTitle(newReqs[ni]!);\n const newCwes = extractCwes(newReqs[ni]!);\n\n let bestIdx = -1;\n let bestComposite = -1;\n let bestCci = 0;\n let bestCwe = -1;\n let bestIsUnclaimed = false;\n\n for (const oi of oldIdxList) {\n const oldCcis = extractCcis(oldReqs[oi]!);\n const oldTitle = safeTitle(oldReqs[oi]!);\n const oldCwes = extractCwes(oldReqs[oi]!);\n\n const cci = cciJaccard(newCcis, oldCcis);\n const title = tokenJaccard(newTitle, oldTitle);\n // CWE Jaccard is used purely as a tiebreaker — it does NOT\n // change composite scoring weights, so existing tests that\n // depend on CCI+title ordering are unaffected.\n const cwe = cciJaccard(newCwes, oldCwes);\n const composite = CCI_WEIGHT * cci + TITLE_WEIGHT * title;\n const isUnclaimed = !matchedOldIndices.has(oi);\n\n // Prefer unclaimed candidates; among same claim status, prefer\n // higher composite; among equal composites, prefer higher CWE\n // Jaccard (tiebreaker added Wave 2).\n if (\n bestIdx === -1 ||\n (isUnclaimed && !bestIsUnclaimed) ||\n (isUnclaimed === bestIsUnclaimed && composite > bestComposite) ||\n (isUnclaimed === bestIsUnclaimed &&\n composite === bestComposite &&\n cwe > bestCwe)\n ) {\n bestIdx = oi;\n bestComposite = composite;\n bestCci = cci;\n bestCwe = cwe;\n bestIsUnclaimed = isUnclaimed;\n }\n }\n\n if (bestIdx >= 0) {\n const relationship = matchedOldIndices.has(bestIdx) ? 'related' : 'primary';\n matched.push({\n oldReq: oldReqs[bestIdx]!,\n newReq: newReqs[ni]!,\n strategy: 'srgCciTiebreak',\n confidence: Math.max(bestCci, 0),\n relationship,\n });\n matchedOldIndices.add(bestIdx);\n matchedNewIndices.add(ni);\n }\n }\n }\n\n // Collect unmatched\n const unmatchedOld: Record<string, unknown>[] = [];\n for (let i = 0; i < oldReqs.length; i++) {\n if (!matchedOldIndices.has(i)) unmatchedOld.push(oldReqs[i]!);\n }\n const unmatchedNew: Record<string, unknown>[] = [];\n for (let i = 0; i < newReqs.length; i++) {\n if (!matchedNewIndices.has(i)) unmatchedNew.push(newReqs[i]!);\n }\n\n return { matched, unmatchedOld, unmatchedNew };\n },\n };\n}\n","import type { MatchStrategy, MatchResult, MatchPair } from './types.js';\n\n/** Default threshold for accepting a Levenshtein match. */\nconst DEFAULT_ACCEPT_THRESHOLD = 0.45;\n\n// Bounds the Levenshtein DP. Far above any realistic requirement/vendor title,\n// so no real match result changes; beyond it the inputs are not titles, and the\n// O(m*n) DP (plus O(n) allocation) would be a needless cost and an algorithmic-DoS\n// surface, so such pairs get the trivial upper bound instead. Mirrors the Go port\n// (hdf-diff/go/matching/vendor_fuzzy_title.go: maxLevenshteinRunes).\nconst MAX_LEVENSHTEIN_LENGTH = 4096;\n\n/** Modal verbs that mark the start of compliance statements. */\nconst COMPLIANCE_MODALS = new Set([\n 'must', 'will', 'shall', 'should', 'may', 'needs',\n]);\n\n/**\n * Compute the Levenshtein edit distance between two strings.\n */\nexport function levenshteinDistance(a: string, b: string): number {\n const m = a.length;\n const n = b.length;\n if (m === 0) return n;\n if (n === 0) return m;\n\n // Beyond the cap the inputs are not realistic titles: return the trivial upper\n // bound (edit distance never exceeds the longer length) rather than allocating\n // O(n) and running O(m*n). Mirrors the Go port's bound.\n if (m > MAX_LEVENSHTEIN_LENGTH || n > MAX_LEVENSHTEIN_LENGTH) {\n return Math.max(m, n);\n }\n\n // Use single row optimization\n let prev = new Array<number>(n + 1);\n let curr = new Array<number>(n + 1);\n for (let j = 0; j <= n; j++) prev[j] = j;\n\n for (let i = 1; i <= m; i++) {\n curr[0] = i;\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n curr[j] = Math.min(\n prev[j]! + 1, // deletion\n curr[j - 1]! + 1, // insertion\n prev[j - 1]! + cost, // substitution\n );\n }\n [prev, curr] = [curr, prev];\n }\n\n return prev[n]!;\n}\n\n/**\n * Normalized Levenshtein distance (0.0 = identical, 1.0 = completely different).\n */\nexport function normalizedLevenshtein(a: string, b: string): number {\n const maxLen = Math.max(a.length, b.length);\n if (maxLen === 0) return 0.0;\n return levenshteinDistance(a, b) / maxLen;\n}\n\n/**\n * Extract tokens before the first modal verb in a title.\n */\nfunction tokensBeforeModal(title: string): string[] {\n const tokens = title.split(/\\s+/).filter((t) => t.length > 0);\n const modalIdx = tokens.findIndex((t) => COMPLIANCE_MODALS.has(t.toLowerCase()));\n return modalIdx === -1 ? tokens : tokens.slice(0, modalIdx);\n}\n\n/**\n * Auto-detect the dominant vendor prefix in a corpus of titles.\n *\n * Tries progressively shorter leading-token prefixes. Returns the prefix\n * that appears in > 50% of titles, stopping before modal verbs.\n * Returns '' when no prefix reaches the threshold.\n */\nexport function autoDetectPrefix(titles: string[], threshold = 0.5): string {\n if (titles.length === 0) return '';\n\n const leading = titles.map((t) => tokensBeforeModal(t));\n const maxLen = Math.max(...leading.map((l) => l.length));\n\n for (let n = maxLen; n > 0; n--) {\n const counts = new Map<string, number>();\n for (const l of leading) {\n if (l.length >= n) {\n const key = l.slice(0, n).join(' ');\n counts.set(key, (counts.get(key) ?? 0) + 1);\n }\n }\n let bestKey = '';\n let bestCount = 0;\n for (const [key, count] of counts) {\n if (count > bestCount) {\n bestKey = key;\n bestCount = count;\n }\n }\n if (bestCount / titles.length > threshold) {\n return bestKey;\n }\n }\n return '';\n}\n\n/**\n * Strip a detected vendor prefix from a title.\n */\nexport function normalizeTitle(title: string, prefix: string): string {\n if (!prefix) return title;\n if (title === prefix) return '';\n if (title.startsWith(prefix + ' ')) return title.slice(prefix.length + 1);\n return title;\n}\n\n/**\n * Extract title string from a requirement.\n */\nfunction safeTitle(req: Record<string, unknown>): string {\n const title = req['title'];\n return typeof title === 'string' ? title : '';\n}\n\n/**\n * Create a vendor fuzzy title matching strategy (Tier 3 of the delta pipeline).\n *\n * Cross-vendor matching with auto-detected vendor prefix stripping.\n * Uses normalized Levenshtein distance to compare titles after removing\n * the dominant vendor prefix (e.g., \"RHEL 9\" or \"Amazon Linux 2023\").\n *\n * Accepts matches below threshold 0.45 (confidence = 1.0 - distance).\n * Greedy best-match.\n *\n * @param acceptThreshold Max normalized Levenshtein distance to accept (default: 0.45)\n */\nexport function createVendorFuzzyTitleStrategy(acceptThreshold?: number): MatchStrategy {\n const threshold = acceptThreshold ?? DEFAULT_ACCEPT_THRESHOLD;\n\n return {\n name: 'vendorFuzzyTitle',\n match(oldReqs: Record<string, unknown>[], newReqs: Record<string, unknown>[]): MatchResult {\n // Collect titles for prefix detection\n const oldTitles = oldReqs.map(safeTitle).filter((t) => t.length > 0);\n const newTitles = newReqs.map(safeTitle).filter((t) => t.length > 0);\n const oldPrefix = autoDetectPrefix(oldTitles);\n const newPrefix = autoDetectPrefix(newTitles);\n\n // Build candidates with normalized titles\n type IndexedTitle = { idx: number; normalized: string };\n const oldNorm: IndexedTitle[] = [];\n for (let i = 0; i < oldReqs.length; i++) {\n const t = safeTitle(oldReqs[i]!);\n if (t) {\n oldNorm.push({ idx: i, normalized: normalizeTitle(t, oldPrefix) });\n }\n }\n const newNorm: IndexedTitle[] = [];\n for (let i = 0; i < newReqs.length; i++) {\n const t = safeTitle(newReqs[i]!);\n if (t) {\n newNorm.push({ idx: i, normalized: normalizeTitle(t, newPrefix) });\n }\n }\n\n // Compute all pairwise distances\n const candidates: Array<{\n oldIdx: number;\n newIdx: number;\n distance: number;\n }> = [];\n\n for (const old of oldNorm) {\n for (const nw of newNorm) {\n if (!old.normalized || !nw.normalized) continue;\n const dist = normalizedLevenshtein(old.normalized, nw.normalized);\n if (dist < threshold) {\n candidates.push({\n oldIdx: old.idx,\n newIdx: nw.idx,\n distance: dist,\n });\n }\n }\n }\n\n // Sort by distance ascending (best matches first)\n candidates.sort((a, b) => a.distance - b.distance);\n\n // Greedy assignment\n const matched: MatchPair[] = [];\n const matchedOldIndices = new Set<number>();\n const matchedNewIndices = new Set<number>();\n\n for (const c of candidates) {\n if (matchedOldIndices.has(c.oldIdx) || matchedNewIndices.has(c.newIdx)) continue;\n\n matched.push({\n oldReq: oldReqs[c.oldIdx]!,\n newReq: newReqs[c.newIdx]!,\n strategy: 'vendorFuzzyTitle',\n confidence: 1.0 - c.distance,\n relationship: 'primary',\n });\n matchedOldIndices.add(c.oldIdx);\n matchedNewIndices.add(c.newIdx);\n }\n\n // Collect unmatched\n const unmatchedOld: Record<string, unknown>[] = [];\n for (let i = 0; i < oldReqs.length; i++) {\n if (!matchedOldIndices.has(i)) unmatchedOld.push(oldReqs[i]!);\n }\n const unmatchedNew: Record<string, unknown>[] = [];\n for (let i = 0; i < newReqs.length; i++) {\n if (!matchedNewIndices.has(i)) unmatchedNew.push(newReqs[i]!);\n }\n\n return { matched, unmatchedOld, unmatchedNew };\n },\n };\n}\n","import type { MatchResult, MatchStrategy } from './types.js';\nimport { createExactIdStrategy } from './exact-id.js';\nimport { createMappedIdStrategy } from './mapped-id.js';\nimport { createCciMatchStrategy } from './cci-match.js';\nimport { createFuzzyTitleStrategy } from './fuzzy-match.js';\nimport { createSrgDeterministicStrategy } from './srg-deterministic.js';\nimport { createSrgCciTiebreakStrategy } from './srg-cci-tiebreak.js';\nimport { createVendorFuzzyTitleStrategy } from './vendor-fuzzy-title.js';\n\n// Re-export types and factory functions\nexport type { MatchResult, MatchPair, MatchStrategy } from './types.js';\nexport { createExactIdStrategy } from './exact-id.js';\nexport { createMappedIdStrategy } from './mapped-id.js';\nexport { createCciMatchStrategy } from './cci-match.js';\nexport { createFuzzyTitleStrategy, tokenize, jaccardSimilarity } from './fuzzy-match.js';\nexport { createSrgDeterministicStrategy } from './srg-deterministic.js';\nexport { createSrgCciTiebreakStrategy } from './srg-cci-tiebreak.js';\nexport { createVendorFuzzyTitleStrategy, levenshteinDistance, normalizedLevenshtein } from './vendor-fuzzy-title.js';\n\n/**\n * Options for configuring requirement matching.\n */\nexport interface MatchOptions {\n /** Primary matching strategy name (default: 'exactId') */\n strategy?: string;\n /** Fallback strategy names, applied in order to remaining unmatched requirements */\n fallbackStrategies?: string[];\n /** Mapping table for the 'mappedId' strategy (old ID -> new ID) */\n mappingTable?: Record<string, string>;\n /** Minimum confidence threshold for fuzzy matching (default: 0.6) */\n minConfidence?: number;\n}\n\n/**\n * Create a strategy instance by name, using the provided options for\n * strategies that require configuration.\n */\nfunction createStrategy(name: string, options: MatchOptions): MatchStrategy {\n switch (name) {\n case 'exactId':\n return createExactIdStrategy();\n case 'mappedId':\n return createMappedIdStrategy(options.mappingTable ?? {});\n case 'cciMatch':\n return createCciMatchStrategy();\n case 'fuzzyTitle':\n return createFuzzyTitleStrategy(options.minConfidence);\n case 'srgDeterministic':\n return createSrgDeterministicStrategy();\n case 'srgCciTiebreak':\n return createSrgCciTiebreakStrategy();\n case 'vendorFuzzyTitle': {\n // vendorFuzzyTitle is parameterized by a max normalized Levenshtein\n // distance, not a min confidence. Translate (confidence = 1 - distance).\n // Leave undefined when minConfidence is unset/zero so the strategy\n // applies its own default threshold.\n const acceptThreshold =\n options.minConfidence !== undefined && options.minConfidence > 0\n ? 1 - options.minConfidence\n : undefined;\n return createVendorFuzzyTitleStrategy(acceptThreshold);\n }\n default:\n throw new Error(`Unknown matching strategy: '${name}'`);\n }\n}\n\n/**\n * Match requirements between two evaluations using a primary strategy\n * and optional fallback strategies.\n *\n * The registry applies strategies in order:\n * 1. Primary strategy matches what it can\n * 2. Unmatched requirements pass to the next fallback strategy\n * 3. Process continues until all strategies are exhausted or all\n * requirements are matched\n *\n * @param oldReqs Requirements from the old evaluation\n * @param newReqs Requirements from the new evaluation\n * @param options Matching configuration\n * @returns Combined match result from all strategies\n */\nexport function matchRequirements(\n oldReqs: Record<string, unknown>[],\n newReqs: Record<string, unknown>[],\n options?: MatchOptions,\n): MatchResult {\n const opts = options ?? {};\n const primaryName = opts.strategy ?? 'exactId';\n const fallbackNames = opts.fallbackStrategies ?? [];\n\n // Build all strategy instances once up front (also validates names —\n // createStrategy throws for unknown strategy names).\n const allNames = [primaryName, ...fallbackNames];\n const strategies = allNames.map((name) => createStrategy(name, opts));\n\n // Accumulate all matched pairs\n const allMatched: MatchResult['matched'] = [];\n\n // Start with all requirements unmatched\n let currentUnmatchedOld = oldReqs;\n let currentUnmatchedNew = newReqs;\n\n // Apply strategies in order\n for (const strategy of strategies) {\n if (currentUnmatchedOld.length === 0 || currentUnmatchedNew.length === 0) {\n break;\n }\n\n const result = strategy.match(currentUnmatchedOld, currentUnmatchedNew);\n\n allMatched.push(...result.matched);\n currentUnmatchedOld = result.unmatchedOld;\n currentUnmatchedNew = result.unmatchedNew;\n }\n\n return {\n matched: allMatched,\n unmatchedOld: currentUnmatchedOld,\n unmatchedNew: currentUnmatchedNew,\n };\n}\n","import type { ValidationError } from '@mitre/hdf-validators';\nimport { validateComparison as validatorsValidateComparison } from '@mitre/hdf-validators';\n\n/**\n * Result of validating a document against the hdf-comparison schema.\n */\nexport interface ValidationResult {\n /** Whether the document conforms to the schema */\n valid: boolean;\n /** Human-readable error messages (only present when valid is false) */\n errors?: string[];\n}\n\n/**\n * Validate a document against the hdf-comparison schema.\n *\n * Delegates to @mitre/hdf-validators which loads schemas from embedded\n * bundled JSON (no filesystem access, no hardcoded version URLs).\n *\n * @param doc - The document to validate (typically the output of `diffHdf()`)\n * @returns Validation result with `valid` boolean and optional `errors` array\n */\nexport function validateComparison(doc: unknown): ValidationResult {\n const result = validatorsValidateComparison(doc);\n\n if (result.valid) {\n return { valid: true };\n }\n\n const errors = result.errors.map((e: ValidationError) =>\n e.field === '(root)' ? e.message : `${e.field}: ${e.message}`\n );\n return { valid: false, errors };\n}\n","import type {\n HDFComparison,\n RequirementDiff,\n BaselineDiff,\n ComponentDiff,\n FieldChange,\n Source,\n} from './types.js';\nimport { computeEffectiveStatus, classifyChangeReasons, classifyDiffStatus } from './status.js';\nimport { computeSummary } from './summary.js';\nimport { normalizeToV2 } from './normalize.js';\nimport { matchRequirements } from './matching/index.js';\nimport type { MatchOptions } from './matching/index.js';\nimport { validateComparison } from './validate.js';\nimport { parseCvssVector as parseCvssVectorUtil } from '@mitre/hdf-utilities';\n\n/**\n * Options for configuring the diff behavior.\n */\nexport interface DiffOptions {\n /** Fields to track for field-level diffs (default: ['impact', 'severity', 'tags']) */\n trackedFields?: string[];\n /** Comparison mode (default: 'temporal') */\n comparisonMode?: 'temporal' | 'baseline' | 'fleet' | 'multiSource' | 'baselineEvolution' | 'systemDrift';\n /** Primary matching strategy name (default: 'exactId') */\n matchStrategy?: string;\n /** Fallback strategy names, applied in order to remaining unmatched requirements */\n fallbackStrategies?: string[];\n /** Mapping table for the 'mappedId' strategy (old ID -> new ID) */\n mappingTable?: Record<string, string>;\n /** Minimum confidence threshold for fuzzy matching (default: 0.6) */\n minConfidence?: number;\n /** Validate output against hdf-comparison schema. Default: false (performance). */\n validateOutput?: boolean;\n}\n\nexport const DEFAULT_TRACKED_FIELDS = ['impact', 'severity', 'tags'];\n\ninterface BaselineLike {\n name: string;\n version?: string;\n requirements: RequirementLike[];\n}\n\ninterface RequirementLike {\n id: string;\n title?: string;\n impact: number;\n [key: string]: unknown;\n}\n\n/**\n * Round a fuzzy-match confidence (0-1 similarity) to 4 decimal places to strip\n * IEEE-754 noise from the serialized matchConfidence value.\n */\nexport function roundConfidence(x: number): number {\n return Math.round(x * 1e4) / 1e4;\n}\n\n/**\n * Extract a dataSource label from a document, if available.\n * Looks for `dataSource.name` in the raw (pre-normalized) document.\n */\nfunction extractDataSourceLabel(doc: Record<string, unknown>): string | undefined {\n const ds = doc['dataSource'] as Record<string, unknown> | undefined;\n if (ds && typeof ds['name'] === 'string') {\n return ds['name'];\n }\n return undefined;\n}\n\n/**\n * Build MatchOptions from DiffOptions, extracting the matching-related fields.\n */\nfunction buildMatchOptions(options?: DiffOptions): MatchOptions {\n return {\n strategy: options?.matchStrategy,\n fallbackStrategies: options?.fallbackStrategies,\n mappingTable: options?.mappingTable,\n minConfidence: options?.minConfidence,\n };\n}\n\n/**\n * Determine the primary strategy name for the matching config output.\n */\nfunction resolveStrategyName(options?: DiffOptions): string {\n return options?.matchStrategy ?? 'exactId';\n}\n\n/**\n * Compare two HDF results documents and produce a structured comparison.\n *\n * Requirements are matched using a configurable matching strategy (default: exact ID).\n * Baselines are matched by `name`.\n *\n * For fleet mode, `newResults` can be an array of documents, each compared\n * pairwise against `oldResults` (the reference).\n */\nexport function diffHdf(\n oldResults: Record<string, unknown>,\n newResults: Record<string, unknown> | Record<string, unknown>[],\n options?: DiffOptions,\n): HDFComparison {\n const trackedFields = options?.trackedFields ?? DEFAULT_TRACKED_FIELDS;\n let comparisonMode = options?.comparisonMode ?? 'temporal';\n const matchOpts = buildMatchOptions(options);\n\n // Auto-detect baseline evolution mode when both inputs are baseline documents\n // (have requirements[] but no baselines[], targets[], or statistics[])\n if (!options?.comparisonMode && !Array.isArray(newResults)) {\n if (isBaselineDocument(oldResults) && isBaselineDocument(newResults)) {\n comparisonMode = 'baselineEvolution';\n } else if (isSystemDocument(oldResults) && isSystemDocument(newResults)) {\n comparisonMode = 'systemDrift';\n }\n }\n\n // Validate array inputs up front (applies to all modes)\n if (Array.isArray(newResults)) {\n if (newResults.length === 0) {\n throw new Error('newResults array must not be empty');\n }\n if (comparisonMode !== 'fleet' && newResults.length > 1) {\n throw new Error(\n `Mode '${comparisonMode}' expects a single document, got ${newResults.length}. Use 'fleet' mode for multiple documents.`\n );\n }\n }\n\n // Baseline evolution mode: compare two baseline documents\n if (comparisonMode === 'baselineEvolution') {\n const newDoc = Array.isArray(newResults) ? newResults[0]! : newResults;\n return diffBaselines(oldResults, newDoc, options);\n }\n\n // System drift mode: compare two system documents\n if (comparisonMode === 'systemDrift') {\n const newDoc = Array.isArray(newResults) ? newResults[0]! : newResults;\n return diffSystems(oldResults, newDoc, options);\n }\n\n // Fleet mode: compare reference against each system\n if (comparisonMode === 'fleet') {\n return diffFleet(oldResults, newResults, trackedFields, matchOpts);\n }\n\n // Non-fleet modes: newResults must be a single document\n const newDoc = Array.isArray(newResults) ? newResults[0]! : newResults;\n\n // Normalize v1 (InSpec exec-json) to v2 if needed\n const oldNormalized = normalizeToV2(oldResults);\n const newNormalized = normalizeToV2(newDoc);\n\n const oldTimestamp = oldNormalized['timestamp'] as string | undefined;\n const newTimestamp = newNormalized['timestamp'] as string | undefined;\n\n // Build sources metadata based on mode\n const sources = buildSources(comparisonMode, oldResults, newDoc, oldTimestamp, newTimestamp);\n\n // Compute baseline and requirement diffs\n const { baselineDiffs, requirementDiffs } = comparePair(\n oldNormalized, newNormalized, oldTimestamp, newTimestamp, trackedFields, matchOpts,\n );\n\n // Sort by id\n requirementDiffs.sort((a, b) => a.id.localeCompare(b.id));\n\n // Extract drift: unchanged requirements with metadata changes\n const drift = extractDrift(requirementDiffs);\n\n const comparison: HDFComparison = {\n formatVersion: '1.0.0',\n comparisonMode,\n timestamp: new Date().toISOString(),\n sources,\n matching: {\n primaryStrategy: resolveStrategyName(options),\n },\n summary: computeSummary(requirementDiffs),\n baselineDiffs,\n requirementDiffs,\n drift,\n };\n\n if (options?.validateOutput) {\n const result = validateComparison(comparison);\n // Safety net: diffHdf always produces valid output by construction.\n // This branch is unreachable in normal operation but guards against future regressions.\n /* c8 ignore start */\n if (!result.valid) {\n throw new Error(`Output validation failed: ${result.errors?.join(', ')}`);\n }\n /* c8 ignore stop */\n }\n\n return comparison;\n}\n\n/**\n * Build source metadata entries based on comparison mode.\n */\nfunction buildSources(\n mode: 'temporal' | 'baseline' | 'multiSource',\n oldDoc: Record<string, unknown>,\n newDoc: Record<string, unknown>,\n oldTimestamp?: string,\n newTimestamp?: string,\n): Source[] {\n switch (mode) {\n case 'baseline':\n return [\n { role: 'golden', label: 'Golden baseline', assessmentTimestamp: oldTimestamp },\n { role: 'new', label: 'Current scan', assessmentTimestamp: newTimestamp },\n ];\n\n case 'multiSource': {\n const oldLabel = extractDataSourceLabel(oldDoc) ?? 'Old evaluation';\n const newLabel = extractDataSourceLabel(newDoc) ?? 'New evaluation';\n return [\n { role: 'old', label: oldLabel, assessmentTimestamp: oldTimestamp },\n { role: 'new', label: newLabel, assessmentTimestamp: newTimestamp },\n ];\n }\n\n case 'temporal':\n default:\n return [\n { role: 'old', label: 'Old evaluation', assessmentTimestamp: oldTimestamp },\n { role: 'new', label: 'New evaluation', assessmentTimestamp: newTimestamp },\n ];\n }\n}\n\n/**\n * Fleet mode: compare a reference document against one or more system documents.\n * Each system is compared pairwise against the reference; all diffs are collected\n * into a single result with `sourceIndex` set on each RequirementDiff.\n */\nfunction diffFleet(\n referenceDoc: Record<string, unknown>,\n newResults: Record<string, unknown> | Record<string, unknown>[],\n trackedFields: string[],\n matchOpts: MatchOptions,\n): HDFComparison {\n const systems = Array.isArray(newResults) ? newResults : [newResults];\n\n const refNormalized = normalizeToV2(referenceDoc);\n const refTimestamp = refNormalized['timestamp'] as string | undefined;\n\n // Build sources, compare each system against the reference, and collect diffs\n // in a single pass — each system document is normalized exactly once.\n const sources: Source[] = [\n { role: 'reference', label: 'Reference', assessmentTimestamp: refTimestamp },\n ];\n const allRequirementDiffs: RequirementDiff[] = [];\n const allBaselineDiffs: BaselineDiff[] = [];\n // Deduplicate baseline diffs by name: first-wins. In fleet mode, every system\n // is compared against the same reference, so the first occurrence of a\n // BaselineDiff for a given baseline name is representative. BaselineDiff does\n // not carry a sourceIndex in v1 of the schema, so per-system baseline tracking\n // is deferred to a future version.\n const seenBaselineNames = new Set<string>();\n\n for (let i = 0; i < systems.length; i++) {\n const sysNormalized = normalizeToV2(systems[i]!);\n const sysTimestamp = sysNormalized['timestamp'] as string | undefined;\n const sourceIndex = i + 1;\n\n // Build the source entry for this system\n sources.push({\n role: 'system',\n label: `System ${sourceIndex}`,\n assessmentTimestamp: sysTimestamp,\n });\n\n const { baselineDiffs, requirementDiffs } = comparePair(\n refNormalized, sysNormalized, refTimestamp, sysTimestamp, trackedFields, matchOpts,\n );\n\n // Tag each requirement diff with its source index\n for (const rd of requirementDiffs) {\n rd.sourceIndex = sourceIndex;\n allRequirementDiffs.push(rd);\n }\n\n // Collect baseline diffs (first-wins dedup; see comment above)\n for (const bd of baselineDiffs) {\n if (!seenBaselineNames.has(bd.name)) {\n seenBaselineNames.add(bd.name);\n allBaselineDiffs.push(bd);\n }\n }\n }\n\n // Sort by id, then by sourceIndex\n allRequirementDiffs.sort((a, b) => {\n const idCmp = a.id.localeCompare(b.id);\n if (idCmp !== 0) return idCmp;\n /* c8 ignore next -- sourceIndex is always set in fleet mode; ?? 0 is defensive typing */\n return (a.sourceIndex ?? 0) - (b.sourceIndex ?? 0);\n });\n\n // Extract drift: unchanged requirements with metadata changes\n const drift = extractDrift(allRequirementDiffs);\n\n return {\n formatVersion: '1.0.0',\n comparisonMode: 'fleet',\n timestamp: new Date().toISOString(),\n sources,\n matching: {\n primaryStrategy: matchOpts.strategy ?? 'exactId',\n },\n summary: computeSummary(allRequirementDiffs),\n baselineDiffs: allBaselineDiffs,\n requirementDiffs: allRequirementDiffs,\n drift,\n };\n}\n\n/**\n * Extract drift entries from requirement diffs.\n *\n * Drift = requirements whose effective status is unchanged but whose metadata\n * changed (tags, descriptions, impact score, etc.). These are the \"silent\"\n * changes that don't affect pass/fail outcome but still matter for auditing.\n *\n * Returns shallow copies so drift entries are independent of requirementDiffs.\n */\nexport function extractDrift(requirementDiffs: RequirementDiff[]): RequirementDiff[] {\n return requirementDiffs\n .filter(r => r.state === 'unchanged' && r.changeReasons.length > 0)\n .map(r => ({ ...r }));\n}\n\n/**\n * Core pairwise comparison between two normalized HDF documents.\n * Returns baseline diffs and requirement diffs without sorting or wrapping.\n *\n * Uses the pluggable matching system to pair requirements between evaluations.\n */\nfunction comparePair(\n oldNormalized: Record<string, unknown>,\n newNormalized: Record<string, unknown>,\n oldTimestamp: string | undefined,\n newTimestamp: string | undefined,\n trackedFields: string[],\n matchOpts: MatchOptions,\n): { baselineDiffs: BaselineDiff[]; requirementDiffs: RequirementDiff[] } {\n const oldBaselines = (oldNormalized['baselines'] as BaselineLike[] | undefined) ?? [];\n const newBaselines = (newNormalized['baselines'] as BaselineLike[] | undefined) ?? [];\n\n // Build baseline maps by name\n const oldBaselineMap = new Map<string, BaselineLike>();\n for (const b of oldBaselines) {\n oldBaselineMap.set(b.name, b);\n }\n const newBaselineMap = new Map<string, BaselineLike>();\n for (const b of newBaselines) {\n newBaselineMap.set(b.name, b);\n }\n\n // Compute baseline diffs\n const allBaselineNames = new Set([...oldBaselineMap.keys(), ...newBaselineMap.keys()]);\n const baselineDiffs: BaselineDiff[] = [];\n\n for (const name of allBaselineNames) {\n const oldB = oldBaselineMap.get(name);\n const newB = newBaselineMap.get(name);\n\n if (oldB && newB) {\n const versionChanged = oldB.version !== newB.version;\n baselineDiffs.push({\n name,\n oldVersion: oldB.version,\n newVersion: newB.version,\n state: versionChanged ? 'updated' : 'unchanged',\n });\n } else if (oldB && !newB) {\n baselineDiffs.push({\n name,\n oldVersion: oldB.version,\n state: 'absent',\n });\n } else if (!oldB && newB) {\n baselineDiffs.push({\n name,\n newVersion: newB.version,\n state: 'new',\n });\n }\n }\n\n // Collect all requirements across all baselines\n const oldReqs: Record<string, unknown>[] = [];\n for (const baseline of oldBaselines) {\n for (const req of baseline.requirements) {\n oldReqs.push(req as unknown as Record<string, unknown>);\n }\n }\n const newReqs: Record<string, unknown>[] = [];\n for (const baseline of newBaselines) {\n for (const req of baseline.requirements) {\n newReqs.push(req as unknown as Record<string, unknown>);\n }\n }\n\n // Use the matching system to pair requirements\n const matchResult = matchRequirements(oldReqs, newReqs, matchOpts);\n\n // Build requirement diffs from match results\n const requirementDiffs: RequirementDiff[] = [];\n\n // Matched pairs\n for (const pair of matchResult.matched) {\n const oldReq = pair.oldReq as RequirementLike;\n const newReq = pair.newReq as RequirementLike;\n /* c8 ignore next -- id is always a string on RequirementLike; ?? is defensive typing */\n const id = (newReq.id ?? oldReq.id) as string;\n\n const oldStatus = computeEffectiveStatus(\n oldReq as unknown as Record<string, unknown>,\n oldTimestamp,\n );\n const newStatus = computeEffectiveStatus(\n newReq as unknown as Record<string, unknown>,\n newTimestamp,\n );\n\n const diffState = classifyDiffStatus(oldStatus, newStatus);\n const changeReasons = classifyChangeReasons(\n oldReq as unknown as Record<string, unknown>,\n newReq as unknown as Record<string, unknown>,\n oldTimestamp,\n newTimestamp,\n );\n\n const fieldChanges = computeFieldChanges(oldReq, newReq, trackedFields);\n\n requirementDiffs.push({\n id,\n title: newReq.title ?? oldReq.title,\n state: diffState,\n oldEffectiveStatus: oldStatus,\n newEffectiveStatus: newStatus,\n changeReasons,\n oldImpact: oldReq.impact,\n newImpact: newReq.impact,\n fieldChanges,\n before: oldReq as unknown as Record<string, unknown>,\n after: newReq as unknown as Record<string, unknown>,\n matchStrategy: pair.strategy,\n matchConfidence: roundConfidence(pair.confidence),\n });\n }\n\n // Unmatched old requirements (absent)\n for (const req of matchResult.unmatchedOld) {\n const oldReq = req as RequirementLike;\n const id = oldReq.id as string;\n const oldStatus = computeEffectiveStatus(\n oldReq as unknown as Record<string, unknown>,\n oldTimestamp,\n );\n requirementDiffs.push({\n id,\n title: oldReq.title,\n state: 'absent',\n oldEffectiveStatus: oldStatus,\n changeReasons: [],\n oldImpact: oldReq.impact,\n fieldChanges: [],\n before: oldReq as unknown as Record<string, unknown>,\n after: null,\n });\n }\n\n // Unmatched new requirements (new)\n for (const req of matchResult.unmatchedNew) {\n const newReq = req as RequirementLike;\n const id = newReq.id as string;\n const newStatus = computeEffectiveStatus(\n newReq as unknown as Record<string, unknown>,\n newTimestamp,\n );\n requirementDiffs.push({\n id,\n title: newReq.title,\n state: 'new',\n newEffectiveStatus: newStatus,\n changeReasons: [],\n newImpact: newReq.impact,\n fieldChanges: [],\n before: null,\n after: newReq as unknown as Record<string, unknown>,\n });\n }\n\n return { baselineDiffs, requirementDiffs };\n}\n\n/** Field names handled by dedicated CVE-ecosystem diff handlers (not generic JSON compare). */\nconst CVE_ECOSYSTEM_FIELDS = new Set(['cvss', 'epss', 'kev', 'cwe', 'affectedPackages']);\n\n/**\n * Compute field-level changes for tracked fields between two requirements.\n * Uses JSON Patch-like op/path format.\n *\n * Always runs the CVE-ecosystem handlers (cvss, epss, kev, cwe, affectedPackages)\n * in addition to whatever scalar fields are in trackedFields, since these\n * structured types need richer diff than generic JSON comparison provides.\n */\nexport function computeFieldChanges(\n oldReq: RequirementLike,\n newReq: RequirementLike,\n trackedFields: string[],\n): FieldChange[] {\n const changes: FieldChange[] = [];\n\n for (const field of trackedFields) {\n // CVE-ecosystem fields are handled below by dedicated handlers\n if (CVE_ECOSYSTEM_FIELDS.has(field)) continue;\n\n const oldVal = oldReq[field];\n const newVal = newReq[field];\n\n // Deep comparison for objects/arrays\n if (JSON.stringify(oldVal) !== JSON.stringify(newVal)) {\n if (oldVal === undefined && newVal !== undefined) {\n changes.push({\n op: 'add',\n path: field,\n newValue: newVal,\n });\n } else if (oldVal !== undefined && newVal === undefined) {\n changes.push({\n op: 'remove',\n path: field,\n oldValue: oldVal,\n });\n } else {\n changes.push({\n op: 'replace',\n path: field,\n oldValue: oldVal,\n newValue: newVal,\n });\n }\n }\n }\n\n // Always run CVE-ecosystem handlers — these fields are part of the v3.x\n // Evaluated_Requirement structured types and need typed diffing regardless\n // of the trackedFields setting.\n changes.push(...diffCvssArray(oldReq['cvss'], newReq['cvss']));\n changes.push(...diffEpss(oldReq['epss'], newReq['epss']));\n changes.push(...diffKev(oldReq['kev'], newReq['kev']));\n changes.push(...diffCweSet(oldReq['cwe'], newReq['cwe']));\n changes.push(...diffAffectedPackages(oldReq['affectedPackages'], newReq['affectedPackages']));\n\n return changes;\n}\n\n// ── CVE-ecosystem diff handlers ─────────────────────────────────────────\n\ninterface CvssEntry {\n source?: string;\n baseScore?: number;\n baseSeverity?: string;\n baseVector?: string;\n threatScore?: number;\n threatVector?: string;\n environmentalScore?: number;\n environmentalVector?: string;\n supplementalVector?: string;\n [key: string]: unknown;\n}\n\nconst CVSS_VECTOR_FIELDS = [\n 'baseVector',\n 'threatVector',\n 'environmentalVector',\n 'supplementalVector',\n] as const;\n\n/**\n * Parse a CVSS vector string into a map of metric-code → value.\n *\n * Accepts both v3.x (\"CVSS:3.1/AV:N/AC:L/...\") and v4.0 (\"CVSS:4.0/AV:N/...\")\n * shapes, plus partial vectors that omit the version prefix (e.g., the\n * `threatVector` field is conventionally just the threat metrics).\n *\n * Returns `null` for inputs that don't look like CVSS vectors so callers\n * can fall back to a scalar string compare.\n *\n * Delegates to `parseCvssVector` from `@mitre/hdf-utilities` but adapts the\n * return shape: returns null for empty/unparseable inputs so call sites can\n * fall back to scalar string compare.\n */\nfunction parseCvssVector(vec: string): { version?: string; metrics: Map<string, string> } | null {\n if (typeof vec !== 'string' || vec.length === 0) return null;\n const parsed = parseCvssVectorUtil(vec);\n if (parsed.metrics.size === 0) return null;\n return {\n version: parsed.version === 'unknown' ? undefined : parsed.version,\n metrics: parsed.metrics,\n };\n}\n\n/**\n * Diff a single pair of cvss entries (same source). Emits per-field changes\n * including decomposed per-metric vector diffs.\n */\nfunction diffCvssEntry(\n source: string,\n oldEntry: CvssEntry,\n newEntry: CvssEntry,\n): FieldChange[] {\n const changes: FieldChange[] = [];\n const allKeys = new Set([...Object.keys(oldEntry), ...Object.keys(newEntry)]);\n\n for (const key of allKeys) {\n if (key === 'source') continue;\n const oldVal = oldEntry[key];\n const newVal = newEntry[key];\n if (JSON.stringify(oldVal) === JSON.stringify(newVal)) continue;\n\n // Vector fields: decompose into per-metric records when both parse cleanly\n if ((CVSS_VECTOR_FIELDS as readonly string[]).includes(key)) {\n if (typeof oldVal === 'string' && typeof newVal === 'string') {\n const oldParsed = parseCvssVector(oldVal);\n const newParsed = parseCvssVector(newVal);\n if (oldParsed && newParsed) {\n const metricKeys = new Set<string>([\n ...oldParsed.metrics.keys(), ...newParsed.metrics.keys(),\n ]);\n for (const m of metricKeys) {\n const o = oldParsed.metrics.get(m);\n const n = newParsed.metrics.get(m);\n if (o === n) continue;\n if (o === undefined && n !== undefined) {\n changes.push({ op: 'add', path: `cvss[${source}].${key}.${m}`, newValue: n });\n } else if (o !== undefined && n === undefined) {\n changes.push({ op: 'remove', path: `cvss[${source}].${key}.${m}`, oldValue: o });\n } else {\n changes.push({\n op: 'replace', path: `cvss[${source}].${key}.${m}`, oldValue: o, newValue: n,\n });\n }\n }\n continue;\n }\n } else if (oldVal === undefined && typeof newVal === 'string') {\n // Whole vector added — decompose into per-metric add records\n const parsed = parseCvssVector(newVal);\n if (parsed) {\n for (const [m, v] of parsed.metrics) {\n changes.push({ op: 'add', path: `cvss[${source}].${key}.${m}`, newValue: v });\n }\n continue;\n }\n } else if (typeof oldVal === 'string' && newVal === undefined) {\n const parsed = parseCvssVector(oldVal);\n if (parsed) {\n for (const [m, v] of parsed.metrics) {\n changes.push({ op: 'remove', path: `cvss[${source}].${key}.${m}`, oldValue: v });\n }\n continue;\n }\n }\n // Fall through to scalar replace for unparseable / mixed-type cases\n }\n\n if (oldVal === undefined) {\n changes.push({ op: 'add', path: `cvss[${source}].${key}`, newValue: newVal });\n } else if (newVal === undefined) {\n changes.push({ op: 'remove', path: `cvss[${source}].${key}`, oldValue: oldVal });\n } else {\n changes.push({\n op: 'replace', path: `cvss[${source}].${key}`, oldValue: oldVal, newValue: newVal,\n });\n }\n }\n\n return changes;\n}\n\n/**\n * Diff old vs new cvss[] arrays. Entries are matched by `source` (CVE ID\n * or scoring authority); added/removed entries emit whole-entry add/remove\n * records; matched pairs are decomposed via diffCvssEntry.\n */\nfunction diffCvssArray(oldField: unknown, newField: unknown): FieldChange[] {\n const oldArr = Array.isArray(oldField) ? (oldField as CvssEntry[]) : [];\n const newArr = Array.isArray(newField) ? (newField as CvssEntry[]) : [];\n if (oldArr.length === 0 && newArr.length === 0) return [];\n\n const oldBySource = new Map<string, CvssEntry>();\n for (const e of oldArr) {\n if (typeof e?.source === 'string') oldBySource.set(e.source, e);\n }\n const newBySource = new Map<string, CvssEntry>();\n for (const e of newArr) {\n if (typeof e?.source === 'string') newBySource.set(e.source, e);\n }\n\n const changes: FieldChange[] = [];\n const allSources = new Set([...oldBySource.keys(), ...newBySource.keys()]);\n for (const source of allSources) {\n const o = oldBySource.get(source);\n const n = newBySource.get(source);\n if (o && !n) {\n changes.push({ op: 'remove', path: `cvss[${source}]`, oldValue: o });\n } else if (!o && n) {\n changes.push({ op: 'add', path: `cvss[${source}]`, newValue: n });\n } else if (o && n) {\n changes.push(...diffCvssEntry(source, o, n));\n }\n }\n return changes;\n}\n\n/** Diff the optional `epss` object (score, percentile, date). */\nfunction diffEpss(oldField: unknown, newField: unknown): FieldChange[] {\n if (oldField === undefined && newField === undefined) return [];\n if (oldField === undefined) {\n return [{ op: 'add', path: 'epss', newValue: newField }];\n }\n if (newField === undefined) {\n return [{ op: 'remove', path: 'epss', oldValue: oldField }];\n }\n if (typeof oldField !== 'object' || typeof newField !== 'object' || oldField === null || newField === null) {\n if (JSON.stringify(oldField) === JSON.stringify(newField)) return [];\n return [{ op: 'replace', path: 'epss', oldValue: oldField, newValue: newField }];\n }\n const oldObj = oldField as Record<string, unknown>;\n const newObj = newField as Record<string, unknown>;\n const changes: FieldChange[] = [];\n const allKeys = new Set([...Object.keys(oldObj), ...Object.keys(newObj)]);\n for (const key of allKeys) {\n const o = oldObj[key];\n const n = newObj[key];\n if (JSON.stringify(o) === JSON.stringify(n)) continue;\n if (o === undefined) {\n changes.push({ op: 'add', path: `epss.${key}`, newValue: n });\n } else if (n === undefined) {\n changes.push({ op: 'remove', path: `epss.${key}`, oldValue: o });\n } else {\n changes.push({ op: 'replace', path: `epss.${key}`, oldValue: o, newValue: n });\n }\n }\n return changes;\n}\n\n/**\n * Diff the optional `kev` object. Flips of `inKev` from false→true (or\n * fresh add with `inKev: true`) get an annotated `message` field calling\n * out the CISA KEV catalog inclusion.\n */\nfunction diffKev(oldField: unknown, newField: unknown): FieldChange[] {\n if (oldField === undefined && newField === undefined) return [];\n if (oldField === undefined) {\n const change: FieldChange = { op: 'add', path: 'kev', newValue: newField };\n const nObj = newField as Record<string, unknown> | null;\n if (nObj && nObj['inKev'] === true) {\n const dateAdded = typeof nObj['dateAdded'] === 'string' ? nObj['dateAdded'] : 'unknown date';\n change.message = `Newly added to CISA KEV catalog as of ${dateAdded}`;\n }\n return [change];\n }\n if (newField === undefined) {\n return [{ op: 'remove', path: 'kev', oldValue: oldField }];\n }\n if (typeof oldField !== 'object' || typeof newField !== 'object' || oldField === null || newField === null) {\n if (JSON.stringify(oldField) === JSON.stringify(newField)) return [];\n return [{ op: 'replace', path: 'kev', oldValue: oldField, newValue: newField }];\n }\n const oldObj = oldField as Record<string, unknown>;\n const newObj = newField as Record<string, unknown>;\n const changes: FieldChange[] = [];\n const allKeys = new Set([...Object.keys(oldObj), ...Object.keys(newObj)]);\n for (const key of allKeys) {\n const o = oldObj[key];\n const n = newObj[key];\n if (JSON.stringify(o) === JSON.stringify(n)) continue;\n let change: FieldChange;\n if (o === undefined) {\n change = { op: 'add', path: `kev.${key}`, newValue: n };\n } else if (n === undefined) {\n change = { op: 'remove', path: `kev.${key}`, oldValue: o };\n } else {\n change = { op: 'replace', path: `kev.${key}`, oldValue: o, newValue: n };\n }\n // Annotate the significant false→true inKev flip\n if (key === 'inKev' && o === false && n === true) {\n const dateAdded = typeof newObj['dateAdded'] === 'string' ? newObj['dateAdded'] : 'unknown date';\n change.message = `Newly added to CISA KEV catalog as of ${dateAdded}`;\n }\n changes.push(change);\n }\n return changes;\n}\n\n/** Diff the `cwe[]` field as a set — order does not matter. */\nfunction diffCweSet(oldField: unknown, newField: unknown): FieldChange[] {\n const toSet = (v: unknown): Set<string> => {\n if (!Array.isArray(v)) return new Set();\n return new Set(v.filter((x): x is string => typeof x === 'string'));\n };\n const oldSet = toSet(oldField);\n const newSet = toSet(newField);\n if (oldSet.size === 0 && newSet.size === 0) return [];\n const changes: FieldChange[] = [];\n for (const c of newSet) {\n if (!oldSet.has(c)) changes.push({ op: 'add', path: 'cwe', newValue: c });\n }\n for (const c of oldSet) {\n if (!newSet.has(c)) changes.push({ op: 'remove', path: 'cwe', oldValue: c });\n }\n return changes;\n}\n\ninterface AffectedPackage {\n name?: string;\n version?: string;\n cpe?: string;\n purl?: string;\n fixedInVersion?: string;\n [key: string]: unknown;\n}\n\n/** Build the natural key for an AffectedPackage: `name@version`. */\nfunction packageKey(pkg: AffectedPackage): string | null {\n const name = pkg?.name;\n const version = pkg?.version;\n if (typeof name !== 'string' || name.length === 0) return null;\n if (typeof version !== 'string' || version.length === 0) return null;\n return `${name}@${version}`;\n}\n\n/**\n * Diff a single pair of affectedPackages entries (matched by name+version).\n * Emits per-field changes for cpe / purl / fixedInVersion and any other\n * non-key fields that differ.\n */\nfunction diffAffectedPackageEntry(\n key: string,\n oldPkg: AffectedPackage,\n newPkg: AffectedPackage,\n): FieldChange[] {\n const changes: FieldChange[] = [];\n const allKeys = new Set([...Object.keys(oldPkg), ...Object.keys(newPkg)]);\n for (const k of allKeys) {\n if (k === 'name' || k === 'version') continue; // part of the match key\n const o = oldPkg[k];\n const n = newPkg[k];\n if (JSON.stringify(o) === JSON.stringify(n)) continue;\n if (o === undefined) {\n changes.push({ op: 'add', path: `affectedPackages[${key}].${k}`, newValue: n });\n } else if (n === undefined) {\n changes.push({ op: 'remove', path: `affectedPackages[${key}].${k}`, oldValue: o });\n } else {\n changes.push({\n op: 'replace', path: `affectedPackages[${key}].${k}`, oldValue: o, newValue: n,\n });\n }\n }\n return changes;\n}\n\n/**\n * Diff old vs new affectedPackages[] arrays. Entries are matched by the\n * `name@version` tuple; added/removed packages emit whole-entry records;\n * matched pairs are decomposed via diffAffectedPackageEntry.\n */\nfunction diffAffectedPackages(oldField: unknown, newField: unknown): FieldChange[] {\n const oldArr = Array.isArray(oldField) ? (oldField as AffectedPackage[]) : [];\n const newArr = Array.isArray(newField) ? (newField as AffectedPackage[]) : [];\n if (oldArr.length === 0 && newArr.length === 0) return [];\n\n const oldByKey = new Map<string, AffectedPackage>();\n for (const p of oldArr) {\n const k = packageKey(p);\n if (k) oldByKey.set(k, p);\n }\n const newByKey = new Map<string, AffectedPackage>();\n for (const p of newArr) {\n const k = packageKey(p);\n if (k) newByKey.set(k, p);\n }\n\n const changes: FieldChange[] = [];\n const allKeys = new Set([...oldByKey.keys(), ...newByKey.keys()]);\n for (const key of allKeys) {\n const o = oldByKey.get(key);\n const n = newByKey.get(key);\n if (o && !n) {\n changes.push({ op: 'remove', path: `affectedPackages[${key}]`, oldValue: o });\n } else if (!o && n) {\n changes.push({ op: 'add', path: `affectedPackages[${key}]`, newValue: n });\n } else if (o && n) {\n changes.push(...diffAffectedPackageEntry(key, o, n));\n }\n }\n return changes;\n}\n\n/**\n * Detect whether a document is a baseline (not results).\n * Baselines have `requirements` at the top level and lack `baselines`, `targets`, and `statistics`.\n */\nfunction isBaselineDocument(doc: Record<string, unknown>): boolean {\n return (\n Array.isArray(doc['requirements']) &&\n !Array.isArray(doc['baselines']) &&\n !Array.isArray(doc['targets']) &&\n doc['statistics'] === undefined\n );\n}\n\n/** Default tracked fields for baseline evolution comparisons. */\nconst BASELINE_TRACKED_FIELDS = ['title', 'impact', 'descriptions', 'tags'];\n\n/**\n * Compare two HDF baseline documents and produce a structured comparison\n * showing requirement changes between baseline versions.\n *\n * Unlike diffHdf (which compares results/evaluations), this compares baseline\n * definitions — requirements without results. There is no status-based classification\n * (fixed/regressed); only metadata changes (title, impact, descriptions, tags) are tracked.\n */\nexport function diffBaselines(\n oldBaseline: Record<string, unknown>,\n newBaseline: Record<string, unknown>,\n options?: DiffOptions,\n): HDFComparison {\n const trackedFields = options?.trackedFields ?? BASELINE_TRACKED_FIELDS;\n const matchOpts = buildMatchOptions(options);\n\n // Extract requirements from baseline documents\n const oldReqs = (oldBaseline['requirements'] as RequirementLike[] | undefined) ?? [];\n const newReqs = (newBaseline['requirements'] as RequirementLike[] | undefined) ?? [];\n\n // Use the matching system to pair requirements\n const matchResult = matchRequirements(\n oldReqs as unknown as Record<string, unknown>[],\n newReqs as unknown as Record<string, unknown>[],\n matchOpts,\n );\n\n // Build requirement diffs from match results\n const requirementDiffs: RequirementDiff[] = [];\n\n // Matched pairs\n for (const pair of matchResult.matched) {\n const oldReq = pair.oldReq as RequirementLike;\n const newReq = pair.newReq as RequirementLike;\n const id = (newReq.id ?? oldReq.id) as string;\n\n const fieldChanges = computeFieldChanges(oldReq, newReq, trackedFields);\n\n // For baseline evolution, state is determined by metadata changes only\n const state: 'unchanged' | 'updated' = fieldChanges.length > 0 ? 'updated' : 'unchanged';\n\n // Determine change reasons for baseline evolution\n const changeReasons: Array<'impactChanged' | 'metadataChanged'> = [];\n if (oldReq.impact !== newReq.impact) {\n changeReasons.push('impactChanged');\n }\n const oldTags = JSON.stringify(oldReq['tags'] ?? {});\n const newTags = JSON.stringify(newReq['tags'] ?? {});\n const oldDescs = JSON.stringify(oldReq['descriptions'] ?? []);\n const newDescs = JSON.stringify(newReq['descriptions'] ?? []);\n const oldTitle = oldReq['title'] as string | undefined;\n const newTitle = newReq['title'] as string | undefined;\n if (oldTags !== newTags || oldDescs !== newDescs || oldTitle !== newTitle) {\n changeReasons.push('metadataChanged');\n }\n\n requirementDiffs.push({\n id,\n title: newReq.title ?? oldReq.title,\n state,\n changeReasons,\n oldImpact: oldReq.impact,\n newImpact: newReq.impact,\n fieldChanges,\n before: oldReq as unknown as Record<string, unknown>,\n after: newReq as unknown as Record<string, unknown>,\n matchStrategy: pair.strategy,\n matchConfidence: roundConfidence(pair.confidence),\n });\n }\n\n // Unmatched old requirements (absent)\n for (const req of matchResult.unmatchedOld) {\n const oldReq = req as RequirementLike;\n requirementDiffs.push({\n id: oldReq.id,\n title: oldReq.title,\n state: 'absent',\n changeReasons: [],\n oldImpact: oldReq.impact,\n fieldChanges: [],\n before: oldReq as unknown as Record<string, unknown>,\n after: null,\n });\n }\n\n // Unmatched new requirements (new)\n for (const req of matchResult.unmatchedNew) {\n const newReq = req as RequirementLike;\n requirementDiffs.push({\n id: newReq.id,\n title: newReq.title,\n state: 'new',\n changeReasons: [],\n newImpact: newReq.impact,\n fieldChanges: [],\n before: null,\n after: newReq as unknown as Record<string, unknown>,\n });\n }\n\n // Sort by id\n requirementDiffs.sort((a, b) => a.id.localeCompare(b.id));\n\n // Build baseline diff from top-level baseline metadata\n const oldName = oldBaseline['name'] as string | undefined ?? '';\n const newName = newBaseline['name'] as string | undefined ?? '';\n const oldVersion = oldBaseline['version'] as string | undefined;\n const newVersion = newBaseline['version'] as string | undefined;\n\n const baselineDiffs: BaselineDiff[] = [];\n const baselineName = newName || oldName;\n if (baselineName) {\n const versionChanged = oldVersion !== newVersion;\n baselineDiffs.push({\n name: baselineName,\n oldVersion,\n newVersion,\n state: versionChanged ? 'updated' : 'unchanged',\n });\n }\n\n // Build sources\n const sources: Source[] = [\n { role: 'old', label: oldVersion ? `${baselineName} ${oldVersion}` : baselineName || 'Old baseline' },\n { role: 'new', label: newVersion ? `${baselineName} ${newVersion}` : baselineName || 'New baseline' },\n ];\n\n const comparison: HDFComparison = {\n formatVersion: '1.0.0',\n comparisonMode: 'baselineEvolution',\n timestamp: new Date().toISOString(),\n sources,\n matching: {\n primaryStrategy: resolveStrategyName(options),\n },\n summary: computeSummary(requirementDiffs),\n baselineDiffs,\n requirementDiffs,\n };\n\n if (options?.validateOutput) {\n const result = validateComparison(comparison);\n /* c8 ignore start */\n if (!result.valid) {\n throw new Error(`Output validation failed: ${result.errors?.join(', ')}`);\n }\n /* c8 ignore stop */\n }\n\n return comparison;\n}\n\n/**\n * Detect whether a document is a system document (has components[] but no baselines/requirements).\n */\nfunction isSystemDocument(doc: Record<string, unknown>): boolean {\n return (\n Array.isArray(doc['components']) &&\n !Array.isArray(doc['baselines']) &&\n !Array.isArray(doc['requirements']) &&\n doc['statistics'] === undefined\n );\n}\n\n/** Fields tracked for system-level field changes. */\nconst SYSTEM_TOP_LEVEL_FIELDS = ['authorizationStatus', 'categorizationLevel', 'description'];\n\n/** Fields tracked for component-level field changes. */\nconst COMPONENT_TRACKED_FIELDS = [\n 'type', 'description', 'baselineRefs', 'inputOverrides', 'boms', 'integrity', 'targetSelector',\n];\n\n/**\n * Compare two HDF system documents and produce a structured comparison\n * showing component-level changes between system versions.\n *\n * Components are matched by componentId (UUID) when available, falling back\n * to exact name matching. Top-level system fields, data flows, and embedded\n * SBOMs are also compared.\n */\nexport function diffSystems(\n oldSystem: Record<string, unknown>,\n newSystem: Record<string, unknown>,\n options?: DiffOptions,\n): HDFComparison {\n const oldComponents = (oldSystem['components'] as Record<string, unknown>[] | undefined) ?? [];\n const newComponents = (newSystem['components'] as Record<string, unknown>[] | undefined) ?? [];\n\n // Match components: prefer componentId, fall back to name\n const pairs = matchComponents(oldComponents, newComponents);\n const componentDiffs: ComponentDiff[] = [];\n\n for (const { oldComp, newComp, name } of pairs) {\n if (oldComp && newComp) {\n const fieldChanges = computeComponentFieldChanges(oldComp, newComp, COMPONENT_TRACKED_FIELDS);\n const state = fieldChanges.length > 0 ? 'updated' : 'unchanged';\n componentDiffs.push({ name, state, before: oldComp, after: newComp, fieldChanges });\n } else if (oldComp && !newComp) {\n componentDiffs.push({ name, state: 'absent', before: oldComp, after: null, fieldChanges: [] });\n } else if (!oldComp && newComp) {\n componentDiffs.push({ name, state: 'new', before: null, after: newComp, fieldChanges: [] });\n }\n }\n\n componentDiffs.sort((a, b) => a.name.localeCompare(b.name));\n\n // Compare top-level system fields\n const systemFieldChanges = computeComponentFieldChanges(\n oldSystem, newSystem, SYSTEM_TOP_LEVEL_FIELDS,\n );\n\n // Build summary counts based on component diffs\n const counts = { new: 0, absent: 0, unchanged: 0, updated: 0 };\n for (const cd of componentDiffs) {\n counts[cd.state]++;\n }\n\n const oldName = oldSystem['name'] as string | undefined ?? '';\n const newName = newSystem['name'] as string | undefined ?? '';\n const systemName = newName || oldName;\n\n const sources: Source[] = [\n { role: 'old', label: systemName ? `${systemName} (old)` : 'Old system' },\n { role: 'new', label: systemName ? `${systemName} (new)` : 'New system' },\n ];\n\n const comparison: HDFComparison = {\n formatVersion: '1.0.0',\n comparisonMode: 'systemDrift',\n timestamp: new Date().toISOString(),\n sources,\n summary: {\n total: pairs.length,\n matchedCount: counts.unchanged + counts.updated,\n unmatchedOldCount: counts.absent,\n unmatchedNewCount: counts.new,\n new: counts.new,\n absent: counts.absent,\n unchanged: counts.unchanged,\n updated: counts.updated,\n fixed: 0,\n regressed: 0,\n },\n baselineDiffs: [],\n requirementDiffs: [],\n componentDiffs,\n };\n\n // Extensions: system field changes + data flow changes\n const extensions: Record<string, unknown> = {};\n if (systemFieldChanges.length > 0) {\n extensions['systemFieldChanges'] = systemFieldChanges;\n }\n const dataFlowChanges = diffDataFlows(oldSystem, newSystem);\n if (dataFlowChanges.length > 0) {\n extensions['dataFlowChanges'] = dataFlowChanges;\n }\n if (Object.keys(extensions).length > 0) {\n comparison.extensions = extensions;\n }\n\n if (options?.validateOutput) {\n const result = validateComparison(comparison);\n /* c8 ignore start */\n if (!result.valid) {\n throw new Error(`Output validation failed: ${result.errors?.join(', ')}`);\n }\n /* c8 ignore stop */\n }\n\n return comparison;\n}\n\ninterface ComponentPair {\n name: string;\n oldComp: Record<string, unknown> | undefined;\n newComp: Record<string, unknown> | undefined;\n}\n\n/**\n * Match old and new components by componentId (when available) or name.\n */\nfunction matchComponents(\n oldComponents: Record<string, unknown>[],\n newComponents: Record<string, unknown>[],\n): ComponentPair[] {\n const matched = new Set<number>(); // indices of matched new components\n const pairs: ComponentPair[] = [];\n\n // First pass: match by componentId\n const newById = new Map<string, number>();\n for (let i = 0; i < newComponents.length; i++) {\n const id = newComponents[i]!['componentId'] as string | undefined;\n if (id) newById.set(id, i);\n }\n\n const oldMatched = new Set<number>();\n for (let i = 0; i < oldComponents.length; i++) {\n const oldId = oldComponents[i]!['componentId'] as string | undefined;\n if (oldId && newById.has(oldId)) {\n const ni = newById.get(oldId)!;\n const newComp = newComponents[ni]!;\n pairs.push({\n name: (newComp['name'] as string) || (oldComponents[i]!['name'] as string) || oldId,\n oldComp: oldComponents[i],\n newComp,\n });\n matched.add(ni);\n oldMatched.add(i);\n }\n }\n\n // Second pass: match remaining by name\n const newByName = new Map<string, number>();\n for (let i = 0; i < newComponents.length; i++) {\n if (matched.has(i)) continue;\n const name = newComponents[i]!['name'] as string;\n if (name) newByName.set(name, i);\n }\n\n for (let i = 0; i < oldComponents.length; i++) {\n if (oldMatched.has(i)) continue;\n const name = oldComponents[i]!['name'] as string;\n if (name && newByName.has(name)) {\n const ni = newByName.get(name)!;\n pairs.push({ name, oldComp: oldComponents[i], newComp: newComponents[ni] });\n matched.add(ni);\n oldMatched.add(i);\n newByName.delete(name);\n }\n }\n\n // Unmatched old → absent\n for (let i = 0; i < oldComponents.length; i++) {\n if (oldMatched.has(i)) continue;\n const name = (oldComponents[i]!['name'] as string) || `component-${i}`;\n pairs.push({ name, oldComp: oldComponents[i], newComp: undefined });\n }\n\n // Unmatched new → new\n for (let i = 0; i < newComponents.length; i++) {\n if (matched.has(i)) continue;\n const name = (newComponents[i]!['name'] as string) || `component-${i}`;\n pairs.push({ name, oldComp: undefined, newComp: newComponents[i] });\n }\n\n return pairs;\n}\n\n/**\n * Diff data flows between two system documents. Flows are keyed by from+to.\n */\nfunction diffDataFlows(\n oldSystem: Record<string, unknown>,\n newSystem: Record<string, unknown>,\n): Array<{ state: string; flow: Record<string, unknown> }> {\n const oldFlows = (oldSystem['dataFlows'] as Record<string, unknown>[] | undefined) ?? [];\n const newFlows = (newSystem['dataFlows'] as Record<string, unknown>[] | undefined) ?? [];\n\n if (oldFlows.length === 0 && newFlows.length === 0) return [];\n\n const flowKey = (f: Record<string, unknown>): string => {\n const from = f['from'] as string ?? '';\n const to = typeof f['to'] === 'string' ? f['to'] as string : JSON.stringify(f['to']);\n return `${from}→${to}`;\n };\n\n const oldMap = new Map<string, Record<string, unknown>>();\n for (const f of oldFlows) oldMap.set(flowKey(f), f);\n const newMap = new Map<string, Record<string, unknown>>();\n for (const f of newFlows) newMap.set(flowKey(f), f);\n\n const allKeys = new Set([...oldMap.keys(), ...newMap.keys()]);\n const changes: Array<{ state: string; flow: Record<string, unknown> }> = [];\n\n for (const key of allKeys) {\n const oldF = oldMap.get(key);\n const newF = newMap.get(key);\n if (oldF && newF) {\n if (JSON.stringify(oldF) !== JSON.stringify(newF)) {\n changes.push({ state: 'updated', flow: newF });\n }\n } else if (oldF && !newF) {\n changes.push({ state: 'removed', flow: oldF });\n } else if (!oldF && newF) {\n changes.push({ state: 'added', flow: newF });\n }\n }\n\n return changes;\n}\n\n/**\n * Compute field-level changes for component or system fields.\n * Uses JSON Patch-like op/path format.\n */\nfunction computeComponentFieldChanges(\n oldObj: Record<string, unknown>,\n newObj: Record<string, unknown>,\n trackedFields: string[],\n): FieldChange[] {\n const changes: FieldChange[] = [];\n\n for (const field of trackedFields) {\n const oldVal = oldObj[field];\n const newVal = newObj[field];\n\n if (JSON.stringify(oldVal) !== JSON.stringify(newVal)) {\n if (oldVal === undefined && newVal !== undefined) {\n changes.push({ op: 'add', path: field, newValue: newVal });\n } else if (oldVal !== undefined && newVal === undefined) {\n changes.push({ op: 'remove', path: field, oldValue: oldVal });\n } else {\n changes.push({ op: 'replace', path: field, oldValue: oldVal, newValue: newVal });\n }\n }\n }\n\n return changes;\n}\n","import { governingOverrideIndex, sha256, type StatusOverrideInput } from '@mitre/hdf-utilities';\nimport { computeEffectiveStatus } from './status.js';\n\ninterface ImpactOverrideLike {\n value: number;\n}\n\ninterface OverrideLike {\n type?: string;\n status?: string;\n impact?: ImpactOverrideLike;\n appliedAt?: string;\n expiresAt: string;\n}\n\nexport interface EffectiveChecksum {\n algorithm: 'sha256';\n value: string;\n}\n\n/** Maps overrides onto the shared neutral selection shape (applied/expiry\n * window only; eligibility is passed separately). */\nfunction overrideWindows(overrides: readonly OverrideLike[]): StatusOverrideInput[] {\n return overrides.map((o) => ({ appliedAt: o.appliedAt, expiresAt: o.expiresAt }));\n}\n\n/**\n * Determine the effective impact of a requirement: the most recently applied\n * non-expired override carrying an impact value wins (the schema's definition\n * of effectiveImpact, selected by the shared governing helper); with no\n * overrides, a stored effectiveImpact field is honored; otherwise the base\n * impact. (Go parity: ComputeEffectiveImpact in hdf-diff/go/effective_checksum.go.)\n */\nexport function computeEffectiveImpact(\n requirement: Record<string, unknown>,\n referenceTimestamp?: string,\n): number {\n const baseImpact = (requirement['impact'] as number | undefined) ?? 0;\n const overrides = requirement['statusOverrides'] as OverrideLike[] | undefined;\n\n if (overrides && overrides.length > 0) {\n const i = governingOverrideIndex(\n overrideWindows(overrides),\n (idx) => overrides[idx]?.impact !== undefined,\n referenceTimestamp,\n );\n if (i >= 0) {\n return overrides[i]!.impact!.value;\n }\n return baseImpact;\n }\n\n const effectiveImpact = requirement['effectiveImpact'] as number | undefined;\n if (effectiveImpact !== undefined) {\n return effectiveImpact;\n }\n return baseImpact;\n}\n\n/**\n * Return the Override_Type of the governing (most recently applied\n * non-expired) override, a stored disposition field when no overrides are\n * present, or null. (Go parity: ComputeDisposition.)\n */\nexport function computeDisposition(\n requirement: Record<string, unknown>,\n referenceTimestamp?: string,\n): string | null {\n const overrides = requirement['statusOverrides'] as OverrideLike[] | undefined;\n\n if (overrides && overrides.length > 0) {\n const i = governingOverrideIndex(overrideWindows(overrides), () => true, referenceTimestamp);\n if (i >= 0) {\n return overrides[i]?.type ?? null;\n }\n return null;\n }\n\n const disposition = requirement['disposition'] as string | undefined;\n return disposition ?? null;\n}\n\n/**\n * Hash the resolved effective posture of a requirement: sha256 over the\n * canonical JSON {\"status\":<resolved>,\"impact\":<resolved>,\"disposition\":<type|null>}.\n * Flips exactly when the operative status, impact, or disposition changes;\n * stable under all other document churn. Byte-identical with the Go\n * implementation (ComputeEffectiveChecksum) — the key order of the canonical\n * object is part of the contract. Pass the document timestamp as\n * referenceTimestamp for determinism. A missing or unparseable reference\n * falls back to the wall clock inside the shared governing-override helper,\n * so callers that need reproducible output must always supply a valid\n * timestamp.\n */\nexport async function computeEffectiveChecksum(\n requirement: Record<string, unknown>,\n referenceTimestamp?: string,\n): Promise<EffectiveChecksum> {\n const canonical = JSON.stringify({\n status: computeEffectiveStatus(requirement, referenceTimestamp),\n impact: computeEffectiveImpact(requirement, referenceTimestamp),\n disposition: computeDisposition(requirement, referenceTimestamp),\n });\n return { algorithm: 'sha256', value: await sha256(canonical) };\n}\n","import {\n computeEffectiveChecksum,\n computeEffectiveImpact,\n type EffectiveChecksum,\n} from './effective-checksum.js';\nimport { computeEffectiveStatus, classifyChangeReasons, classifyDiffStatus } from './status.js';\nimport type { ChangeReason } from './types.js';\n\n/**\n * The reconciler's per-key last-value state (ADR-0005 §1): the minimal\n * posture a producer compares against to decide whether a requirement moved.\n * Go parity: KeyState in hdf-diff/go/change_event.go.\n */\nexport interface KeyState {\n effectiveStatus: string;\n effectiveImpact: number;\n checksum: EffectiveChecksum;\n}\n\n/**\n * Caller-injected envelope identity for an emitted event. Everything is\n * supplied by the caller — the kernel touches no wall clock and no RNG, so\n * identical inputs always produce identical events. referenceTimestamp\n * anchors override expiry (pass the new document's timestamp); timestamp is\n * the event's occurrence time (RFC 3339, trimmed UTC).\n */\nexport interface EventInputs {\n eventId: string;\n source: string;\n sequence: number;\n systemRef: string;\n componentId: string;\n requirementId: string;\n timestamp: string;\n referenceTimestamp: string;\n /** Prior observation's timestamp — enables overrideExpired detection across the window. */\n prevReferenceTimestamp?: string;\n schemaRef?: string;\n}\n\n/** Batch ChangeReason → event-vocabulary mapping; unmapped reasons are batch-only. */\nconst EVENT_REASON_FOR: Partial<Record<ChangeReason, string>> = {\n resultChanged: 'resultChanged',\n overrideAdded: 'overrideAdded',\n overrideExpired: 'overrideExpired',\n overrideRemoved: 'overrideRemoved',\n impactChanged: 'impactChanged',\n effectiveImpactChanged: 'impactChanged',\n};\n\nfunction classifyEventReasons(\n prev: KeyState,\n newReq: Record<string, unknown>,\n prevReq: Record<string, unknown> | null,\n inputs: EventInputs,\n): string[] {\n const reasons: string[] = [];\n const add = (r: string | undefined): void => {\n if (r && !reasons.includes(r)) reasons.push(r);\n };\n\n if (prevReq) {\n const prevRef = inputs.prevReferenceTimestamp ?? inputs.referenceTimestamp;\n for (const r of classifyChangeReasons(prevReq, newReq, prevRef, inputs.referenceTimestamp)) {\n add(EVENT_REASON_FOR[r]);\n }\n return reasons;\n }\n\n if (computeEffectiveImpact(newReq, inputs.referenceTimestamp) !== prev.effectiveImpact) {\n add('impactChanged');\n }\n return reasons;\n}\n\n/**\n * The pure detection kernel (ADR-0005): compare a requirement's resolved\n * posture against the stored last-value state and emit a\n * Requirement_Change_Event when it moved, or null when it did not.\n *\n * - prev null → state \"new\" (chain start: null before/priorChecksum)\n * - newReq null → state \"absent\" (after null, thin before preserved)\n * - checksum match → null (no event; the steady-state majority)\n * - otherwise → fixed/regressed/updated per the effective-status\n * transition, with the full after requirement as payload\n *\n * prevReq (optional) is the full prior requirement when the caller's\n * materialized state has it; it enables complete changeReasons\n * classification via the batch classifier, filtered to the event\n * vocabulary. Without it, only reasons provable from the thin state\n * (impactChanged) are emitted. Byte-parity with the Go kernel\n * (ChangeEventFromPrevious) is pinned by shared test vectors.\n */\nexport async function changeEventFromPrevious(\n prev: KeyState | null,\n newReq: Record<string, unknown> | null,\n prevReq: Record<string, unknown> | null,\n inputs: EventInputs,\n): Promise<Record<string, unknown> | null> {\n if (!prev && !newReq) {\n return null;\n }\n\n const envelope: Record<string, unknown> = {\n eventId: inputs.eventId,\n source: inputs.source,\n sequence: inputs.sequence,\n systemRef: inputs.systemRef,\n componentId: inputs.componentId,\n requirementId: inputs.requirementId,\n timestamp: inputs.timestamp,\n ...(inputs.schemaRef !== undefined ? { schemaRef: inputs.schemaRef } : {}),\n };\n\n if (!prev) {\n return { ...envelope, priorChecksum: null, state: 'new', before: null, after: newReq };\n }\n\n const before = {\n effectiveStatus: prev.effectiveStatus,\n effectiveImpact: prev.effectiveImpact,\n };\n\n if (!newReq) {\n return {\n ...envelope,\n priorChecksum: { ...prev.checksum },\n state: 'absent',\n before,\n after: null,\n };\n }\n\n const newChecksum = await computeEffectiveChecksum(newReq, inputs.referenceTimestamp);\n if (newChecksum.value === prev.checksum.value) {\n return null;\n }\n\n const newStatus = computeEffectiveStatus(newReq, inputs.referenceTimestamp);\n const transition = classifyDiffStatus(prev.effectiveStatus, newStatus);\n // Status unchanged but the checksum moved: impact or disposition shifted.\n const state = transition === 'fixed' || transition === 'regressed' ? transition : 'updated';\n\n const changeReasons = classifyEventReasons(prev, newReq, prevReq, inputs);\n return {\n ...envelope,\n priorChecksum: { ...prev.checksum },\n state,\n ...(changeReasons.length > 0 ? { changeReasons } : {}),\n before,\n after: newReq,\n };\n}\n","import { computeEffectiveChecksum } from './effective-checksum.js';\n\ntype Doc = Record<string, unknown>;\n\n/** Extract the priorChecksum hex from an event ('' when null/absent). */\nexport function eventPriorValue(ev: Doc): string {\n const prior = ev['priorChecksum'] as { value?: string } | null | undefined;\n return prior?.value ?? '';\n}\n\n/** Effective checksum of a requirement ('' when absent). */\nexport async function requirementChecksum(req: Doc | null, referenceTimestamp: string): Promise<string> {\n if (!req) return '';\n return (await computeEffectiveChecksum(req, referenceTimestamp)).value;\n}\n\n/**\n * Drop duplicate (source, eventId) deliveries — the fold contract's\n * idempotency key (ADR-0005 §4). Go parity: dedupEvents.\n */\nexport function dedupEvents(events: Doc[]): Doc[] {\n const seen = new Set<string>();\n const deduped: Doc[] = [];\n for (const ev of events) {\n if (!ev) continue;\n const key = `${String(ev['source'])}|${String(ev['eventId'])}`;\n if (seen.has(key)) continue;\n seen.add(key);\n deduped.push(ev);\n }\n return deduped;\n}\n\n/**\n * Group events per entity key, each chain ordered by sequence (eventId\n * tie-break), keys sorted for deterministic iteration. Go parity:\n * groupEventChains.\n */\nexport function groupEventChains(events: Doc[]): { byKey: Map<string, Doc[]>; keys: string[] } {\n const byKey = new Map<string, Doc[]>();\n for (const ev of events) {\n const id = ev['requirementId'] as string;\n const chain = byKey.get(id) ?? [];\n chain.push(ev);\n byKey.set(id, chain);\n }\n const keys = [...byKey.keys()].sort();\n for (const [, chain] of byKey) {\n chain.sort((a, b) => {\n const seqA = a['sequence'] as number;\n const seqB = b['sequence'] as number;\n if (seqA !== seqB) return seqA - seqB;\n return String(a['eventId']).localeCompare(String(b['eventId']));\n });\n }\n return { byKey, keys };\n}\n\n/**\n * Walk a per-key chain's priorChecksum links from the seed posture forward,\n * reporting anomalies through keyWarn. Best-effort: expiry anchored to each\n * event's occurrence time. Unanchored chains (key not in seed, first event\n * not new) are left to the caller's application outcome. Go parity:\n * verifyEventChain.\n */\nexport async function verifyEventChain(\n chain: Doc[],\n seedReq: Doc | null,\n inSeed: boolean,\n keyWarn: (kind: string, message: string) => void,\n): Promise<void> {\n const first = chain[0];\n if (!first) return;\n if (!inSeed && first['state'] !== 'new') return;\n\n let expected = '';\n if (seedReq) {\n expected = await requirementChecksum(seedReq, first['timestamp'] as string);\n }\n for (const ev of chain) {\n const prior = eventPriorValue(ev);\n if (ev['state'] === 'new') {\n if (inSeed) {\n keyWarn('newOnExisting', 'state new for a key already present in the seed');\n } else if (prior !== '') {\n keyWarn('chainGap', 'new-state event carries a non-null priorChecksum');\n }\n } else if (prior !== expected) {\n // Two indistinguishable causes: events genuinely missing from the chain,\n // or a chain derived under an older effective-status semantics (a\n // checksum epoch — the resolved status the checksum hashes changed\n // across binary versions).\n keyWarn(\n 'chainGap',\n `priorChecksum \"${prior}\" does not match expected chain state \"${expected}\" — either events are missing from this chain, or it was derived under an older effective-status semantics (see status-determination.md); re-derive from a fresh rescan to re-anchor`,\n );\n }\n expected = await requirementChecksum(ev['after'] as Doc | null, ev['timestamp'] as string);\n }\n}\n","import { formatTimestamp, parseTimestamp, sha256 } from '@mitre/hdf-utilities';\nimport {\n dedupEvents,\n groupEventChains,\n verifyEventChain,\n} from './event-stream-common.js';\n\n/**\n * Caller-supplied identity for a reassembly run. Everything else in the\n * derivation block is computed from the seed text and the event batch — no\n * wall clock, no RNG. Go parity: ApplyInputs in hdf-diff/go/apply_events.go.\n */\nexport interface ApplyInputs {\n /** Names the reconciling tool — a reconciled document never masquerades as scanner output. */\n generator: { name: string; version: string };\n /** Locates the seed snapshot; its checksum is computed from the seed text. */\n seedUri: string;\n /** The event-stream producer context recorded in the derivation block. */\n source: string;\n}\n\n/**\n * A non-fatal per-key anomaly. Warnings never abort the fold: the key is\n * still applied last-value-wins and the warning marks it unverified\n * (ADR-0005 §4 fold contract).\n */\nexport interface ApplyWarning {\n requirementId: string;\n /** chainGap | newOnExisting | absentUnknown | multiBaseline */\n kind: string;\n message: string;\n}\n\nexport interface ApplyResult {\n results: Record<string, unknown>;\n warnings: ApplyWarning[];\n}\n\ntype Doc = Record<string, unknown>;\n\nfunction findRequirement(\n doc: Doc,\n id: string,\n): { baseline: Doc; requirements: Doc[]; index: number } | null {\n const baselines = (doc['baselines'] as Doc[] | undefined) ?? [];\n for (const baseline of baselines) {\n const requirements = (baseline['requirements'] as Doc[] | undefined) ?? [];\n const index = requirements.findIndex((r) => r['id'] === id);\n if (index >= 0) {\n return { baseline, requirements, index };\n }\n }\n return null;\n}\n\n/**\n * Reassemble the current posture from a seed hdf-results document plus a\n * batch of requirement-change events (ADR-0005 §§4-7): keyed last-value-wins\n * by sequence, idempotent via (source, eventId) dedup, tombstone-aware\n * (absent removes), total over the event-state enum. Delivery order and\n * duplicates never change the output. The result carries the caller's\n * generator and a derivation block (seed pinned by content, watermark,\n * count, asOf) so it can never masquerade as scan evidence. Chain gaps and\n * anomalies surface as warnings, never as refusal. Go parity:\n * ApplyChangeEvents.\n */\nexport async function applyChangeEvents(\n seedJson: string,\n events: Doc[],\n inputs: ApplyInputs,\n): Promise<ApplyResult> {\n const doc = JSON.parse(seedJson) as Doc;\n const seedChecksum = await sha256(seedJson);\n const docTimestamp = (doc['timestamp'] as string | undefined) ?? '';\n\n const { byKey, keys } = groupEventChains(dedupEvents(events));\n\n const warnings: ApplyWarning[] = [];\n let maxSequence = 0;\n let maxOccurredMs = Number.NEGATIVE_INFINITY;\n let asOfFromEvents = '';\n let eventsApplied = 0;\n const insertions: { sequence: number; id: string; payload: Doc }[] = [];\n\n for (const id of keys) {\n const chain = byKey.get(id) ?? [];\n const first = chain[0];\n const winner = chain[chain.length - 1];\n if (!first || !winner) continue;\n const inSeed = findRequirement(doc, id) !== null;\n\n // One warning per key, application anomalies taking priority over\n // chain-link mismatches.\n let keyWarned = false;\n const keyWarn = (kind: string, message: string): void => {\n if (!keyWarned) {\n keyWarned = true;\n warnings.push({ requirementId: id, kind, message });\n }\n };\n\n // Chain verification (shared with the fold): unanchored chains defer\n // to the application outcome below.\n const located = findRequirement(doc, id);\n await verifyEventChain(chain, located ? (located.requirements[located.index] ?? null) : null, inSeed, keyWarn);\n const verifyLinks = inSeed || first['state'] === 'new';\n\n // Apply the winner.\n const winnerSeq = winner['sequence'] as number;\n if (winnerSeq > maxSequence) maxSequence = winnerSeq;\n // parseTimestamp + formatTimestamp keep the occurrence host-independent\n // and render asOf as trimmed UTC, matching the Go peer's\n // winner.Timestamp.UTC().Format(RFC3339Nano).\n const occurred = parseTimestamp(winner['timestamp'] as string);\n if (occurred !== null && occurred.getTime() > maxOccurredMs) {\n maxOccurredMs = occurred.getTime();\n asOfFromEvents = formatTimestamp(occurred);\n }\n\n if (winner['state'] === 'absent') {\n const hit = findRequirement(doc, id);\n if (hit) {\n hit.requirements.splice(hit.index, 1);\n eventsApplied++;\n } else {\n keyWarn('absentUnknown', 'absent event for a key not present in the document');\n }\n continue;\n }\n\n if (!verifyLinks) {\n keyWarn('chainGap', 'non-new chain for a key the seed does not carry');\n }\n\n const payload = winner['after'] as Doc | null;\n if (!payload) {\n keyWarn('chainGap', 'winning event carries no applicable after payload');\n continue;\n }\n const hit = findRequirement(doc, id);\n if (hit) {\n hit.requirements[hit.index] = structuredClone(payload);\n eventsApplied++;\n } else {\n insertions.push({ sequence: winnerSeq, id, payload: structuredClone(payload) });\n }\n }\n\n // Deterministic insertion order regardless of delivery order.\n insertions.sort((a, b) => (a.sequence !== b.sequence ? a.sequence - b.sequence : a.id.localeCompare(b.id)));\n if (insertions.length > 0) {\n const baselines = (doc['baselines'] as Doc[] | undefined) ?? [];\n const firstBaseline = baselines[0];\n const firstInsertion = insertions[0];\n if (!firstBaseline || !firstInsertion) {\n throw new Error('seed document has no baselines to insert new requirements into');\n }\n if (baselines.length > 1) {\n warnings.push({\n requirementId: firstInsertion.id,\n kind: 'multiBaseline',\n message: 'seed has multiple baselines; new requirements appended to the first',\n });\n }\n const requirements = (firstBaseline['requirements'] as Doc[] | undefined) ?? [];\n for (const ins of insertions) {\n requirements.push(ins.payload);\n eventsApplied++;\n }\n firstBaseline['requirements'] = requirements;\n }\n\n const asOf = asOfFromEvents !== '' ? asOfFromEvents : docTimestamp;\n if (asOf === '') {\n throw new Error('cannot derive asOf: no events supplied and the seed document has no timestamp');\n }\n\n doc['generator'] = { name: inputs.generator.name, version: inputs.generator.version };\n doc['timestamp'] = asOf;\n doc['derivation'] = {\n seed: {\n uri: inputs.seedUri,\n checksum: { algorithm: 'sha256', value: seedChecksum },\n },\n source: inputs.source,\n throughSequence: maxSequence,\n eventsApplied,\n asOf,\n };\n\n return { results: doc, warnings };\n}\n","import { formatTimestamp, parseTimestamp } from '@mitre/hdf-utilities';\nimport { computeSummary } from './summary.js';\nimport { computeEffectiveStatus } from './status.js';\nimport { computeFieldChanges, extractDrift, DEFAULT_TRACKED_FIELDS } from './diff.js';\nimport { dedupEvents, groupEventChains, verifyEventChain } from './event-stream-common.js';\nimport type { ApplyWarning } from './apply-events.js';\nimport type { RequirementDiff, ChangeReason, RequirementState } from './types.js';\n\ntype Doc = Record<string, unknown>;\ntype FieldChangesInput = Parameters<typeof computeFieldChanges>[0];\n\nexport interface FoldResult {\n comparison: Record<string, unknown>;\n warnings: ApplyWarning[];\n}\n\nfunction findSeedRequirement(doc: Doc, id: string): Doc | null {\n const baselines = (doc['baselines'] as Doc[] | undefined) ?? [];\n for (const baseline of baselines) {\n const requirements = (baseline['requirements'] as Doc[] | undefined) ?? [];\n const hit = requirements.find((r) => r['id'] === id);\n if (hit) return hit;\n }\n return null;\n}\n\n/**\n * Materialize a change-event batch into a full systemDrift hdf-comparison\n * against the seed document (ADR-0005 §5): each winning event lifts into the\n * Requirement_Diff shape the batch engine produces — before from the seed,\n * after from the event payload, field changes derived by the batch engine's\n * own computeFieldChanges — under the same fold contract as\n * applyChangeEvents (dedup, last-value-wins by sequence, tombstone-aware,\n * warnings never abort). Deterministic: the comparison timestamp is the\n * latest event occurrence, and seed-side override expiry anchors to the\n * seed's own timestamp (falling back to the event occurrence when the seed\n * has none) — never wall clock. Go parity: FoldChangeEventsIntoComparison.\n */\nexport async function foldChangeEventsIntoComparison(\n seedJson: string,\n events: Doc[],\n): Promise<FoldResult> {\n const doc = JSON.parse(seedJson) as Doc;\n const docTimestamp = (doc['timestamp'] as string | undefined) ?? '';\n\n const { byKey, keys } = groupEventChains(dedupEvents(events));\n\n const warnings: ApplyWarning[] = [];\n const diffs: RequirementDiff[] = [];\n let maxOccurredMs = Number.NEGATIVE_INFINITY;\n let asOfFromEvents = '';\n let systemRef = '';\n\n for (const id of keys) {\n const chain = byKey.get(id) ?? [];\n const winner = chain[chain.length - 1];\n if (!winner) continue;\n if (systemRef === '') {\n systemRef = (winner['systemRef'] as string | undefined) ?? '';\n }\n\n let keyWarned = false;\n const keyWarn = (kind: string, message: string): void => {\n if (!keyWarned) {\n keyWarned = true;\n warnings.push({ requirementId: id, kind, message });\n }\n };\n\n const seedReq = findSeedRequirement(doc, id);\n const inSeed = seedReq !== null;\n await verifyEventChain(chain, seedReq, inSeed, keyWarn);\n\n // parseTimestamp + formatTimestamp keep the occurrence host-independent\n // and render timestamps as trimmed UTC, matching the Go peer's\n // winner.Timestamp.UTC().Format(RFC3339Nano).\n const occurred = parseTimestamp(winner['timestamp'] as string);\n if (occurred !== null && occurred.getTime() > maxOccurredMs) {\n maxOccurredMs = occurred.getTime();\n asOfFromEvents = formatTimestamp(occurred);\n }\n const newTs = occurred !== null ? formatTimestamp(occurred) : (winner['timestamp'] as string);\n // Seed-side override expiry needs a deterministic anchor: the seed's\n // own observation time, else the event occurrence — a timestamp-less\n // seed must never fall through to the wall clock.\n const seedRef = docTimestamp !== '' ? docTimestamp : newTs;\n\n if (winner['state'] === 'absent') {\n if (!seedReq) {\n keyWarn('absentUnknown', 'absent event for a key not present in the seed');\n continue;\n }\n diffs.push({\n id,\n title: seedReq['title'] as string | undefined,\n state: 'absent',\n oldEffectiveStatus: computeEffectiveStatus(seedReq, seedRef),\n changeReasons: [],\n oldImpact: seedReq['impact'] as number | undefined,\n fieldChanges: [],\n before: seedReq,\n after: null,\n });\n continue;\n }\n\n const after = winner['after'] as Doc | null;\n if (!after) {\n keyWarn('chainGap', 'winning event carries no applicable after payload');\n continue;\n }\n const newStatus = computeEffectiveStatus(after, newTs);\n\n // Content-bearing chain for a key the seed does not carry: the\n // comparison vocabulary allows a null before only on new, so the entry\n // is coerced to the batch engine's new shape; the warning records the\n // anomaly.\n if (!seedReq) {\n if (winner['state'] !== 'new') {\n keyWarn('chainGap', 'non-new chain for a key the seed does not carry; lifted as new');\n }\n diffs.push({\n id,\n title: after['title'] as string | undefined,\n state: 'new',\n newEffectiveStatus: newStatus,\n changeReasons: [],\n newImpact: after['impact'] as number | undefined,\n fieldChanges: [],\n before: null,\n after,\n });\n continue;\n }\n\n diffs.push({\n id,\n title: (after['title'] as string | undefined) ?? (seedReq['title'] as string | undefined),\n state: winner['state'] as RequirementState,\n oldEffectiveStatus: computeEffectiveStatus(seedReq, seedRef),\n newEffectiveStatus: newStatus,\n changeReasons: ((winner['changeReasons'] as string[] | undefined) ?? []) as ChangeReason[],\n oldImpact: seedReq['impact'] as number | undefined,\n newImpact: after['impact'] as number | undefined,\n fieldChanges: computeFieldChanges(\n seedReq as FieldChangesInput,\n after as FieldChangesInput,\n DEFAULT_TRACKED_FIELDS,\n ),\n before: seedReq,\n after,\n });\n }\n\n diffs.sort((a, b) => a.id.localeCompare(b.id));\n\n const asOf = asOfFromEvents !== '' ? asOfFromEvents : docTimestamp;\n if (asOf === '') {\n throw new Error(\n 'cannot derive a comparison timestamp: no events supplied and the seed document has no timestamp',\n );\n }\n\n return {\n comparison: {\n formatVersion: '1.0.0',\n comparisonMode: 'systemDrift',\n timestamp: asOf,\n ...(systemRef !== '' ? { systemRef } : {}),\n sources: [\n { role: 'old', label: 'Old evaluation' },\n { role: 'new', label: 'New evaluation' },\n ],\n matching: { primaryStrategy: 'exactId' },\n summary: computeSummary(diffs),\n baselineDiffs: [],\n requirementDiffs: diffs,\n drift: extractDrift(diffs),\n },\n warnings,\n };\n}\n","import type { ComparisonSummary } from './types.js';\n\n/** GNU diff compatible exit codes (--exit-code mode) */\nexport const EXIT_IDENTICAL = 0;\nexport const EXIT_DIFFERENCES = 1;\nexport const EXIT_ERROR = 2;\n\n/** Detailed exit codes (--detailed-exitcode mode) */\nexport const EXIT_DETAILED_IDENTICAL = 0;\nexport const EXIT_DETAILED_ERROR = 1;\nexport const EXIT_DETAILED_FIXES_ONLY = 10;\nexport const EXIT_DETAILED_REGRESSIONS_ONLY = 11;\nexport const EXIT_DETAILED_MIXED = 12;\nexport const EXIT_DETAILED_BASELINE_CHANGED = 13;\nexport const EXIT_DETAILED_DRIFT_ONLY = 14;\n\n/**\n * Compute the GNU diff compatible exit code from a comparison summary.\n *\n * Returns:\n * 0 = identical (no differences found)\n * 1 = differences found (any kind)\n *\n * Note: error (exit code 2) is not computed from the summary — callers\n * should return EXIT_ERROR directly when I/O or parse errors occur.\n */\nexport function computeExitCode(summary: ComparisonSummary): number {\n if (hasDifferences(summary)) {\n return EXIT_DIFFERENCES;\n }\n return EXIT_IDENTICAL;\n}\n\n/**\n * Compute the detailed exit code from a comparison summary.\n *\n * Returns:\n * 0 = identical (no differences found)\n * 10 = differences found, fixes only (security posture improved)\n * 11 = differences found, regressions only (security posture degraded)\n * 12 = differences found, mixed fixes and regressions\n * 13 = differences found, only new/absent controls (baseline changed)\n * 14 = differences found, only metadata drift (no status changes)\n *\n * Note: error (exit code 1) is not computed from the summary — callers\n * should return EXIT_DETAILED_ERROR directly when I/O or parse errors occur.\n *\n * Priority order: mixed(12) > regressions(11) > fixes(10) > baseline(13) > drift(14)\n */\nexport function computeDetailedExitCode(summary: ComparisonSummary): number {\n if (!hasDifferences(summary)) {\n return EXIT_DETAILED_IDENTICAL;\n }\n\n // Mixed: both fixes and regressions\n if (summary.regressed > 0 && summary.fixed > 0) {\n return EXIT_DETAILED_MIXED;\n }\n\n // Regressions only (no fixes)\n if (summary.regressed > 0) {\n return EXIT_DETAILED_REGRESSIONS_ONLY;\n }\n\n // Fixes only (no regressions)\n if (summary.fixed > 0) {\n return EXIT_DETAILED_FIXES_ONLY;\n }\n\n // Baseline changes: new or absent controls (but no status changes)\n if (summary.new > 0 || summary.absent > 0) {\n return EXIT_DETAILED_BASELINE_CHANGED;\n }\n\n // Everything else is metadata drift (updated tags, descriptions, etc.)\n return EXIT_DETAILED_DRIFT_ONLY;\n}\n\n/**\n * Returns true if the summary indicates any differences at all.\n */\nfunction hasDifferences(summary: ComparisonSummary): boolean {\n return summary.total !== summary.unchanged;\n}\n","import type { RequirementDiff } from '../types.js';\nimport type { RenderOptions } from './types.js';\n\n/**\n * Filter requirement diffs based on render options.\n *\n * Supports filtering by:\n * - `filterStates`: Only include requirements matching the given states\n * - `filterSeverity`: Only include requirements matching the given severity tag\n */\nexport function filterRequirements(\n diffs: RequirementDiff[],\n options?: RenderOptions,\n): RequirementDiff[] {\n let filtered = diffs;\n\n if (options?.filterStates && options.filterStates.length > 0) {\n const states = new Set(options.filterStates);\n filtered = filtered.filter((r) => states.has(r.state));\n }\n\n if (options?.filterSeverity) {\n const severity = options.filterSeverity.toLowerCase();\n filtered = filtered.filter((r) => {\n const before = r.before as Record<string, unknown> | null;\n const after = r.after as Record<string, unknown> | null;\n const tags =\n (after?.['tags'] as Record<string, unknown> | undefined) ??\n (before?.['tags'] as Record<string, unknown> | undefined);\n if (!tags) return false;\n return (\n typeof tags['severity'] === 'string' &&\n tags['severity'].toLowerCase() === severity\n );\n });\n }\n\n return filtered;\n}\n","import type { HDFComparison, RequirementDiff } from '../types.js';\nimport type { RenderOptions } from './types.js';\nimport { filterRequirements } from './filter.js';\n\n/**\n * Strip `before` and `after` from a RequirementDiff, keeping only\n * the summary fields (id, state, title, statuses, changeReasons, fieldChanges).\n */\nfunction stripSnapshots(\n req: RequirementDiff,\n): Omit<RequirementDiff, 'before' | 'after'> {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { before, after, ...rest } = req;\n return rest;\n}\n\n/**\n * Render an HDFComparison as a JSON string.\n *\n * - `detail: 'summary'` -- only `{ formatVersion, comparisonMode, summary }`\n * - `detail: 'control'` -- full document but `before`/`after` stripped from requirementDiffs\n * - `detail: 'full'` -- `JSON.stringify(comparison, null, 2)` (the complete document)\n *\n * Default detail level: `'control'`.\n */\nexport function renderJson(\n comparison: HDFComparison,\n options?: RenderOptions,\n): string {\n const detail = options?.detail ?? 'control';\n\n if (detail === 'summary') {\n return JSON.stringify(\n {\n formatVersion: comparison.formatVersion,\n comparisonMode: comparison.comparisonMode,\n summary: comparison.summary,\n },\n null,\n 2,\n );\n }\n\n if (detail === 'full') {\n const filtered = filterRequirements(\n comparison.requirementDiffs,\n options,\n );\n if (filtered.length !== comparison.requirementDiffs.length) {\n return JSON.stringify(\n { ...comparison, requirementDiffs: filtered },\n null,\n 2,\n );\n }\n return JSON.stringify(comparison, null, 2);\n }\n\n // detail === 'control' (default)\n const filtered = filterRequirements(\n comparison.requirementDiffs,\n options,\n );\n const strippedDiffs = filtered.map(stripSnapshots);\n\n return JSON.stringify(\n { ...comparison, requirementDiffs: strippedDiffs },\n null,\n 2,\n );\n}\n","import type { HDFComparison, RequirementDiff } from '../types.js';\nimport type { RenderOptions } from './types.js';\nimport { filterRequirements } from './filter.js';\n\n/**\n * Render the summary table in markdown format.\n */\nfunction renderSummaryTable(comparison: HDFComparison): string {\n const { summary } = comparison;\n const lines: string[] = [\n '## HDF Comparison Summary',\n '',\n '| Metric | Count |',\n '|--------|-------|',\n `| Fixed | ${summary.fixed} |`,\n `| Regressed | ${summary.regressed} |`,\n `| New | ${summary.new} |`,\n `| Absent | ${summary.absent} |`,\n `| Unchanged | ${summary.unchanged} |`,\n `| Updated | ${summary.updated} |`,\n `| **Total** | **${summary.total}** |`,\n ];\n return lines.join('\\n');\n}\n\n/**\n * Group requirement diffs by state.\n */\nfunction groupByState(\n diffs: RequirementDiff[],\n): Map<string, RequirementDiff[]> {\n const groups = new Map<string, RequirementDiff[]>();\n for (const diff of diffs) {\n const existing = groups.get(diff.state);\n if (existing) {\n existing.push(diff);\n } else {\n groups.set(diff.state, [diff]);\n }\n }\n return groups;\n}\n\n/**\n * Escape a value for use in a markdown table cell.\n * Replaces pipe characters with their HTML entity.\n */\nfunction escapeCell(value: string): string {\n return value.replace(/\\|/g, '&#124;');\n}\n\n/**\n * Format field changes for a markdown cell.\n */\nfunction formatFieldChanges(req: RequirementDiff): string {\n if (req.fieldChanges.length === 0) return '';\n return req.fieldChanges\n .map((fc) => {\n if (fc.op === 'add') return `+${fc.path}: ${JSON.stringify(fc.newValue)}`;\n if (fc.op === 'remove')\n return `-${fc.path}: ${JSON.stringify(fc.oldValue)}`;\n return `${fc.path}: ${JSON.stringify(fc.oldValue)} -> ${JSON.stringify(fc.newValue)}`;\n })\n .join('; ');\n}\n\n/**\n * Render a section for a single state group.\n */\nfunction renderStateSection(\n state: string,\n diffs: RequirementDiff[],\n detail: string,\n): string {\n const label = state.charAt(0).toUpperCase() + state.slice(1);\n const lines: string[] = [`### ${label} (${diffs.length})`];\n\n if (diffs.length === 0) {\n lines.push('', '(none)');\n return lines.join('\\n');\n }\n\n lines.push('');\n\n if (detail === 'full') {\n lines.push(\n '| ID | Title | Old Status | New Status | Change Reasons | Field Changes |',\n '|----|-------|------------|------------|----------------|---------------|',\n );\n for (const req of diffs) {\n const id = escapeCell(req.id);\n const title = escapeCell(req.title ?? '');\n const oldStatus = escapeCell(req.oldEffectiveStatus ?? '');\n const newStatus = escapeCell(req.newEffectiveStatus ?? '');\n const reasons = escapeCell(req.changeReasons.join(', '));\n const fieldChanges = escapeCell(formatFieldChanges(req));\n lines.push(\n `| ${id} | ${title} | ${oldStatus} | ${newStatus} | ${reasons} | ${fieldChanges} |`,\n );\n }\n } else {\n lines.push(\n '| ID | Title | Old Status | New Status |',\n '|----|-------|------------|------------|',\n );\n for (const req of diffs) {\n const id = escapeCell(req.id);\n const title = escapeCell(req.title ?? '');\n const oldStatus = escapeCell(req.oldEffectiveStatus ?? '');\n const newStatus = escapeCell(req.newEffectiveStatus ?? '');\n lines.push(`| ${id} | ${title} | ${oldStatus} | ${newStatus} |`);\n }\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Render an HDFComparison as a Markdown string.\n *\n * - `detail: 'summary'` -- summary table only\n * - `detail: 'control'` -- summary + per-requirement tables by state\n * - `detail: 'full'` -- summary + per-requirement tables with changeReasons and fieldChanges\n *\n * Default detail level: `'control'`.\n */\nexport function renderMarkdown(\n comparison: HDFComparison,\n options?: RenderOptions,\n): string {\n const detail = options?.detail ?? 'control';\n const parts: string[] = [renderSummaryTable(comparison)];\n\n if (detail === 'summary') {\n return parts.join('\\n');\n }\n\n // Determine which states to display\n const stateOrder: string[] = [\n 'fixed',\n 'regressed',\n 'new',\n 'absent',\n 'updated',\n 'unchanged',\n ];\n\n const filtered = filterRequirements(\n comparison.requirementDiffs,\n options,\n );\n const grouped = groupByState(filtered);\n\n // If filtering by states, only show those specific states\n const statesToShow =\n options?.filterStates && options.filterStates.length > 0\n ? stateOrder.filter((s) => options.filterStates!.includes(s))\n : stateOrder;\n\n for (const state of statesToShow) {\n parts.push('');\n const diffs = grouped.get(state) ?? [];\n parts.push(renderStateSection(state, diffs, detail));\n }\n\n return parts.join('\\n');\n}\n","import type { HDFComparison, RequirementDiff } from '../types.js';\nimport type { RenderOptions } from './types.js';\nimport { filterRequirements } from './filter.js';\n\n// ANSI color codes\nconst RESET = '\\x1b[0m';\nconst GREEN = '\\x1b[32m';\nconst RED = '\\x1b[31m';\nconst YELLOW = '\\x1b[33m';\nconst BOLD = '\\x1b[1m';\nconst DIM = '\\x1b[2m';\n\n/**\n * Get the symbol and color for a requirement state.\n */\nfunction getSymbolAndColor(\n state: string,\n useColor: boolean,\n): { symbol: string; colorFn: (s: string) => string } {\n const identity = (s: string): string => s;\n\n switch (state) {\n case 'fixed':\n case 'new':\n return {\n symbol: '+',\n colorFn: useColor ? (s) => `${GREEN}${s}${RESET}` : identity,\n };\n case 'regressed':\n case 'absent':\n return {\n symbol: '-',\n colorFn: useColor ? (s) => `${RED}${s}${RESET}` : identity,\n };\n case 'updated':\n return {\n symbol: '~',\n colorFn: useColor ? (s) => `${YELLOW}${s}${RESET}` : identity,\n };\n case 'unchanged':\n default:\n return {\n symbol: ' ',\n colorFn: useColor ? (s) => `${DIM}${s}${RESET}` : identity,\n };\n }\n}\n\n/**\n * Format the status transition for a requirement.\n */\nfunction formatStatusTransition(req: RequirementDiff): string {\n if (req.state === 'new') {\n return '(new)';\n }\n if (req.state === 'absent') {\n return '(absent)';\n }\n\n const parts: string[] = [];\n\n // Show status change if both exist\n if (req.oldEffectiveStatus && req.newEffectiveStatus) {\n parts.push(`${req.oldEffectiveStatus} → ${req.newEffectiveStatus}`);\n }\n\n // Add state label for non-obvious transitions\n if (req.state !== 'unchanged') {\n parts.push(`(${req.state})`);\n }\n\n return parts.join(' ');\n}\n\n/**\n * Format field changes for full detail.\n */\nfunction formatFieldChangesForTerminal(req: RequirementDiff): string {\n if (req.fieldChanges.length === 0) return '';\n\n const parts = req.fieldChanges.map((fc) => {\n if (fc.op === 'add') return `+${fc.path}: ${JSON.stringify(fc.newValue)}`;\n if (fc.op === 'remove') return `-${fc.path}: ${JSON.stringify(fc.oldValue)}`;\n return `${fc.path}: ${JSON.stringify(fc.oldValue)} → ${JSON.stringify(fc.newValue)}`;\n });\n\n return parts.join('; ');\n}\n\n/**\n * Render a single requirement line.\n */\nfunction renderRequirementLine(\n req: RequirementDiff,\n detail: string,\n useColor: boolean,\n): string {\n const { symbol, colorFn } = getSymbolAndColor(req.state, useColor);\n const title = req.title ?? '';\n const transition = formatStatusTransition(req);\n\n let line = ` ${symbol} ${req.id} ${title} ${transition}`;\n\n if (detail === 'full') {\n // Add change reasons\n if (req.changeReasons.length > 0) {\n line += ` [${req.changeReasons.join(', ')}]`;\n }\n // Add field changes\n const fieldChanges = formatFieldChangesForTerminal(req);\n if (fieldChanges) {\n line += ` ${fieldChanges}`;\n }\n }\n\n return colorFn(line);\n}\n\n/**\n * Build the summary line.\n */\nfunction buildSummaryLine(comparison: HDFComparison, useColor: boolean): string {\n const { summary } = comparison;\n\n const parts = [\n `${summary.fixed} fixed`,\n `${summary.regressed} regressed`,\n `${summary.new} new`,\n `${summary.absent} absent`,\n `${summary.unchanged} unchanged`,\n `${summary.updated} updated`,\n `(${summary.total} total)`,\n ];\n\n const line = `Summary: ${parts.join(', ')}`;\n\n if (useColor) {\n return `${BOLD}${line}${RESET}`;\n }\n return line;\n}\n\n/**\n * Build the header line.\n */\nfunction buildHeaderLine(comparison: HDFComparison, useColor: boolean): string {\n const mode = comparison.comparisonMode;\n const oldSource = comparison.sources.find((s) => s.role === 'old' || s.role === 'golden' || s.role === 'reference');\n const newSource = comparison.sources.find((s) => s.role === 'new' || s.role === 'system');\n\n let header = `HDF Comparison: ${mode}`;\n\n const oldTimestamp = oldSource?.assessmentTimestamp;\n const newTimestamp = newSource?.assessmentTimestamp;\n\n if (oldTimestamp && newTimestamp) {\n // Format as date-only if possible, otherwise use full timestamp\n // split() always returns at least one element, so [0] is safe\n const oldDate = oldTimestamp.split('T')[0]!;\n const newDate = newTimestamp.split('T')[0]!;\n header += ` (${oldDate} → ${newDate})`;\n }\n\n if (useColor) {\n return `${BOLD}${header}${RESET}`;\n }\n return header;\n}\n\n/**\n * Render an HDFComparison for terminal display with optional ANSI colors.\n *\n * - `detail: 'summary'` -- just the summary line\n * - `detail: 'control'` -- requirement list + summary (excludes unchanged)\n * - `detail: 'full'` -- all requirements including unchanged, with changeReasons and fieldChanges\n *\n * When `color: false`, no ANSI escape codes are emitted.\n * Default detail level: `'control'`. Default color: `true`.\n */\nexport function renderTerminal(\n comparison: HDFComparison,\n options?: RenderOptions,\n): string {\n const detail = options?.detail ?? 'control';\n const useColor = options?.color ?? true;\n\n const lines: string[] = [];\n\n // Header\n lines.push(buildHeaderLine(comparison, useColor));\n lines.push('');\n\n if (detail === 'summary') {\n lines.push(buildSummaryLine(comparison, useColor));\n return lines.join('\\n');\n }\n\n // Requirement lines\n const filtered = filterRequirements(comparison.requirementDiffs, options);\n\n for (const req of filtered) {\n // In 'control' mode, skip unchanged requirements\n if (detail === 'control' && req.state === 'unchanged') {\n continue;\n }\n lines.push(renderRequirementLine(req, detail, useColor));\n }\n\n lines.push('');\n lines.push(buildSummaryLine(comparison, useColor));\n\n return lines.join('\\n');\n}\n","import type { HDFComparison, RequirementDiff } from '../types.js';\nimport type { RenderOptions } from './types.js';\nimport { filterRequirements } from './filter.js';\n\n/**\n * Escape a value for CSV output.\n *\n * Per RFC 4180:\n * - Fields containing commas, double quotes, or newlines are enclosed in double quotes.\n * - Double quotes within a field are escaped by doubling them.\n */\nfunction escapeCsvField(value: string): string {\n if (value.includes(',') || value.includes('\"') || value.includes('\\n') || value.includes('\\r')) {\n return `\"${value.replace(/\"/g, '\"\"')}\"`;\n }\n return value;\n}\n\n/**\n * Format field changes as a human-readable string.\n */\nfunction formatFieldChanges(req: RequirementDiff): string {\n if (req.fieldChanges.length === 0) return '';\n return req.fieldChanges\n .map((fc) => {\n if (fc.op === 'add') return `+${fc.path}: ${JSON.stringify(fc.newValue)}`;\n if (fc.op === 'remove') return `-${fc.path}: ${JSON.stringify(fc.oldValue)}`;\n return `${fc.path}: ${JSON.stringify(fc.oldValue)} -> ${JSON.stringify(fc.newValue)}`;\n })\n .join('; ');\n}\n\n/**\n * Render an HDFComparison as a CSV string.\n *\n * One row per requirement. Columns:\n * - ID, Title, State, Old Status, New Status, Impact (Old), Impact (New), Change Reasons\n *\n * When `detail: 'full'`, an additional Field Changes column is included.\n *\n * Header row is always included. Standard CSV escaping (RFC 4180).\n * Default detail level: `'control'`.\n */\nexport function renderCsv(\n comparison: HDFComparison,\n options?: RenderOptions,\n): string {\n const detail = options?.detail ?? 'control';\n const filtered = filterRequirements(comparison.requirementDiffs, options);\n\n const headers = [\n 'ID',\n 'Title',\n 'State',\n 'Old Status',\n 'New Status',\n 'Impact (Old)',\n 'Impact (New)',\n 'Change Reasons',\n ];\n\n if (detail === 'full') {\n headers.push('Field Changes');\n }\n\n const lines: string[] = [headers.join(',')];\n\n for (const req of filtered) {\n const row = [\n escapeCsvField(req.id),\n escapeCsvField(req.title ?? ''),\n escapeCsvField(req.state),\n escapeCsvField(req.oldEffectiveStatus ?? ''),\n escapeCsvField(req.newEffectiveStatus ?? ''),\n escapeCsvField(req.oldImpact !== undefined ? String(req.oldImpact) : ''),\n escapeCsvField(req.newImpact !== undefined ? String(req.newImpact) : ''),\n escapeCsvField(req.changeReasons.join(', ')),\n ];\n\n if (detail === 'full') {\n row.push(escapeCsvField(formatFieldChanges(req)));\n }\n\n lines.push(row.join(','));\n }\n\n return lines.join('\\n');\n}\n","export { renderJson } from './json.js';\nexport { renderMarkdown } from './markdown.js';\nexport { renderTerminal } from './terminal.js';\nexport { renderCsv } from './csv.js';\nexport type { DetailLevel, RenderOptions } from './types.js';\n\nimport type { HDFComparison } from '../types.js';\nimport type { RenderOptions } from './types.js';\nimport { renderJson } from './json.js';\nimport { renderMarkdown } from './markdown.js';\nimport { renderTerminal } from './terminal.js';\nimport { renderCsv } from './csv.js';\n\n/**\n * Convenience function to render a comparison in any supported format.\n *\n * @param comparison - The HDFComparison document to render\n * @param format - Output format: 'json', 'markdown', 'terminal', or 'csv'\n * @param options - Rendering options (detail level, filters, color)\n * @returns The rendered string\n */\nexport function render(\n comparison: HDFComparison,\n format: 'json' | 'markdown' | 'terminal' | 'csv',\n options?: RenderOptions,\n): string {\n switch (format) {\n case 'json':\n return renderJson(comparison, options);\n case 'markdown':\n return renderMarkdown(comparison, options);\n case 'terminal':\n return renderTerminal(comparison, options);\n case 'csv':\n return renderCsv(comparison, options);\n }\n}\n","/**\n * SBOM comparison for the HDF diff engine.\n *\n * Compares two SBOM documents (CycloneDX or SPDX JSON) and produces\n * package-level diffs: added, removed, updated, unchanged packages.\n *\n * Format auto-detection:\n * - CycloneDX: has `bomFormat: \"CycloneDX\"`, packages in `components[]`\n * - SPDX: has `spdxVersion`, packages in `packages[]`\n */\n\n/**\n * The comparison result for a single package between two SBOMs.\n */\nexport interface PackageDiff {\n purl: string;\n name: string;\n state: 'added' | 'removed' | 'updated' | 'unchanged';\n oldVersion?: string;\n newVersion?: string;\n licenses?: string[];\n}\n\n/**\n * The complete result of comparing two SBOM documents.\n */\nexport interface SbomDiffResult {\n packageDiffs: PackageDiff[];\n added: number;\n removed: number;\n updated: number;\n unchanged: number;\n}\n\n/**\n * Internal representation of a parsed package from any SBOM format.\n */\ninterface ParsedPackage {\n purl: string;\n name: string;\n version: string;\n licenses: string[];\n}\n\n/**\n * Compare two SBOM documents (CycloneDX or SPDX JSON strings) and return\n * package-level diffs.\n *\n * @param oldJson - JSON string of the old SBOM document\n * @param newJson - JSON string of the new SBOM document\n * @returns Structured diff result with per-package state and aggregate counts\n * @throws Error if either input is not valid JSON or not a recognized SBOM format\n */\nexport function diffSboms(oldJson: string, newJson: string): SbomDiffResult {\n const oldParsed = JSON.parse(oldJson) as Record<string, unknown>;\n const newParsed = JSON.parse(newJson) as Record<string, unknown>;\n\n const oldPackages = extractPackages(oldParsed);\n const newPackages = extractPackages(newParsed);\n\n const oldMap = buildPackageMap(oldPackages);\n const newMap = buildPackageMap(newPackages);\n\n const diffs: PackageDiff[] = [];\n const seen = new Set<string>();\n\n // Check old packages against new\n for (const [key, oldPkg] of oldMap) {\n seen.add(key);\n const newPkg = newMap.get(key);\n if (newPkg) {\n if (oldPkg.version !== newPkg.version) {\n diffs.push({\n purl: newPkg.purl || newPkg.name,\n name: newPkg.name,\n state: 'updated',\n oldVersion: oldPkg.version,\n newVersion: newPkg.version,\n licenses: newPkg.licenses.length > 0 ? newPkg.licenses : undefined,\n });\n } else {\n diffs.push({\n purl: oldPkg.purl || oldPkg.name,\n name: oldPkg.name,\n state: 'unchanged',\n });\n }\n } else {\n diffs.push({\n purl: oldPkg.purl || oldPkg.name,\n name: oldPkg.name,\n state: 'removed',\n oldVersion: oldPkg.version,\n });\n }\n }\n\n // Check for added packages\n for (const [key, newPkg] of newMap) {\n if (!seen.has(key)) {\n diffs.push({\n purl: newPkg.purl || newPkg.name,\n name: newPkg.name,\n state: 'added',\n newVersion: newPkg.version,\n licenses: newPkg.licenses.length > 0 ? newPkg.licenses : undefined,\n });\n }\n }\n\n // Sort by name for deterministic output\n diffs.sort((a, b) => a.name.localeCompare(b.name));\n\n // Count states\n let added = 0;\n let removed = 0;\n let updated = 0;\n let unchanged = 0;\n for (const d of diffs) {\n switch (d.state) {\n case 'added': added++; break;\n case 'removed': removed++; break;\n case 'updated': updated++; break;\n case 'unchanged': unchanged++; break;\n }\n }\n\n return { packageDiffs: diffs, added, removed, updated, unchanged };\n}\n\n/**\n * Extract packages from an SBOM document, auto-detecting the format.\n */\nfunction extractPackages(doc: Record<string, unknown>): ParsedPackage[] {\n if (doc['bomFormat'] === 'CycloneDX') {\n return extractCycloneDXPackages(doc);\n }\n if (typeof doc['spdxVersion'] === 'string') {\n return extractSPDXPackages(doc);\n }\n throw new Error(\n 'Unrecognized SBOM format: expected CycloneDX (bomFormat) or SPDX (spdxVersion)',\n );\n}\n\n/**\n * Extract packages from a CycloneDX document.\n * Reads components[] with purl, name, version fields.\n */\nfunction extractCycloneDXPackages(doc: Record<string, unknown>): ParsedPackage[] {\n const components = doc['components'] as Array<Record<string, unknown>> | undefined;\n if (!Array.isArray(components)) {\n return [];\n }\n\n return components.map((comp): ParsedPackage => {\n const licenses = extractCycloneDXLicenses(comp);\n return {\n purl: (comp['purl'] as string) ?? '',\n name: (comp['name'] as string) ?? '',\n version: (comp['version'] as string) ?? '',\n licenses,\n };\n });\n}\n\n/**\n * Extract license strings from a CycloneDX component.\n * CycloneDX licenses can be in `licenses[].license.id` or `licenses[].license.name`.\n */\nfunction extractCycloneDXLicenses(comp: Record<string, unknown>): string[] {\n const licensesArr = comp['licenses'] as Array<Record<string, unknown>> | undefined;\n if (!Array.isArray(licensesArr)) {\n return [];\n }\n const result: string[] = [];\n for (const entry of licensesArr) {\n const license = entry['license'] as Record<string, unknown> | undefined;\n if (license) {\n const id = license['id'] as string | undefined;\n const name = license['name'] as string | undefined;\n if (id) {\n result.push(id);\n } else if (name) {\n result.push(name);\n }\n }\n }\n return result;\n}\n\n/**\n * Extract packages from an SPDX document.\n * Reads packages[] with name, versionInfo, and externalRefs (for PURL).\n */\nfunction extractSPDXPackages(doc: Record<string, unknown>): ParsedPackage[] {\n const packages = doc['packages'] as Array<Record<string, unknown>> | undefined;\n if (!Array.isArray(packages)) {\n return [];\n }\n\n return packages.map((pkg): ParsedPackage => {\n const purl = extractSPDXPurl(pkg);\n const license = (pkg['licenseConcluded'] as string) ?? (pkg['licenseDeclared'] as string) ?? '';\n return {\n purl,\n name: (pkg['name'] as string) ?? '',\n version: (pkg['versionInfo'] as string) ?? '',\n licenses: license && license !== 'NOASSERTION' ? [license] : [],\n };\n });\n}\n\n/**\n * Extract a PURL from an SPDX package's externalRefs array.\n */\nfunction extractSPDXPurl(pkg: Record<string, unknown>): string {\n const refs = pkg['externalRefs'] as Array<Record<string, unknown>> | undefined;\n if (!Array.isArray(refs)) {\n return '';\n }\n for (const ref of refs) {\n const refType = ref['referenceType'] as string | undefined;\n if (refType === 'purl') {\n return (ref['referenceLocator'] as string) ?? '';\n }\n }\n return '';\n}\n\n/**\n * Build a lookup map of packages indexed by name (version-independent key).\n */\nfunction buildPackageMap(packages: ParsedPackage[]): Map<string, ParsedPackage> {\n const map = new Map<string, ParsedPackage>();\n for (const pkg of packages) {\n const key = pkg.name || pkg.purl;\n if (key) {\n map.set(key, pkg);\n }\n }\n return map;\n}\n"],"mappings":";;;;AAIA,MAAM,mCAAmB,IAAI,IAAI,CAAC,QAAQ,CAAC;;AAG3C,MAAM,mCAAmB,IAAI,IAAI;CAAC;CAAU;CAAS;AAAa,CAAC;;;;;;;;;;;;;AAwBnE,SAAgB,uBACd,aACA,oBACQ;CACR,MAAM,UAAW,YAAY,cAA2C,CAAC;CACzE,MAAM,YAAa,YAAY,sBAAqD,CAAC;CACrF,OAAOA,yBACL;EAEE,QAAS,YAAY,aAAoC;EACzD,gBAAgB,QAAQ,KAAK,MAAM,EAAE,MAAM;EAC3C,WAAW,UAAU,KAAK,OAAO;GAC/B,QAAQ,EAAE;GACV,WAAW,EAAE;GACb,WAAW,EAAE;EACf,EAAE;CACJ,GACA,kBACF;AACF;;;;;AAMA,SAAgB,sBACd,QACA,QACA,cACA,cACgB;CAChB,MAAM,UAA0B,CAAC;CAGjC,MAAM,aAAc,OAAO,cA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AAI;CACrB,IAAI,CAAC,MAAM,QAAQ,QAAQ,GACzB,OAAO,CAAC;CAGV,OAAO,SAAS,KAAK,QAAuB;EAC1C,MAAM,OAAO,gBAAgB,GAAG;EAChC,MAAM,UAAW,IAAI,uBAAmC,IAAI,sBAAiC;EAC7F,OAAO;GACL;GACA,MAAO,IAAI,WAAsB;GACjC,SAAU,IAAI,kBAA6B;GAC3C,UAAU,WAAW,YAAY,gBAAgB,CAAC,OAAO,IAAI,CAAC;EAChE;CACF,CAAC;AACH;;;;AAKA,SAAS,gBAAgB,KAAsC;CAC7D,MAAM,OAAO,IAAI;CACjB,IAAI,CAAC,MAAM,QAAQ,IAAI,GACrB,OAAO;CAET,KAAK,MAAM,OAAO,MAEhB,IADgB,IAAI,qBACJ,QACd,OAAQ,IAAI,uBAAkC;CAGlD,OAAO;AACT;;;;AAKA,SAAS,gBAAgB,UAAuD;CAC9E,MAAM,sBAAM,IAAI,IAA2B;CAC3C,KAAK,MAAM,OAAO,UAAU;EAC1B,MAAM,MAAM,IAAI,QAAQ,IAAI;EAC5B,IAAI,KACF,IAAI,IAAI,KAAK,GAAG;CAEpB;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"index.js","names":["canonicalEffectiveStatus","extractCcis","extractCwes","extractGtitle","safeTitle","validatorsValidateComparison","parseCvssVector","parseCvssVectorUtil","formatFieldChanges"],"sources":["../src/status.ts","../src/summary.ts","../src/normalize.ts","../src/matching/exact-id.ts","../src/matching/mapped-id.ts","../src/matching/cci-match.ts","../src/matching/fuzzy-match.ts","../src/matching/srg-deterministic.ts","../src/matching/srg-cci-tiebreak.ts","../src/matching/vendor-fuzzy-title.ts","../src/matching/index.ts","../src/validate.ts","../src/diff.ts","../src/effective-checksum.ts","../src/change-event.ts","../src/event-stream-common.ts","../src/apply-events.ts","../src/fold-events.ts","../src/exit-codes.ts","../src/renderers/filter.ts","../src/renderers/json.ts","../src/renderers/markdown.ts","../src/renderers/terminal.ts","../src/renderers/csv.ts","../src/renderers/index.ts","../src/sbom.ts"],"sourcesContent":["import { computeEffectiveStatus as canonicalEffectiveStatus, parseTimestamp } from '@mitre/hdf-utilities';\nimport type { ChangeReason, RequirementState } from './types.js';\n\n/** Statuses that count as \"passing\" for fixed/regressed classification */\nconst PASSING_STATUSES = new Set(['passed']);\n\n/** Statuses that count as \"failing\" for fixed/regressed classification */\nconst FAILING_STATUSES = new Set(['failed', 'error', 'notReviewed']);\n\ninterface ResultLike {\n status: string;\n}\n\ninterface OverrideLike {\n status?: string;\n appliedAt?: string;\n expiresAt: string;\n}\n\n/**\n * Determine the effective status of a requirement from its results and\n * overrides, delegating to the canonical shared implementation in\n * `@mitre/hdf-utilities` (see status-determination.md):\n *\n * 1. the governing (most recent non-expired) status override's status\n * 2. else result roll-up error → error\n * 3. else impact === 0 → notApplicable\n * 4. else worst-wins roll-up of the results (empty → notReviewed)\n *\n * The stored effectiveStatus field is an output cache and is never read.\n */\nexport function computeEffectiveStatus(\n requirement: Record<string, unknown>,\n referenceTimestamp?: string,\n): string {\n const results = (requirement['results'] as ResultLike[] | undefined) ?? [];\n const overrides = (requirement['statusOverrides'] as OverrideLike[] | undefined) ?? [];\n return canonicalEffectiveStatus(\n {\n // A missing impact must not read as 0 (which would force notApplicable).\n impact: (requirement['impact'] as number | undefined) ?? Number.NaN,\n resultStatuses: results.map((r) => r.status),\n overrides: overrides.map((o) => ({\n status: o.status,\n appliedAt: o.appliedAt,\n expiresAt: o.expiresAt,\n })),\n },\n referenceTimestamp,\n );\n}\n\n/**\n * Classify why the status changed between two requirements.\n * Returns an array of change reasons (a status change can have multiple causes).\n */\nexport function classifyChangeReasons(\n oldReq: Record<string, unknown>,\n newReq: Record<string, unknown>,\n oldTimestamp?: string,\n newTimestamp?: string,\n): ChangeReason[] {\n const reasons: ChangeReason[] = [];\n\n // Check result status changes\n const oldResults = (oldReq['results'] as ResultLike[] | undefined) ?? [];\n const newResults = (newReq['results'] as ResultLike[] | undefined) ?? [];\n const oldResultStatuses = oldResults.map((r) => r.status).sort();\n const newResultStatuses = newResults.map((r) => r.status).sort();\n if (JSON.stringify(oldResultStatuses) !== JSON.stringify(newResultStatuses)) {\n reasons.push('resultChanged');\n }\n\n // Check override changes\n const oldOverrides = (oldReq['statusOverrides'] as OverrideLike[] | undefined) ?? [];\n const newOverrides = (newReq['statusOverrides'] as OverrideLike[] | undefined) ?? [];\n\n if (newOverrides.length > oldOverrides.length) {\n reasons.push('overrideAdded');\n } else if (newOverrides.length < oldOverrides.length) {\n reasons.push('overrideRemoved');\n }\n\n // Check for override expiration between scans. parseTimestamp keeps\n // zone-less scan timestamps host-independent (repo timestamp convention);\n // null means unparseable, so the check is skipped.\n if (oldTimestamp && newTimestamp && oldOverrides.length > 0) {\n const oldTime = parseTimestamp(oldTimestamp)?.getTime();\n const newTime = parseTimestamp(newTimestamp)?.getTime();\n if (oldTime !== undefined && newTime !== undefined) {\n for (const override of oldOverrides) {\n const expiresAt = parseTimestamp(override.expiresAt)?.getTime();\n if (expiresAt !== undefined && expiresAt > oldTime && expiresAt <= newTime) {\n reasons.push('overrideExpired');\n break; // Only report once\n }\n }\n }\n }\n\n // Check impact changes\n const oldImpact = oldReq['impact'] as number | undefined;\n const newImpact = newReq['impact'] as number | undefined;\n if (oldImpact !== newImpact) {\n reasons.push('impactChanged');\n }\n\n // Check disposition changes\n const oldDisposition = oldReq['disposition'] as string | undefined;\n const newDisposition = newReq['disposition'] as string | undefined;\n if (oldDisposition !== newDisposition) {\n reasons.push('dispositionChanged');\n }\n\n // Check effectiveImpact changes\n const oldEffectiveImpact = oldReq['effectiveImpact'] as number | undefined;\n const newEffectiveImpact = newReq['effectiveImpact'] as number | undefined;\n if (oldEffectiveImpact !== newEffectiveImpact) {\n reasons.push('effectiveImpactChanged');\n }\n\n // Check baseline metadata changes (tags, descriptions, title)\n const oldTags = JSON.stringify(oldReq['tags'] ?? {});\n const newTags = JSON.stringify(newReq['tags'] ?? {});\n const oldDescs = JSON.stringify(oldReq['descriptions'] ?? []);\n const newDescs = JSON.stringify(newReq['descriptions'] ?? []);\n const oldTitle = oldReq['title'] as string | undefined;\n const newTitle = newReq['title'] as string | undefined;\n\n if (oldTags !== newTags || oldDescs !== newDescs || oldTitle !== newTitle) {\n reasons.push('metadataChanged');\n }\n\n return reasons;\n}\n\n/**\n * Classify the overall diff status based on old and new effective statuses.\n *\n * - If old is failing and new is passing → 'fixed'\n * - If old is passing and new is failing → 'regressed'\n * - If statuses are equal → 'unchanged'\n * - Otherwise → 'updated'\n */\nexport function classifyDiffStatus(\n oldEffectiveStatus: string,\n newEffectiveStatus: string,\n): RequirementState {\n if (oldEffectiveStatus === newEffectiveStatus) {\n return 'unchanged';\n }\n\n const oldIsFailing = FAILING_STATUSES.has(oldEffectiveStatus);\n const newIsPassing = PASSING_STATUSES.has(newEffectiveStatus);\n const oldIsPassing = PASSING_STATUSES.has(oldEffectiveStatus);\n const newIsFailing = FAILING_STATUSES.has(newEffectiveStatus);\n\n if (oldIsFailing && newIsPassing) {\n return 'fixed';\n }\n if (oldIsPassing && newIsFailing) {\n return 'regressed';\n }\n\n return 'updated';\n}\n","import type { ComparisonSummary, RequirementDiff } from './types.js';\n\n/**\n * Compute summary counts from an array of RequirementDiff entries.\n */\nexport function computeSummary(requirements: RequirementDiff[]): ComparisonSummary {\n const summary: ComparisonSummary = {\n fixed: 0,\n regressed: 0,\n new: 0,\n absent: 0,\n unchanged: 0,\n updated: 0,\n total: requirements.length,\n matchedCount: 0,\n unmatchedOldCount: 0,\n unmatchedNewCount: 0,\n };\n\n for (const req of requirements) {\n switch (req.state) {\n case 'fixed':\n summary.fixed++;\n summary.matchedCount++;\n break;\n case 'regressed':\n summary.regressed++;\n summary.matchedCount++;\n break;\n case 'new':\n summary.new++;\n summary.unmatchedNewCount++;\n break;\n case 'absent':\n summary.absent++;\n summary.unmatchedOldCount++;\n break;\n case 'unchanged':\n summary.unchanged++;\n summary.matchedCount++;\n break;\n case 'updated':\n summary.updated++;\n summary.matchedCount++;\n break;\n }\n }\n\n return summary;\n}\n","/**\n * Normalize InSpec exec-json v1 format to HDF v2 structure for diffing.\n *\n * V1 uses: profiles[].controls[].results[].code_desc, source_location, start_time\n * V2 uses: baselines[].requirements[].results[].codeDesc, sourceLocation, startTime\n *\n * This module detects v1 documents and converts them in-memory to v2 shape\n * so the diff engine only needs to handle one format.\n */\n\nimport { parseTimestamp } from '@mitre/hdf-utilities';\n\ninterface V1Result {\n status: string;\n code_desc?: string;\n codeDesc?: string;\n run_time?: number;\n runTime?: number;\n start_time?: string;\n startTime?: string;\n message?: string;\n [key: string]: unknown;\n}\n\ninterface V1Control {\n id: string;\n title?: string;\n desc?: string;\n impact: number;\n tags?: Record<string, unknown>;\n refs?: unknown[];\n code?: string;\n source_location?: { ref?: string; line?: number };\n sourceLocation?: { ref?: string; line?: number };\n results?: V1Result[];\n [key: string]: unknown;\n}\n\ninterface V1Profile {\n name: string;\n title?: string;\n version?: string;\n sha256?: string;\n controls?: V1Control[];\n groups?: unknown[];\n supports?: unknown[];\n attributes?: unknown[];\n [key: string]: unknown;\n}\n\n/**\n * Detect whether a document is v1 (InSpec exec-json) format.\n * V1 has `profiles` at the top level; v2 has `baselines`.\n */\nexport function isV1Format(doc: Record<string, unknown>): boolean {\n return Array.isArray(doc['profiles']) && !Array.isArray(doc['baselines']);\n}\n\n/**\n * Normalize a document to v2-like structure. If already v2, returns as-is.\n * If v1, converts profiles→baselines, controls→requirements, and snake_case→camelCase.\n */\nexport function normalizeToV2(doc: Record<string, unknown>): Record<string, unknown> {\n if (!isV1Format(doc)) {\n return doc;\n }\n\n const profiles = doc['profiles'] as V1Profile[];\n const baselines = profiles.map(normalizeProfile);\n\n // Preserve timestamp from statistics if available\n const statistics = doc['statistics'] as Record<string, unknown> | undefined;\n\n return {\n baselines,\n statistics,\n timestamp: doc['timestamp'],\n };\n}\n\nfunction normalizeProfile(profile: V1Profile): Record<string, unknown> {\n const controls = profile.controls ?? [];\n const requirements = controls.map(normalizeControl);\n\n return {\n name: profile.name,\n title: profile.title,\n version: profile.version,\n checksum: profile.sha256 ? { algorithm: 'sha256', value: profile.sha256 } : undefined,\n groups: profile.groups ?? [],\n supports: profile.supports ?? [],\n inputs: profile.attributes ?? [],\n requirements,\n };\n}\n\nfunction normalizeControl(control: V1Control): Record<string, unknown> {\n const v1Results = control.results ?? [];\n const results = v1Results.map(normalizeResult);\n\n return {\n id: control.id,\n title: control.title,\n descriptions: control.desc\n ? [{ label: 'default', data: control.desc }]\n : [],\n impact: control.impact,\n tags: control.tags ?? {},\n refs: control.refs ?? [],\n code: control.code,\n sourceLocation: control.source_location ?? control.sourceLocation,\n results,\n };\n}\n\n/**\n * Map InSpec v1 result status values to HDF v2 Result_Status enum values.\n *\n * InSpec v1 uses: \"passed\", \"failed\", \"skipped\", \"error\"\n * HDF v2 uses: \"passed\", \"failed\", \"notApplicable\", \"notReviewed\", \"error\"\n *\n * \"skipped\" in InSpec means the test was not executed (typically because a\n * `describe.one_of` condition was not met, or `only_if` excluded it).\n * This maps to \"notReviewed\" in HDF v2 — the requirement was not assessed.\n */\nfunction normalizeResultStatus(v1Status: string): string {\n switch (v1Status) {\n case 'skipped':\n return 'notReviewed';\n default:\n return v1Status;\n }\n}\n\n/**\n * Normalize a timestamp string to RFC 3339 / ISO 8601 date-time format.\n *\n * InSpec v1 uses formats like \"2017-09-22 14:12:15 -0400\" which are not valid\n * RFC 3339. This function attempts to parse and re-format such timestamps.\n * If parsing fails, the original string is returned as-is.\n */\nfunction normalizeTimestamp(timestamp: string): string {\n // Already valid ISO 8601 (contains 'T')\n if (timestamp.includes('T')) {\n return timestamp;\n }\n\n // Parse InSpec format (\"YYYY-MM-DD HH:MM:SS +HHMM\") via the shared helper,\n // which reads a zone-less value as UTC rather than host-local.\n const parsed = parseTimestamp(timestamp);\n if (parsed) {\n return parsed.toISOString();\n }\n\n return timestamp;\n}\n\nfunction normalizeResult(result: V1Result): Record<string, unknown> {\n const rawStartTime = result.start_time ?? result.startTime ?? '';\n const normalized: Record<string, unknown> = {\n status: normalizeResultStatus(result.status),\n codeDesc: result.code_desc ?? result.codeDesc ?? '',\n startTime: rawStartTime ? normalizeTimestamp(rawStartTime) : rawStartTime,\n };\n\n // Only include optional fields when they have values\n const runTime = result.run_time ?? result.runTime;\n if (runTime !== undefined) {\n normalized['runTime'] = runTime;\n }\n if (result.message !== undefined) {\n normalized['message'] = result.message;\n }\n\n return normalized;\n}\n","import type { MatchStrategy, MatchResult } from './types.js';\n\n/**\n * Create an exact ID matching strategy.\n *\n * Matches requirements by their `id` field with exact string equality.\n * Confidence is always 1.0 for matches.\n */\nexport function createExactIdStrategy(): MatchStrategy {\n return {\n name: 'exactId',\n match(oldReqs: Record<string, unknown>[], newReqs: Record<string, unknown>[]): MatchResult {\n const result: MatchResult = {\n matched: [],\n unmatchedOld: [],\n unmatchedNew: [],\n };\n\n // Build a map of new requirements by id, detecting duplicates.\n // When multiple requirements share the same ID, the ID is ambiguous\n // and cannot be used for matching — all duplicates go to unmatchedNew.\n const newById = new Map<string, Record<string, unknown>>();\n const duplicateNewIds = new Set<string>();\n for (const req of newReqs) {\n const id = req['id'];\n if (typeof id === 'string') {\n if (newById.has(id)) {\n // Mark this ID as a duplicate — remove it from the map\n duplicateNewIds.add(id);\n newById.delete(id);\n } else if (!duplicateNewIds.has(id)) {\n newById.set(id, req);\n }\n }\n }\n\n // Build a map of old requirements by id, detecting duplicates.\n const oldById = new Map<string, Record<string, unknown>>();\n const duplicateOldIds = new Set<string>();\n for (const req of oldReqs) {\n const id = req['id'];\n if (typeof id === 'string') {\n if (oldById.has(id)) {\n duplicateOldIds.add(id);\n oldById.delete(id);\n } else if (!duplicateOldIds.has(id)) {\n oldById.set(id, req);\n }\n }\n }\n\n // Track which new reqs have been matched\n const matchedNewIds = new Set<string>();\n\n // Match old requirements against new by id (skip duplicate old IDs)\n for (const oldReq of oldReqs) {\n const id = oldReq['id'];\n if (typeof id !== 'string' || duplicateOldIds.has(id)) {\n result.unmatchedOld.push(oldReq);\n continue;\n }\n\n const newReq = newById.get(id);\n if (newReq) {\n result.matched.push({\n oldReq,\n newReq,\n strategy: 'exactId',\n confidence: 1.0,\n });\n matchedNewIds.add(id);\n } else {\n result.unmatchedOld.push(oldReq);\n }\n }\n\n // Collect unmatched new requirements (including all duplicates)\n for (const req of newReqs) {\n const id = req['id'];\n if (typeof id === 'string') {\n if (duplicateNewIds.has(id) || !matchedNewIds.has(id)) {\n result.unmatchedNew.push(req);\n }\n } else {\n result.unmatchedNew.push(req);\n }\n }\n\n return result;\n },\n };\n}\n","import type { MatchStrategy, MatchResult } from './types.js';\n\n/**\n * Create a mapped ID matching strategy.\n *\n * Translates old requirement IDs using a mapping table before matching.\n * Only matches requirements whose old ID appears in the mapping table and\n * whose mapped new ID exists in the new requirements.\n *\n * Confidence is 0.95 for mapped matches (slightly less than exact ID\n * because the match depends on the accuracy of the mapping table).\n */\nexport function createMappedIdStrategy(mapping: Record<string, string>): MatchStrategy {\n return {\n name: 'mappedId',\n match(oldReqs: Record<string, unknown>[], newReqs: Record<string, unknown>[]): MatchResult {\n const result: MatchResult = {\n matched: [],\n unmatchedOld: [],\n unmatchedNew: [],\n };\n\n // Build a map of new requirements by id, detecting duplicates.\n // When multiple requirements share the same ID, the ID is ambiguous\n // and cannot be used for matching — all duplicates go to unmatchedNew.\n const newById = new Map<string, Record<string, unknown>>();\n const duplicateNewIds = new Set<string>();\n for (const req of newReqs) {\n const id = req['id'];\n if (typeof id === 'string') {\n if (newById.has(id)) {\n duplicateNewIds.add(id);\n newById.delete(id);\n } else if (!duplicateNewIds.has(id)) {\n newById.set(id, req);\n }\n }\n }\n\n // Build a map of old requirements by id, detecting duplicates.\n const oldById = new Map<string, Record<string, unknown>>();\n const duplicateOldIds = new Set<string>();\n for (const req of oldReqs) {\n const id = req['id'];\n if (typeof id === 'string') {\n if (oldById.has(id)) {\n duplicateOldIds.add(id);\n oldById.delete(id);\n } else if (!duplicateOldIds.has(id)) {\n oldById.set(id, req);\n }\n }\n }\n\n // Track which new reqs have been matched\n const matchedNewIds = new Set<string>();\n\n // Try to match old requirements using the mapping table (skip duplicate old IDs)\n for (const oldReq of oldReqs) {\n const oldId = oldReq['id'];\n if (typeof oldId !== 'string' || duplicateOldIds.has(oldId)) {\n result.unmatchedOld.push(oldReq);\n continue;\n }\n\n const mappedNewId = mapping[oldId];\n if (mappedNewId === undefined) {\n result.unmatchedOld.push(oldReq);\n continue;\n }\n\n // Skip if the mapped new ID is a duplicate\n if (duplicateNewIds.has(mappedNewId)) {\n result.unmatchedOld.push(oldReq);\n continue;\n }\n\n const newReq = newById.get(mappedNewId);\n if (newReq && !matchedNewIds.has(mappedNewId)) {\n result.matched.push({\n oldReq,\n newReq,\n strategy: 'mappedId',\n confidence: 0.95,\n });\n matchedNewIds.add(mappedNewId);\n } else {\n result.unmatchedOld.push(oldReq);\n }\n }\n\n // Collect unmatched new requirements (including all duplicates)\n for (const req of newReqs) {\n const id = req['id'];\n if (typeof id === 'string') {\n if (duplicateNewIds.has(id) || !matchedNewIds.has(id)) {\n result.unmatchedNew.push(req);\n }\n } else {\n result.unmatchedNew.push(req);\n }\n }\n\n return result;\n },\n };\n}\n","import type { MatchStrategy, MatchResult } from './types.js';\n\n/**\n * Extract CCI identifiers from a requirement's tags.\n * Looks for `tags.cci` as an array of strings.\n */\nfunction extractCcis(req: Record<string, unknown>): string[] {\n const tags = req['tags'] as Record<string, unknown> | undefined;\n if (!tags) return [];\n const cci = tags['cci'];\n if (!Array.isArray(cci)) return [];\n return cci.filter((c): c is string => typeof c === 'string');\n}\n\n/**\n * Extract CWE identifiers from a requirement.\n *\n * Prefers the structured `req.cwe[]` field (introduced in Evaluated_Requirement\n * Wave 1) when present and non-empty. Falls back to `tags.cwe` for compatibility\n * with HDF files emitted before the structured field existed. `tags.cwe` may be\n * either an array of strings or a single string.\n *\n * Exported for reuse by sibling matchers (e.g. srg-cci-tiebreak) and to make\n * the preference order directly testable.\n */\nexport function extractCwes(req: Record<string, unknown>): string[] {\n const cwe = req['cwe'];\n if (Array.isArray(cwe)) {\n const filtered = cwe.filter((c): c is string => typeof c === 'string');\n if (filtered.length > 0) return filtered;\n }\n const tags = req['tags'] as Record<string, unknown> | undefined;\n if (!tags) return [];\n const tagCwe = tags['cwe'];\n if (Array.isArray(tagCwe)) {\n return tagCwe.filter((c): c is string => typeof c === 'string');\n }\n if (typeof tagCwe === 'string') {\n return [tagCwe];\n }\n return [];\n}\n\n/**\n * Build a key → [requirement-indices] map for unambiguous-pair lookup.\n */\nfunction indexByKey(\n reqs: Record<string, unknown>[],\n keys: (req: Record<string, unknown>) => string[],\n): Map<string, number[]> {\n const map = new Map<string, number[]>();\n for (let i = 0; i < reqs.length; i++) {\n for (const key of keys(reqs[i]!)) {\n const list = map.get(key);\n if (list) {\n list.push(i);\n } else {\n map.set(key, [i]);\n }\n }\n }\n return map;\n}\n\n/**\n * Pair indices by an unambiguous shared key (exactly 1 old + 1 new per key),\n * skipping any indices already claimed in `matchedOld` / `matchedNew`.\n */\nfunction pairUnambiguous(\n oldMap: Map<string, number[]>,\n newMap: Map<string, number[]>,\n matchedOld: Set<number>,\n matchedNew: Set<number>,\n): Array<{ oldIdx: number; newIdx: number }> {\n const pairs: Array<{ oldIdx: number; newIdx: number }> = [];\n const allKeys = new Set([...oldMap.keys(), ...newMap.keys()]);\n for (const key of allKeys) {\n const oldIndices = oldMap.get(key) ?? [];\n const newIndices = newMap.get(key) ?? [];\n if (oldIndices.length !== 1 || newIndices.length !== 1) continue;\n const oldIdx = oldIndices[0]!;\n const newIdx = newIndices[0]!;\n if (matchedOld.has(oldIdx) || matchedNew.has(newIdx)) continue;\n pairs.push({ oldIdx, newIdx });\n matchedOld.add(oldIdx);\n matchedNew.add(newIdx);\n }\n return pairs;\n}\n\n/**\n * Create a CCI-based matching strategy.\n *\n * Matches requirements that share the same CCI identifier in `tags.cci`.\n * Only produces a match when exactly one old requirement and exactly one\n * new requirement share a given CCI (unambiguous). Ambiguous CCIs (shared\n * by multiple old or multiple new requirements) are skipped, and those\n * requirements are left unmatched.\n *\n * As a fallback, also pairs unambiguous CWE matches (preferring the\n * structured `req.cwe[]` field over the legacy `tags.cwe`). This catches\n * CVE-ecosystem findings where CCI is absent but CWE is present.\n *\n * Confidence is 0.8 for CCI matches and 0.6 for CWE-fallback matches.\n */\nexport function createCciMatchStrategy(): MatchStrategy {\n return {\n name: 'cciMatch',\n match(oldReqs: Record<string, unknown>[], newReqs: Record<string, unknown>[]): MatchResult {\n const matchedOldIndices = new Set<number>();\n const matchedNewIndices = new Set<number>();\n const matched: MatchResult['matched'] = [];\n\n // Primary signal: CCI.\n const oldCciMap = indexByKey(oldReqs, extractCcis);\n const newCciMap = indexByKey(newReqs, extractCcis);\n for (const { oldIdx, newIdx } of pairUnambiguous(\n oldCciMap,\n newCciMap,\n matchedOldIndices,\n matchedNewIndices,\n )) {\n matched.push({\n oldReq: oldReqs[oldIdx]!,\n newReq: newReqs[newIdx]!,\n strategy: 'cciMatch',\n confidence: 0.8,\n });\n }\n\n // Fallback signal: CWE (structured field preferred over tags.cwe).\n // All reqs are indexed here; pairUnambiguous skips any already claimed by\n // CCI pairing via the matchedOld/NewIndices sets passed below.\n const oldCweMap = indexByKey(oldReqs, (r) => extractCwes(r));\n const newCweMap = indexByKey(newReqs, (r) => extractCwes(r));\n for (const { oldIdx, newIdx } of pairUnambiguous(\n oldCweMap,\n newCweMap,\n matchedOldIndices,\n matchedNewIndices,\n )) {\n matched.push({\n oldReq: oldReqs[oldIdx]!,\n newReq: newReqs[newIdx]!,\n strategy: 'cciMatch',\n confidence: 0.6,\n });\n }\n\n const unmatchedOld: Record<string, unknown>[] = [];\n for (let i = 0; i < oldReqs.length; i++) {\n if (!matchedOldIndices.has(i)) unmatchedOld.push(oldReqs[i]!);\n }\n const unmatchedNew: Record<string, unknown>[] = [];\n for (let i = 0; i < newReqs.length; i++) {\n if (!matchedNewIndices.has(i)) unmatchedNew.push(newReqs[i]!);\n }\n\n return { matched, unmatchedOld, unmatchedNew };\n },\n };\n}\n","import type { MatchStrategy, MatchResult } from './types.js';\n\n/** Common English stop words to exclude from tokenization */\nconst STOP_WORDS = new Set([\n 'a', 'an', 'the', 'is', 'are', 'was', 'were', 'be', 'been', 'being',\n 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'could',\n 'should', 'may', 'might', 'shall', 'can', 'to', 'of', 'in', 'for',\n 'on', 'with', 'at', 'by', 'from', 'as', 'into', 'through', 'during',\n 'before', 'after', 'above', 'below', 'between', 'out', 'off', 'over',\n 'under', 'again', 'further', 'then', 'once', 'and', 'but', 'or', 'nor',\n 'not', 'no', 'so', 'if', 'it', 'its', 'that', 'this', 'these', 'those',\n 'each', 'every', 'all', 'both', 'few', 'more', 'most', 'other', 'some',\n 'such', 'than', 'too', 'very', 'just', 'about',\n]);\n\n/**\n * Tokenize a title string into a set of meaningful tokens.\n *\n * - Lowercases the string\n * - Splits on whitespace and punctuation\n * - Filters out common stop words\n * - Returns unique tokens as a Set\n */\nexport function tokenize(text: string): Set<string> {\n if (!text) return new Set();\n\n const tokens = text\n .toLowerCase()\n .split(/[\\s\\-_/\\\\,.;:!?()[\\]{}\"']+/)\n .filter((t) => t.length > 0 && !STOP_WORDS.has(t));\n\n return new Set(tokens);\n}\n\n/**\n * Compute Jaccard similarity between two sets.\n * Returns |intersection| / |union|, or 0 if both sets are empty.\n */\nexport function jaccardSimilarity(a: Set<string>, b: Set<string>): number {\n if (a.size === 0 && b.size === 0) return 0.0;\n\n let intersectionSize = 0;\n // Iterate over the smaller set for efficiency\n const [smaller, larger] = a.size <= b.size ? [a, b] : [b, a];\n for (const item of smaller) {\n if (larger.has(item)) {\n intersectionSize++;\n }\n }\n\n const unionSize = a.size + b.size - intersectionSize;\n // Unreachable: if both sets are empty, we return above. If either is non-empty, unionSize > 0.\n // Guard kept for mathematical correctness.\n /* c8 ignore next */\n if (unionSize === 0) return 0.0;\n\n return intersectionSize / unionSize;\n}\n\n/**\n * Default minimum confidence threshold for fuzzy title matching.\n */\nconst DEFAULT_MIN_CONFIDENCE = 0.6;\n\n/**\n * Create a fuzzy title matching strategy.\n *\n * Matches requirements by token-based Jaccard similarity on the `title` field.\n * Uses greedy best-match: for each unmatched old requirement, finds the\n * best-matching unmatched new requirement above the confidence threshold.\n *\n * @param minConfidence Minimum Jaccard similarity to accept a match (default: 0.6)\n */\nexport function createFuzzyTitleStrategy(minConfidence?: number): MatchStrategy {\n const threshold = minConfidence ?? DEFAULT_MIN_CONFIDENCE;\n\n return {\n name: 'fuzzyTitle',\n match(oldReqs: Record<string, unknown>[], newReqs: Record<string, unknown>[]): MatchResult {\n const result: MatchResult = {\n matched: [],\n unmatchedOld: [],\n unmatchedNew: [],\n };\n\n // Pre-tokenize all titles\n const oldTokens: Array<{ idx: number; tokens: Set<string> }> = [];\n for (let i = 0; i < oldReqs.length; i++) {\n const title = oldReqs[i]!['title'];\n if (typeof title === 'string' && title.length > 0) {\n const tokens = tokenize(title);\n if (tokens.size > 0) {\n oldTokens.push({ idx: i, tokens });\n }\n }\n }\n\n const newTokens: Array<{ idx: number; tokens: Set<string> }> = [];\n for (let i = 0; i < newReqs.length; i++) {\n const title = newReqs[i]!['title'];\n if (typeof title === 'string' && title.length > 0) {\n const tokens = tokenize(title);\n if (tokens.size > 0) {\n newTokens.push({ idx: i, tokens });\n }\n }\n }\n\n // Track matched indices\n const matchedOldIndices = new Set<number>();\n const matchedNewIndices = new Set<number>();\n\n // Build a list of all potential matches with similarity scores\n const candidates: Array<{\n oldIdx: number;\n newIdx: number;\n similarity: number;\n }> = [];\n\n for (const old of oldTokens) {\n for (const nw of newTokens) {\n const sim = jaccardSimilarity(old.tokens, nw.tokens);\n if (sim >= threshold) {\n candidates.push({\n oldIdx: old.idx,\n newIdx: nw.idx,\n similarity: sim,\n });\n }\n }\n }\n\n // Sort by similarity descending (greedy best-match)\n candidates.sort((a, b) => b.similarity - a.similarity);\n\n // Greedily assign matches\n for (const candidate of candidates) {\n if (matchedOldIndices.has(candidate.oldIdx) || matchedNewIndices.has(candidate.newIdx)) {\n continue;\n }\n\n result.matched.push({\n oldReq: oldReqs[candidate.oldIdx]!,\n newReq: newReqs[candidate.newIdx]!,\n strategy: 'fuzzyTitle',\n confidence: candidate.similarity,\n });\n matchedOldIndices.add(candidate.oldIdx);\n matchedNewIndices.add(candidate.newIdx);\n }\n\n // Collect unmatched\n for (let i = 0; i < oldReqs.length; i++) {\n if (!matchedOldIndices.has(i)) {\n result.unmatchedOld.push(oldReqs[i]!);\n }\n }\n for (let i = 0; i < newReqs.length; i++) {\n if (!matchedNewIndices.has(i)) {\n result.unmatchedNew.push(newReqs[i]!);\n }\n }\n\n return result;\n },\n };\n}\n","import type { MatchStrategy, MatchResult, MatchPair } from './types.js';\n\n/**\n * Extract the SRG-OS ID from a requirement's tags.gtitle field.\n * Returns null if missing or not a string.\n */\nfunction extractGtitle(req: Record<string, unknown>): string | null {\n const tags = req['tags'] as Record<string, unknown> | undefined;\n if (!tags) return null;\n const gtitle = tags['gtitle'];\n if (typeof gtitle !== 'string' || gtitle === '') return null;\n return gtitle;\n}\n\n/**\n * Create a deterministic SRG matching strategy (Tier 1 of the delta pipeline).\n *\n * Matches requirements by exact `tags.gtitle` (SRG-OS requirement ID).\n *\n * For each gtitle shared between old and new:\n * - 1 old + 1 new → single MatchPair (confidence 1.0, relationship \"primary\")\n * - 1 new + N old → N MatchPairs (first old \"primary\", rest \"related\")\n * - N new + 1 old → N MatchPairs (first new \"primary\", rest \"related\")\n * - N:M (both > 1) → skip, leave for fallback strategies\n *\n * Requirements without a gtitle pass through as unmatched.\n */\nexport function createSrgDeterministicStrategy(): MatchStrategy {\n return {\n name: 'srgDeterministic',\n match(oldReqs: Record<string, unknown>[], newReqs: Record<string, unknown>[]): MatchResult {\n // Build gtitle → indices for old\n const oldGtitleMap = new Map<string, number[]>();\n for (let i = 0; i < oldReqs.length; i++) {\n const g = extractGtitle(oldReqs[i]!);\n if (g) {\n const list = oldGtitleMap.get(g);\n if (list) list.push(i);\n else oldGtitleMap.set(g, [i]);\n }\n }\n\n // Build gtitle → indices for new\n const newGtitleMap = new Map<string, number[]>();\n for (let i = 0; i < newReqs.length; i++) {\n const g = extractGtitle(newReqs[i]!);\n if (g) {\n const list = newGtitleMap.get(g);\n if (list) list.push(i);\n else newGtitleMap.set(g, [i]);\n }\n }\n\n const matched: MatchPair[] = [];\n const matchedOldIndices = new Set<number>();\n const matchedNewIndices = new Set<number>();\n // Track which old indices have been claimed as \"primary\"\n const claimedOldIndices = new Set<number>();\n\n for (const [gtitle, newIdxList] of newGtitleMap) {\n const oldIdxList = oldGtitleMap.get(gtitle);\n if (!oldIdxList || oldIdxList.length === 0) continue;\n\n const nc = newIdxList.length;\n const oc = oldIdxList.length;\n\n // N:M ambiguous — skip\n if (nc > 1 && oc > 1) continue;\n\n // Create match pairs\n for (const ni of newIdxList) {\n let primaryOldSet = false;\n for (const oi of oldIdxList) {\n let relationship: 'primary' | 'related';\n if (oc === 1) {\n // 1 old, possibly multiple new → claim tracking\n relationship = claimedOldIndices.has(oi) ? 'related' : 'primary';\n if (relationship === 'primary') claimedOldIndices.add(oi);\n } else {\n // Multiple old, 1 new → first old is primary\n relationship = primaryOldSet ? 'related' : 'primary';\n primaryOldSet = true;\n }\n\n matched.push({\n oldReq: oldReqs[oi]!,\n newReq: newReqs[ni]!,\n strategy: 'srgDeterministic',\n confidence: 1.0,\n relationship,\n });\n matchedOldIndices.add(oi);\n }\n matchedNewIndices.add(ni);\n }\n }\n\n // Collect unmatched\n const unmatchedOld: Record<string, unknown>[] = [];\n for (let i = 0; i < oldReqs.length; i++) {\n if (!matchedOldIndices.has(i)) unmatchedOld.push(oldReqs[i]!);\n }\n const unmatchedNew: Record<string, unknown>[] = [];\n for (let i = 0; i < newReqs.length; i++) {\n if (!matchedNewIndices.has(i)) unmatchedNew.push(newReqs[i]!);\n }\n\n return { matched, unmatchedOld, unmatchedNew };\n },\n };\n}\n","import type { MatchStrategy, MatchResult, MatchPair } from './types.js';\n\n/** Composite score weights matching SAF CLI's Tier 2. */\nconst CCI_WEIGHT = 0.7;\nconst TITLE_WEIGHT = 0.3;\n\n/**\n * Extract CCI identifiers from a requirement's tags.cci.\n */\nfunction extractCcis(req: Record<string, unknown>): Set<string> {\n const tags = req['tags'] as Record<string, unknown> | undefined;\n if (!tags) return new Set();\n const cci = tags['cci'];\n if (!Array.isArray(cci)) return new Set();\n return new Set(cci.filter((c): c is string => typeof c === 'string'));\n}\n\n/**\n * Extract CWE identifiers from a requirement.\n *\n * Prefers the structured `req.cwe[]` field (introduced in Evaluated_Requirement\n * Wave 1) when present and non-empty. Falls back to `tags.cwe` (array or string)\n * for compatibility with HDF files emitted before the structured field existed.\n *\n * Exported so callers and tests can verify the preference order directly.\n */\nexport function extractCwes(req: Record<string, unknown>): Set<string> {\n const cwe = req['cwe'];\n if (Array.isArray(cwe)) {\n const filtered = cwe.filter((c): c is string => typeof c === 'string');\n if (filtered.length > 0) return new Set(filtered);\n }\n const tags = req['tags'] as Record<string, unknown> | undefined;\n if (!tags) return new Set();\n const tagCwe = tags['cwe'];\n if (Array.isArray(tagCwe)) {\n return new Set(tagCwe.filter((c): c is string => typeof c === 'string'));\n }\n if (typeof tagCwe === 'string') {\n return new Set([tagCwe]);\n }\n return new Set();\n}\n\n/**\n * Extract tags.gtitle from a requirement.\n */\nfunction extractGtitle(req: Record<string, unknown>): string | null {\n const tags = req['tags'] as Record<string, unknown> | undefined;\n if (!tags) return null;\n const gtitle = tags['gtitle'];\n if (typeof gtitle !== 'string' || gtitle === '') return null;\n return gtitle;\n}\n\n/**\n * Extract title from a requirement.\n */\nfunction safeTitle(req: Record<string, unknown>): string {\n const title = req['title'];\n return typeof title === 'string' ? title : '';\n}\n\n/**\n * Jaccard similarity between two sets.\n */\nfunction cciJaccard(a: Set<string>, b: Set<string>): number {\n if (a.size === 0 && b.size === 0) return 0;\n let intersectionSize = 0;\n for (const x of a) {\n if (b.has(x)) intersectionSize++;\n }\n const unionSize = a.size + b.size - intersectionSize;\n return intersectionSize / unionSize;\n}\n\n/**\n * Simple whitespace-split token Jaccard similarity.\n */\nfunction tokenJaccard(a: string, b: string): number {\n const ta = new Set(\n a\n .toLowerCase()\n .split(/\\s+/)\n .filter((t) => t.length > 0),\n );\n const tb = new Set(\n b\n .toLowerCase()\n .split(/\\s+/)\n .filter((t) => t.length > 0),\n );\n if (ta.size === 0 || tb.size === 0) return 0;\n let intersectionSize = 0;\n for (const x of ta) {\n if (tb.has(x)) intersectionSize++;\n }\n const unionSize = ta.size + tb.size - intersectionSize;\n return intersectionSize / unionSize;\n}\n\n/**\n * Create an SRG CCI Tiebreak matching strategy (Tier 2 of the delta pipeline).\n *\n * Handles ambiguous SRG matches where multiple old or new requirements share\n * the same tags.gtitle. Uses a composite score of CCI Jaccard (70%) and\n * token Jaccard on titles (30%) to pick the best match.\n *\n * Only activates for gtitle groups with multiple candidates (>1 old or >1 new).\n * 1:1 matches are left for srgDeterministic (Tier 1).\n */\nexport function createSrgCciTiebreakStrategy(): MatchStrategy {\n return {\n name: 'srgCciTiebreak',\n match(oldReqs: Record<string, unknown>[], newReqs: Record<string, unknown>[]): MatchResult {\n // Build gtitle → indices\n const oldGtitleMap = new Map<string, number[]>();\n for (let i = 0; i < oldReqs.length; i++) {\n const g = extractGtitle(oldReqs[i]!);\n if (g) {\n const list = oldGtitleMap.get(g);\n if (list) list.push(i);\n else oldGtitleMap.set(g, [i]);\n }\n }\n\n const newGtitleMap = new Map<string, number[]>();\n for (let i = 0; i < newReqs.length; i++) {\n const g = extractGtitle(newReqs[i]!);\n if (g) {\n const list = newGtitleMap.get(g);\n if (list) list.push(i);\n else newGtitleMap.set(g, [i]);\n }\n }\n\n const matched: MatchPair[] = [];\n const matchedOldIndices = new Set<number>();\n const matchedNewIndices = new Set<number>();\n\n for (const [gtitle, newIdxList] of newGtitleMap) {\n const oldIdxList = oldGtitleMap.get(gtitle);\n if (!oldIdxList || oldIdxList.length === 0) continue;\n\n const nc = newIdxList.length;\n const oc = oldIdxList.length;\n\n // Only handle ambiguous cases (at least one side > 1)\n // 1:1 is handled by srgDeterministic\n if (nc === 1 && oc === 1) continue;\n\n // Greedy matching: process each new req, find best old candidate\n for (const ni of newIdxList) {\n if (matchedNewIndices.has(ni)) continue;\n\n const newCcis = extractCcis(newReqs[ni]!);\n const newTitle = safeTitle(newReqs[ni]!);\n const newCwes = extractCwes(newReqs[ni]!);\n\n let bestIdx = -1;\n let bestComposite = -1;\n let bestCci = 0;\n let bestCwe = -1;\n let bestIsUnclaimed = false;\n\n for (const oi of oldIdxList) {\n const oldCcis = extractCcis(oldReqs[oi]!);\n const oldTitle = safeTitle(oldReqs[oi]!);\n const oldCwes = extractCwes(oldReqs[oi]!);\n\n const cci = cciJaccard(newCcis, oldCcis);\n const title = tokenJaccard(newTitle, oldTitle);\n // CWE Jaccard is used purely as a tiebreaker — it does NOT\n // change composite scoring weights, so existing tests that\n // depend on CCI+title ordering are unaffected.\n const cwe = cciJaccard(newCwes, oldCwes);\n const composite = CCI_WEIGHT * cci + TITLE_WEIGHT * title;\n const isUnclaimed = !matchedOldIndices.has(oi);\n\n // Prefer unclaimed candidates; among same claim status, prefer\n // higher composite; among equal composites, prefer higher CWE\n // Jaccard (tiebreaker added Wave 2).\n if (\n bestIdx === -1 ||\n (isUnclaimed && !bestIsUnclaimed) ||\n (isUnclaimed === bestIsUnclaimed && composite > bestComposite) ||\n (isUnclaimed === bestIsUnclaimed &&\n composite === bestComposite &&\n cwe > bestCwe)\n ) {\n bestIdx = oi;\n bestComposite = composite;\n bestCci = cci;\n bestCwe = cwe;\n bestIsUnclaimed = isUnclaimed;\n }\n }\n\n if (bestIdx >= 0) {\n const relationship = matchedOldIndices.has(bestIdx) ? 'related' : 'primary';\n matched.push({\n oldReq: oldReqs[bestIdx]!,\n newReq: newReqs[ni]!,\n strategy: 'srgCciTiebreak',\n confidence: Math.max(bestCci, 0),\n relationship,\n });\n matchedOldIndices.add(bestIdx);\n matchedNewIndices.add(ni);\n }\n }\n }\n\n // Collect unmatched\n const unmatchedOld: Record<string, unknown>[] = [];\n for (let i = 0; i < oldReqs.length; i++) {\n if (!matchedOldIndices.has(i)) unmatchedOld.push(oldReqs[i]!);\n }\n const unmatchedNew: Record<string, unknown>[] = [];\n for (let i = 0; i < newReqs.length; i++) {\n if (!matchedNewIndices.has(i)) unmatchedNew.push(newReqs[i]!);\n }\n\n return { matched, unmatchedOld, unmatchedNew };\n },\n };\n}\n","import type { MatchStrategy, MatchResult, MatchPair } from './types.js';\n\n/** Default threshold for accepting a Levenshtein match. */\nconst DEFAULT_ACCEPT_THRESHOLD = 0.45;\n\n// Bounds the Levenshtein DP. Far above any realistic requirement/vendor title,\n// so no real match result changes; beyond it the inputs are not titles, and the\n// O(m*n) DP (plus O(n) allocation) would be a needless cost and an algorithmic-DoS\n// surface, so such pairs get the trivial upper bound instead. Mirrors the Go port\n// (hdf-diff/go/matching/vendor_fuzzy_title.go: maxLevenshteinRunes).\nconst MAX_LEVENSHTEIN_LENGTH = 4096;\n\n/** Modal verbs that mark the start of compliance statements. */\nconst COMPLIANCE_MODALS = new Set([\n 'must', 'will', 'shall', 'should', 'may', 'needs',\n]);\n\n/**\n * Compute the Levenshtein edit distance between two strings.\n */\nexport function levenshteinDistance(a: string, b: string): number {\n const m = a.length;\n const n = b.length;\n if (m === 0) return n;\n if (n === 0) return m;\n\n // Beyond the cap the inputs are not realistic titles: return the trivial upper\n // bound (edit distance never exceeds the longer length) rather than allocating\n // O(n) and running O(m*n). Mirrors the Go port's bound.\n if (m > MAX_LEVENSHTEIN_LENGTH || n > MAX_LEVENSHTEIN_LENGTH) {\n return Math.max(m, n);\n }\n\n // Use single row optimization\n let prev = new Array<number>(n + 1);\n let curr = new Array<number>(n + 1);\n for (let j = 0; j <= n; j++) prev[j] = j;\n\n for (let i = 1; i <= m; i++) {\n curr[0] = i;\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n curr[j] = Math.min(\n prev[j]! + 1, // deletion\n curr[j - 1]! + 1, // insertion\n prev[j - 1]! + cost, // substitution\n );\n }\n [prev, curr] = [curr, prev];\n }\n\n return prev[n]!;\n}\n\n/**\n * Normalized Levenshtein distance (0.0 = identical, 1.0 = completely different).\n */\nexport function normalizedLevenshtein(a: string, b: string): number {\n const maxLen = Math.max(a.length, b.length);\n if (maxLen === 0) return 0.0;\n return levenshteinDistance(a, b) / maxLen;\n}\n\n/**\n * Extract tokens before the first modal verb in a title.\n */\nfunction tokensBeforeModal(title: string): string[] {\n const tokens = title.split(/\\s+/).filter((t) => t.length > 0);\n const modalIdx = tokens.findIndex((t) => COMPLIANCE_MODALS.has(t.toLowerCase()));\n return modalIdx === -1 ? tokens : tokens.slice(0, modalIdx);\n}\n\n/**\n * Auto-detect the dominant vendor prefix in a corpus of titles.\n *\n * Tries progressively shorter leading-token prefixes. Returns the prefix\n * that appears in > 50% of titles, stopping before modal verbs.\n * Returns '' when no prefix reaches the threshold.\n */\nexport function autoDetectPrefix(titles: string[], threshold = 0.5): string {\n if (titles.length === 0) return '';\n\n const leading = titles.map((t) => tokensBeforeModal(t));\n const maxLen = Math.max(...leading.map((l) => l.length));\n\n for (let n = maxLen; n > 0; n--) {\n const counts = new Map<string, number>();\n for (const l of leading) {\n if (l.length >= n) {\n const key = l.slice(0, n).join(' ');\n counts.set(key, (counts.get(key) ?? 0) + 1);\n }\n }\n let bestKey = '';\n let bestCount = 0;\n for (const [key, count] of counts) {\n if (count > bestCount) {\n bestKey = key;\n bestCount = count;\n }\n }\n if (bestCount / titles.length > threshold) {\n return bestKey;\n }\n }\n return '';\n}\n\n/**\n * Strip a detected vendor prefix from a title.\n */\nexport function normalizeTitle(title: string, prefix: string): string {\n if (!prefix) return title;\n if (title === prefix) return '';\n if (title.startsWith(prefix + ' ')) return title.slice(prefix.length + 1);\n return title;\n}\n\n/**\n * Extract title string from a requirement.\n */\nfunction safeTitle(req: Record<string, unknown>): string {\n const title = req['title'];\n return typeof title === 'string' ? title : '';\n}\n\n/**\n * Create a vendor fuzzy title matching strategy (Tier 3 of the delta pipeline).\n *\n * Cross-vendor matching with auto-detected vendor prefix stripping.\n * Uses normalized Levenshtein distance to compare titles after removing\n * the dominant vendor prefix (e.g., \"RHEL 9\" or \"Amazon Linux 2023\").\n *\n * Accepts matches below threshold 0.45 (confidence = 1.0 - distance).\n * Greedy best-match.\n *\n * @param acceptThreshold Max normalized Levenshtein distance to accept (default: 0.45)\n */\nexport function createVendorFuzzyTitleStrategy(acceptThreshold?: number): MatchStrategy {\n const threshold = acceptThreshold ?? DEFAULT_ACCEPT_THRESHOLD;\n\n return {\n name: 'vendorFuzzyTitle',\n match(oldReqs: Record<string, unknown>[], newReqs: Record<string, unknown>[]): MatchResult {\n // Collect titles for prefix detection\n const oldTitles = oldReqs.map(safeTitle).filter((t) => t.length > 0);\n const newTitles = newReqs.map(safeTitle).filter((t) => t.length > 0);\n const oldPrefix = autoDetectPrefix(oldTitles);\n const newPrefix = autoDetectPrefix(newTitles);\n\n // Build candidates with normalized titles\n type IndexedTitle = { idx: number; normalized: string };\n const oldNorm: IndexedTitle[] = [];\n for (let i = 0; i < oldReqs.length; i++) {\n const t = safeTitle(oldReqs[i]!);\n if (t) {\n oldNorm.push({ idx: i, normalized: normalizeTitle(t, oldPrefix) });\n }\n }\n const newNorm: IndexedTitle[] = [];\n for (let i = 0; i < newReqs.length; i++) {\n const t = safeTitle(newReqs[i]!);\n if (t) {\n newNorm.push({ idx: i, normalized: normalizeTitle(t, newPrefix) });\n }\n }\n\n // Compute all pairwise distances\n const candidates: Array<{\n oldIdx: number;\n newIdx: number;\n distance: number;\n }> = [];\n\n for (const old of oldNorm) {\n for (const nw of newNorm) {\n if (!old.normalized || !nw.normalized) continue;\n const dist = normalizedLevenshtein(old.normalized, nw.normalized);\n if (dist < threshold) {\n candidates.push({\n oldIdx: old.idx,\n newIdx: nw.idx,\n distance: dist,\n });\n }\n }\n }\n\n // Sort by distance ascending (best matches first)\n candidates.sort((a, b) => a.distance - b.distance);\n\n // Greedy assignment\n const matched: MatchPair[] = [];\n const matchedOldIndices = new Set<number>();\n const matchedNewIndices = new Set<number>();\n\n for (const c of candidates) {\n if (matchedOldIndices.has(c.oldIdx) || matchedNewIndices.has(c.newIdx)) continue;\n\n matched.push({\n oldReq: oldReqs[c.oldIdx]!,\n newReq: newReqs[c.newIdx]!,\n strategy: 'vendorFuzzyTitle',\n confidence: 1.0 - c.distance,\n relationship: 'primary',\n });\n matchedOldIndices.add(c.oldIdx);\n matchedNewIndices.add(c.newIdx);\n }\n\n // Collect unmatched\n const unmatchedOld: Record<string, unknown>[] = [];\n for (let i = 0; i < oldReqs.length; i++) {\n if (!matchedOldIndices.has(i)) unmatchedOld.push(oldReqs[i]!);\n }\n const unmatchedNew: Record<string, unknown>[] = [];\n for (let i = 0; i < newReqs.length; i++) {\n if (!matchedNewIndices.has(i)) unmatchedNew.push(newReqs[i]!);\n }\n\n return { matched, unmatchedOld, unmatchedNew };\n },\n };\n}\n","import type { MatchResult, MatchStrategy } from './types.js';\nimport { createExactIdStrategy } from './exact-id.js';\nimport { createMappedIdStrategy } from './mapped-id.js';\nimport { createCciMatchStrategy } from './cci-match.js';\nimport { createFuzzyTitleStrategy } from './fuzzy-match.js';\nimport { createSrgDeterministicStrategy } from './srg-deterministic.js';\nimport { createSrgCciTiebreakStrategy } from './srg-cci-tiebreak.js';\nimport { createVendorFuzzyTitleStrategy } from './vendor-fuzzy-title.js';\n\n// Re-export types and factory functions\nexport type { MatchResult, MatchPair, MatchStrategy } from './types.js';\nexport { createExactIdStrategy } from './exact-id.js';\nexport { createMappedIdStrategy } from './mapped-id.js';\nexport { createCciMatchStrategy } from './cci-match.js';\nexport { createFuzzyTitleStrategy, tokenize, jaccardSimilarity } from './fuzzy-match.js';\nexport { createSrgDeterministicStrategy } from './srg-deterministic.js';\nexport { createSrgCciTiebreakStrategy } from './srg-cci-tiebreak.js';\nexport { createVendorFuzzyTitleStrategy, levenshteinDistance, normalizedLevenshtein } from './vendor-fuzzy-title.js';\n\n/**\n * Options for configuring requirement matching.\n */\nexport interface MatchOptions {\n /** Primary matching strategy name (default: 'exactId') */\n strategy?: string;\n /** Fallback strategy names, applied in order to remaining unmatched requirements */\n fallbackStrategies?: string[];\n /** Mapping table for the 'mappedId' strategy (old ID -> new ID) */\n mappingTable?: Record<string, string>;\n /** Minimum confidence threshold for fuzzy matching (default: 0.6) */\n minConfidence?: number;\n}\n\n/**\n * Create a strategy instance by name, using the provided options for\n * strategies that require configuration.\n */\nfunction createStrategy(name: string, options: MatchOptions): MatchStrategy {\n switch (name) {\n case 'exactId':\n return createExactIdStrategy();\n case 'mappedId':\n return createMappedIdStrategy(options.mappingTable ?? {});\n case 'cciMatch':\n return createCciMatchStrategy();\n case 'fuzzyTitle':\n return createFuzzyTitleStrategy(options.minConfidence);\n case 'srgDeterministic':\n return createSrgDeterministicStrategy();\n case 'srgCciTiebreak':\n return createSrgCciTiebreakStrategy();\n case 'vendorFuzzyTitle': {\n // vendorFuzzyTitle is parameterized by a max normalized Levenshtein\n // distance, not a min confidence. Translate (confidence = 1 - distance).\n // Leave undefined when minConfidence is unset/zero so the strategy\n // applies its own default threshold.\n const acceptThreshold =\n options.minConfidence !== undefined && options.minConfidence > 0\n ? 1 - options.minConfidence\n : undefined;\n return createVendorFuzzyTitleStrategy(acceptThreshold);\n }\n default:\n throw new Error(`Unknown matching strategy: '${name}'`);\n }\n}\n\n/**\n * Match requirements between two evaluations using a primary strategy\n * and optional fallback strategies.\n *\n * The registry applies strategies in order:\n * 1. Primary strategy matches what it can\n * 2. Unmatched requirements pass to the next fallback strategy\n * 3. Process continues until all strategies are exhausted or all\n * requirements are matched\n *\n * @param oldReqs Requirements from the old evaluation\n * @param newReqs Requirements from the new evaluation\n * @param options Matching configuration\n * @returns Combined match result from all strategies\n */\nexport function matchRequirements(\n oldReqs: Record<string, unknown>[],\n newReqs: Record<string, unknown>[],\n options?: MatchOptions,\n): MatchResult {\n const opts = options ?? {};\n const primaryName = opts.strategy ?? 'exactId';\n const fallbackNames = opts.fallbackStrategies ?? [];\n\n // Build all strategy instances once up front (also validates names —\n // createStrategy throws for unknown strategy names).\n const allNames = [primaryName, ...fallbackNames];\n const strategies = allNames.map((name) => createStrategy(name, opts));\n\n // Accumulate all matched pairs\n const allMatched: MatchResult['matched'] = [];\n\n // Start with all requirements unmatched\n let currentUnmatchedOld = oldReqs;\n let currentUnmatchedNew = newReqs;\n\n // Apply strategies in order\n for (const strategy of strategies) {\n if (currentUnmatchedOld.length === 0 || currentUnmatchedNew.length === 0) {\n break;\n }\n\n const result = strategy.match(currentUnmatchedOld, currentUnmatchedNew);\n\n allMatched.push(...result.matched);\n currentUnmatchedOld = result.unmatchedOld;\n currentUnmatchedNew = result.unmatchedNew;\n }\n\n return {\n matched: allMatched,\n unmatchedOld: currentUnmatchedOld,\n unmatchedNew: currentUnmatchedNew,\n };\n}\n","import type { ValidationError } from '@mitre/hdf-validators';\nimport { validateComparison as validatorsValidateComparison } from '@mitre/hdf-validators';\n\n/**\n * Result of validating a document against the hdf-comparison schema.\n */\nexport interface ValidationResult {\n /** Whether the document conforms to the schema */\n valid: boolean;\n /** Human-readable error messages (only present when valid is false) */\n errors?: string[];\n}\n\n/**\n * Validate a document against the hdf-comparison schema.\n *\n * Delegates to @mitre/hdf-validators which loads schemas from embedded\n * bundled JSON (no filesystem access, no hardcoded version URLs).\n *\n * @param doc - The document to validate (typically the output of `diffHdf()`)\n * @returns Validation result with `valid` boolean and optional `errors` array\n */\nexport function validateComparison(doc: unknown): ValidationResult {\n const result = validatorsValidateComparison(doc);\n\n if (result.valid) {\n return { valid: true };\n }\n\n const errors = result.errors.map((e: ValidationError) =>\n e.field === '(root)' ? e.message : `${e.field}: ${e.message}`\n );\n return { valid: false, errors };\n}\n","import type {\n HDFComparison,\n RequirementDiff,\n BaselineDiff,\n ComponentDiff,\n FieldChange,\n Source,\n} from './types.js';\nimport { computeEffectiveStatus, classifyChangeReasons, classifyDiffStatus } from './status.js';\nimport { computeSummary } from './summary.js';\nimport { normalizeToV2 } from './normalize.js';\nimport { matchRequirements } from './matching/index.js';\nimport type { MatchOptions } from './matching/index.js';\nimport { validateComparison } from './validate.js';\nimport { parseCvssVector as parseCvssVectorUtil } from '@mitre/hdf-utilities';\n\n/**\n * Options for configuring the diff behavior.\n */\nexport interface DiffOptions {\n /** Fields to track for field-level diffs (default: ['impact', 'severity', 'tags']) */\n trackedFields?: string[];\n /** Comparison mode (default: 'temporal') */\n comparisonMode?: 'temporal' | 'baseline' | 'fleet' | 'multiSource' | 'baselineEvolution' | 'systemDrift';\n /** Primary matching strategy name (default: 'exactId') */\n matchStrategy?: string;\n /** Fallback strategy names, applied in order to remaining unmatched requirements */\n fallbackStrategies?: string[];\n /** Mapping table for the 'mappedId' strategy (old ID -> new ID) */\n mappingTable?: Record<string, string>;\n /** Minimum confidence threshold for fuzzy matching (default: 0.6) */\n minConfidence?: number;\n /** Validate output against hdf-comparison schema. Default: false (performance). */\n validateOutput?: boolean;\n}\n\nexport const DEFAULT_TRACKED_FIELDS = ['impact', 'severity', 'tags'];\n\ninterface BaselineLike {\n name: string;\n version?: string;\n requirements: RequirementLike[];\n}\n\ninterface RequirementLike {\n id: string;\n title?: string;\n impact: number;\n [key: string]: unknown;\n}\n\n/**\n * Round a fuzzy-match confidence (0-1 similarity) to 4 decimal places to strip\n * IEEE-754 noise from the serialized matchConfidence value.\n */\nexport function roundConfidence(x: number): number {\n return Math.round(x * 1e4) / 1e4;\n}\n\n/**\n * Extract a dataSource label from a document, if available.\n * Looks for `dataSource.name` in the raw (pre-normalized) document.\n */\nfunction extractDataSourceLabel(doc: Record<string, unknown>): string | undefined {\n const ds = doc['dataSource'] as Record<string, unknown> | undefined;\n if (ds && typeof ds['name'] === 'string') {\n return ds['name'];\n }\n return undefined;\n}\n\n/**\n * Build MatchOptions from DiffOptions, extracting the matching-related fields.\n */\nfunction buildMatchOptions(options?: DiffOptions): MatchOptions {\n return {\n strategy: options?.matchStrategy,\n fallbackStrategies: options?.fallbackStrategies,\n mappingTable: options?.mappingTable,\n minConfidence: options?.minConfidence,\n };\n}\n\n/**\n * Determine the primary strategy name for the matching config output.\n */\nfunction resolveStrategyName(options?: DiffOptions): string {\n return options?.matchStrategy ?? 'exactId';\n}\n\n/**\n * Compare two HDF results documents and produce a structured comparison.\n *\n * Requirements are matched using a configurable matching strategy (default: exact ID).\n * Baselines are matched by `name`.\n *\n * For fleet mode, `newResults` can be an array of documents, each compared\n * pairwise against `oldResults` (the reference).\n */\nexport function diffHdf(\n oldResults: Record<string, unknown>,\n newResults: Record<string, unknown> | Record<string, unknown>[],\n options?: DiffOptions,\n): HDFComparison {\n const trackedFields = options?.trackedFields ?? DEFAULT_TRACKED_FIELDS;\n let comparisonMode = options?.comparisonMode ?? 'temporal';\n const matchOpts = buildMatchOptions(options);\n\n // Auto-detect baseline evolution mode when both inputs are baseline documents\n // (have requirements[] but no baselines[], targets[], or statistics[])\n if (!options?.comparisonMode && !Array.isArray(newResults)) {\n if (isBaselineDocument(oldResults) && isBaselineDocument(newResults)) {\n comparisonMode = 'baselineEvolution';\n } else if (isSystemDocument(oldResults) && isSystemDocument(newResults)) {\n comparisonMode = 'systemDrift';\n }\n }\n\n // Validate array inputs up front (applies to all modes)\n if (Array.isArray(newResults)) {\n if (newResults.length === 0) {\n throw new Error('newResults array must not be empty');\n }\n if (comparisonMode !== 'fleet' && newResults.length > 1) {\n throw new Error(\n `Mode '${comparisonMode}' expects a single document, got ${newResults.length}. Use 'fleet' mode for multiple documents.`\n );\n }\n }\n\n // Baseline evolution mode: compare two baseline documents\n if (comparisonMode === 'baselineEvolution') {\n const newDoc = Array.isArray(newResults) ? newResults[0]! : newResults;\n return diffBaselines(oldResults, newDoc, options);\n }\n\n // System drift mode: compare two system documents\n if (comparisonMode === 'systemDrift') {\n const newDoc = Array.isArray(newResults) ? newResults[0]! : newResults;\n return diffSystems(oldResults, newDoc, options);\n }\n\n // Fleet mode: compare reference against each system\n if (comparisonMode === 'fleet') {\n return diffFleet(oldResults, newResults, trackedFields, matchOpts);\n }\n\n // Non-fleet modes: newResults must be a single document\n const newDoc = Array.isArray(newResults) ? newResults[0]! : newResults;\n\n // Normalize v1 (InSpec exec-json) to v2 if needed\n const oldNormalized = normalizeToV2(oldResults);\n const newNormalized = normalizeToV2(newDoc);\n\n const oldTimestamp = oldNormalized['timestamp'] as string | undefined;\n const newTimestamp = newNormalized['timestamp'] as string | undefined;\n\n // Build sources metadata based on mode\n const sources = buildSources(comparisonMode, oldResults, newDoc, oldTimestamp, newTimestamp);\n\n // Compute baseline and requirement diffs\n const { baselineDiffs, requirementDiffs } = comparePair(\n oldNormalized, newNormalized, oldTimestamp, newTimestamp, trackedFields, matchOpts,\n );\n\n // Sort by id\n requirementDiffs.sort((a, b) => a.id.localeCompare(b.id));\n\n // Extract drift: unchanged requirements with metadata changes\n const drift = extractDrift(requirementDiffs);\n\n const comparison: HDFComparison = {\n formatVersion: '1.0.0',\n comparisonMode,\n timestamp: new Date().toISOString(),\n sources,\n matching: {\n primaryStrategy: resolveStrategyName(options),\n },\n summary: computeSummary(requirementDiffs),\n baselineDiffs,\n requirementDiffs,\n drift,\n };\n\n if (options?.validateOutput) {\n const result = validateComparison(comparison);\n // Safety net: diffHdf always produces valid output by construction.\n // This branch is unreachable in normal operation but guards against future regressions.\n /* c8 ignore start */\n if (!result.valid) {\n throw new Error(`Output validation failed: ${result.errors?.join(', ')}`);\n }\n /* c8 ignore stop */\n }\n\n return comparison;\n}\n\n/**\n * Build source metadata entries based on comparison mode.\n */\nfunction buildSources(\n mode: 'temporal' | 'baseline' | 'multiSource',\n oldDoc: Record<string, unknown>,\n newDoc: Record<string, unknown>,\n oldTimestamp?: string,\n newTimestamp?: string,\n): Source[] {\n switch (mode) {\n case 'baseline':\n return [\n { role: 'golden', label: 'Golden baseline', assessmentTimestamp: oldTimestamp },\n { role: 'new', label: 'Current scan', assessmentTimestamp: newTimestamp },\n ];\n\n case 'multiSource': {\n const oldLabel = extractDataSourceLabel(oldDoc) ?? 'Old evaluation';\n const newLabel = extractDataSourceLabel(newDoc) ?? 'New evaluation';\n return [\n { role: 'old', label: oldLabel, assessmentTimestamp: oldTimestamp },\n { role: 'new', label: newLabel, assessmentTimestamp: newTimestamp },\n ];\n }\n\n case 'temporal':\n default:\n return [\n { role: 'old', label: 'Old evaluation', assessmentTimestamp: oldTimestamp },\n { role: 'new', label: 'New evaluation', assessmentTimestamp: newTimestamp },\n ];\n }\n}\n\n/**\n * Fleet mode: compare a reference document against one or more system documents.\n * Each system is compared pairwise against the reference; all diffs are collected\n * into a single result with `sourceIndex` set on each RequirementDiff.\n */\nfunction diffFleet(\n referenceDoc: Record<string, unknown>,\n newResults: Record<string, unknown> | Record<string, unknown>[],\n trackedFields: string[],\n matchOpts: MatchOptions,\n): HDFComparison {\n const systems = Array.isArray(newResults) ? newResults : [newResults];\n\n const refNormalized = normalizeToV2(referenceDoc);\n const refTimestamp = refNormalized['timestamp'] as string | undefined;\n\n // Build sources, compare each system against the reference, and collect diffs\n // in a single pass — each system document is normalized exactly once.\n const sources: Source[] = [\n { role: 'reference', label: 'Reference', assessmentTimestamp: refTimestamp },\n ];\n const allRequirementDiffs: RequirementDiff[] = [];\n const allBaselineDiffs: BaselineDiff[] = [];\n // Deduplicate baseline diffs by name: first-wins. In fleet mode, every system\n // is compared against the same reference, so the first occurrence of a\n // BaselineDiff for a given baseline name is representative. BaselineDiff does\n // not carry a sourceIndex in v1 of the schema, so per-system baseline tracking\n // is deferred to a future version.\n const seenBaselineNames = new Set<string>();\n\n for (let i = 0; i < systems.length; i++) {\n const sysNormalized = normalizeToV2(systems[i]!);\n const sysTimestamp = sysNormalized['timestamp'] as string | undefined;\n const sourceIndex = i + 1;\n\n // Build the source entry for this system\n sources.push({\n role: 'system',\n label: `System ${sourceIndex}`,\n assessmentTimestamp: sysTimestamp,\n });\n\n const { baselineDiffs, requirementDiffs } = comparePair(\n refNormalized, sysNormalized, refTimestamp, sysTimestamp, trackedFields, matchOpts,\n );\n\n // Tag each requirement diff with its source index\n for (const rd of requirementDiffs) {\n rd.sourceIndex = sourceIndex;\n allRequirementDiffs.push(rd);\n }\n\n // Collect baseline diffs (first-wins dedup; see comment above)\n for (const bd of baselineDiffs) {\n if (!seenBaselineNames.has(bd.name)) {\n seenBaselineNames.add(bd.name);\n allBaselineDiffs.push(bd);\n }\n }\n }\n\n // Sort by id, then by sourceIndex\n allRequirementDiffs.sort((a, b) => {\n const idCmp = a.id.localeCompare(b.id);\n if (idCmp !== 0) return idCmp;\n /* c8 ignore next -- sourceIndex is always set in fleet mode; ?? 0 is defensive typing */\n return (a.sourceIndex ?? 0) - (b.sourceIndex ?? 0);\n });\n\n // Extract drift: unchanged requirements with metadata changes\n const drift = extractDrift(allRequirementDiffs);\n\n return {\n formatVersion: '1.0.0',\n comparisonMode: 'fleet',\n timestamp: new Date().toISOString(),\n sources,\n matching: {\n primaryStrategy: matchOpts.strategy ?? 'exactId',\n },\n summary: computeSummary(allRequirementDiffs),\n baselineDiffs: allBaselineDiffs,\n requirementDiffs: allRequirementDiffs,\n drift,\n };\n}\n\n/**\n * Extract drift entries from requirement diffs.\n *\n * Drift = requirements whose effective status is unchanged but whose metadata\n * changed (tags, descriptions, impact score, etc.). These are the \"silent\"\n * changes that don't affect pass/fail outcome but still matter for auditing.\n *\n * Returns shallow copies so drift entries are independent of requirementDiffs.\n */\nexport function extractDrift(requirementDiffs: RequirementDiff[]): RequirementDiff[] {\n return requirementDiffs\n .filter(r => r.state === 'unchanged' && r.changeReasons.length > 0)\n .map(r => ({ ...r }));\n}\n\n/**\n * Core pairwise comparison between two normalized HDF documents.\n * Returns baseline diffs and requirement diffs without sorting or wrapping.\n *\n * Uses the pluggable matching system to pair requirements between evaluations.\n */\nfunction comparePair(\n oldNormalized: Record<string, unknown>,\n newNormalized: Record<string, unknown>,\n oldTimestamp: string | undefined,\n newTimestamp: string | undefined,\n trackedFields: string[],\n matchOpts: MatchOptions,\n): { baselineDiffs: BaselineDiff[]; requirementDiffs: RequirementDiff[] } {\n const oldBaselines = (oldNormalized['baselines'] as BaselineLike[] | undefined) ?? [];\n const newBaselines = (newNormalized['baselines'] as BaselineLike[] | undefined) ?? [];\n\n // Build baseline maps by name\n const oldBaselineMap = new Map<string, BaselineLike>();\n for (const b of oldBaselines) {\n oldBaselineMap.set(b.name, b);\n }\n const newBaselineMap = new Map<string, BaselineLike>();\n for (const b of newBaselines) {\n newBaselineMap.set(b.name, b);\n }\n\n // Compute baseline diffs\n const allBaselineNames = new Set([...oldBaselineMap.keys(), ...newBaselineMap.keys()]);\n const baselineDiffs: BaselineDiff[] = [];\n\n for (const name of allBaselineNames) {\n const oldB = oldBaselineMap.get(name);\n const newB = newBaselineMap.get(name);\n\n if (oldB && newB) {\n const versionChanged = oldB.version !== newB.version;\n baselineDiffs.push({\n name,\n oldVersion: oldB.version,\n newVersion: newB.version,\n state: versionChanged ? 'updated' : 'unchanged',\n });\n } else if (oldB && !newB) {\n baselineDiffs.push({\n name,\n oldVersion: oldB.version,\n state: 'absent',\n });\n } else if (!oldB && newB) {\n baselineDiffs.push({\n name,\n newVersion: newB.version,\n state: 'new',\n });\n }\n }\n\n // Collect all requirements across all baselines\n const oldReqs: Record<string, unknown>[] = [];\n for (const baseline of oldBaselines) {\n for (const req of baseline.requirements) {\n oldReqs.push(req as unknown as Record<string, unknown>);\n }\n }\n const newReqs: Record<string, unknown>[] = [];\n for (const baseline of newBaselines) {\n for (const req of baseline.requirements) {\n newReqs.push(req as unknown as Record<string, unknown>);\n }\n }\n\n // Use the matching system to pair requirements\n const matchResult = matchRequirements(oldReqs, newReqs, matchOpts);\n\n // Build requirement diffs from match results\n const requirementDiffs: RequirementDiff[] = [];\n\n // Matched pairs\n for (const pair of matchResult.matched) {\n const oldReq = pair.oldReq as RequirementLike;\n const newReq = pair.newReq as RequirementLike;\n /* c8 ignore next -- id is always a string on RequirementLike; ?? is defensive typing */\n const id = (newReq.id ?? oldReq.id) as string;\n\n const oldStatus = computeEffectiveStatus(\n oldReq as unknown as Record<string, unknown>,\n oldTimestamp,\n );\n const newStatus = computeEffectiveStatus(\n newReq as unknown as Record<string, unknown>,\n newTimestamp,\n );\n\n const diffState = classifyDiffStatus(oldStatus, newStatus);\n const changeReasons = classifyChangeReasons(\n oldReq as unknown as Record<string, unknown>,\n newReq as unknown as Record<string, unknown>,\n oldTimestamp,\n newTimestamp,\n );\n\n const fieldChanges = computeFieldChanges(oldReq, newReq, trackedFields);\n\n requirementDiffs.push({\n id,\n title: newReq.title ?? oldReq.title,\n state: diffState,\n oldEffectiveStatus: oldStatus,\n newEffectiveStatus: newStatus,\n changeReasons,\n oldImpact: oldReq.impact,\n newImpact: newReq.impact,\n fieldChanges,\n before: oldReq as unknown as Record<string, unknown>,\n after: newReq as unknown as Record<string, unknown>,\n matchStrategy: pair.strategy,\n matchConfidence: roundConfidence(pair.confidence),\n });\n }\n\n // Unmatched old requirements (absent)\n for (const req of matchResult.unmatchedOld) {\n const oldReq = req as RequirementLike;\n const id = oldReq.id as string;\n const oldStatus = computeEffectiveStatus(\n oldReq as unknown as Record<string, unknown>,\n oldTimestamp,\n );\n requirementDiffs.push({\n id,\n title: oldReq.title,\n state: 'absent',\n oldEffectiveStatus: oldStatus,\n changeReasons: [],\n oldImpact: oldReq.impact,\n fieldChanges: [],\n before: oldReq as unknown as Record<string, unknown>,\n after: null,\n });\n }\n\n // Unmatched new requirements (new)\n for (const req of matchResult.unmatchedNew) {\n const newReq = req as RequirementLike;\n const id = newReq.id as string;\n const newStatus = computeEffectiveStatus(\n newReq as unknown as Record<string, unknown>,\n newTimestamp,\n );\n requirementDiffs.push({\n id,\n title: newReq.title,\n state: 'new',\n newEffectiveStatus: newStatus,\n changeReasons: [],\n newImpact: newReq.impact,\n fieldChanges: [],\n before: null,\n after: newReq as unknown as Record<string, unknown>,\n });\n }\n\n return { baselineDiffs, requirementDiffs };\n}\n\n/** Field names handled by dedicated CVE-ecosystem diff handlers (not generic JSON compare). */\nconst CVE_ECOSYSTEM_FIELDS = new Set(['cvss', 'epss', 'kev', 'cwe', 'affectedPackages']);\n\n/**\n * Compute field-level changes for tracked fields between two requirements.\n * Uses JSON Patch-like op/path format.\n *\n * Always runs the CVE-ecosystem handlers (cvss, epss, kev, cwe, affectedPackages)\n * in addition to whatever scalar fields are in trackedFields, since these\n * structured types need richer diff than generic JSON comparison provides.\n */\nexport function computeFieldChanges(\n oldReq: RequirementLike,\n newReq: RequirementLike,\n trackedFields: string[],\n): FieldChange[] {\n const changes: FieldChange[] = [];\n\n for (const field of trackedFields) {\n // CVE-ecosystem fields are handled below by dedicated handlers\n if (CVE_ECOSYSTEM_FIELDS.has(field)) continue;\n\n const oldVal = oldReq[field];\n const newVal = newReq[field];\n\n // Deep comparison for objects/arrays\n if (JSON.stringify(oldVal) !== JSON.stringify(newVal)) {\n if (oldVal === undefined && newVal !== undefined) {\n changes.push({\n op: 'add',\n path: field,\n newValue: newVal,\n });\n } else if (oldVal !== undefined && newVal === undefined) {\n changes.push({\n op: 'remove',\n path: field,\n oldValue: oldVal,\n });\n } else {\n changes.push({\n op: 'replace',\n path: field,\n oldValue: oldVal,\n newValue: newVal,\n });\n }\n }\n }\n\n // Always run CVE-ecosystem handlers — these fields are part of the v3.x\n // Evaluated_Requirement structured types and need typed diffing regardless\n // of the trackedFields setting.\n changes.push(...diffCvssArray(oldReq['cvss'], newReq['cvss']));\n changes.push(...diffEpss(oldReq['epss'], newReq['epss']));\n changes.push(...diffKev(oldReq['kev'], newReq['kev']));\n changes.push(...diffCweSet(oldReq['cwe'], newReq['cwe']));\n changes.push(...diffAffectedPackages(oldReq['affectedPackages'], newReq['affectedPackages']));\n\n return changes;\n}\n\n// ── CVE-ecosystem diff handlers ─────────────────────────────────────────\n\ninterface CvssEntry {\n source?: string;\n baseScore?: number;\n baseSeverity?: string;\n baseVector?: string;\n threatScore?: number;\n threatVector?: string;\n environmentalScore?: number;\n environmentalVector?: string;\n supplementalVector?: string;\n [key: string]: unknown;\n}\n\nconst CVSS_VECTOR_FIELDS = [\n 'baseVector',\n 'threatVector',\n 'environmentalVector',\n 'supplementalVector',\n] as const;\n\n/**\n * Parse a CVSS vector string into a map of metric-code → value.\n *\n * Accepts both v3.x (\"CVSS:3.1/AV:N/AC:L/...\") and v4.0 (\"CVSS:4.0/AV:N/...\")\n * shapes, plus partial vectors that omit the version prefix (e.g., the\n * `threatVector` field is conventionally just the threat metrics).\n *\n * Returns `null` for inputs that don't look like CVSS vectors so callers\n * can fall back to a scalar string compare.\n *\n * Delegates to `parseCvssVector` from `@mitre/hdf-utilities` but adapts the\n * return shape: returns null for empty/unparseable inputs so call sites can\n * fall back to scalar string compare.\n */\nfunction parseCvssVector(vec: string): { version?: string; metrics: Map<string, string> } | null {\n if (typeof vec !== 'string' || vec.length === 0) return null;\n const parsed = parseCvssVectorUtil(vec);\n if (parsed.metrics.size === 0) return null;\n return {\n version: parsed.version === 'unknown' ? undefined : parsed.version,\n metrics: parsed.metrics,\n };\n}\n\n/**\n * Diff a single pair of cvss entries (same source). Emits per-field changes\n * including decomposed per-metric vector diffs.\n */\nfunction diffCvssEntry(\n source: string,\n oldEntry: CvssEntry,\n newEntry: CvssEntry,\n): FieldChange[] {\n const changes: FieldChange[] = [];\n const allKeys = new Set([...Object.keys(oldEntry), ...Object.keys(newEntry)]);\n\n for (const key of allKeys) {\n if (key === 'source') continue;\n const oldVal = oldEntry[key];\n const newVal = newEntry[key];\n if (JSON.stringify(oldVal) === JSON.stringify(newVal)) continue;\n\n // Vector fields: decompose into per-metric records when both parse cleanly\n if ((CVSS_VECTOR_FIELDS as readonly string[]).includes(key)) {\n if (typeof oldVal === 'string' && typeof newVal === 'string') {\n const oldParsed = parseCvssVector(oldVal);\n const newParsed = parseCvssVector(newVal);\n if (oldParsed && newParsed) {\n const metricKeys = new Set<string>([\n ...oldParsed.metrics.keys(), ...newParsed.metrics.keys(),\n ]);\n for (const m of metricKeys) {\n const o = oldParsed.metrics.get(m);\n const n = newParsed.metrics.get(m);\n if (o === n) continue;\n if (o === undefined && n !== undefined) {\n changes.push({ op: 'add', path: `cvss[${source}].${key}.${m}`, newValue: n });\n } else if (o !== undefined && n === undefined) {\n changes.push({ op: 'remove', path: `cvss[${source}].${key}.${m}`, oldValue: o });\n } else {\n changes.push({\n op: 'replace', path: `cvss[${source}].${key}.${m}`, oldValue: o, newValue: n,\n });\n }\n }\n continue;\n }\n } else if (oldVal === undefined && typeof newVal === 'string') {\n // Whole vector added — decompose into per-metric add records\n const parsed = parseCvssVector(newVal);\n if (parsed) {\n for (const [m, v] of parsed.metrics) {\n changes.push({ op: 'add', path: `cvss[${source}].${key}.${m}`, newValue: v });\n }\n continue;\n }\n } else if (typeof oldVal === 'string' && newVal === undefined) {\n const parsed = parseCvssVector(oldVal);\n if (parsed) {\n for (const [m, v] of parsed.metrics) {\n changes.push({ op: 'remove', path: `cvss[${source}].${key}.${m}`, oldValue: v });\n }\n continue;\n }\n }\n // Fall through to scalar replace for unparseable / mixed-type cases\n }\n\n if (oldVal === undefined) {\n changes.push({ op: 'add', path: `cvss[${source}].${key}`, newValue: newVal });\n } else if (newVal === undefined) {\n changes.push({ op: 'remove', path: `cvss[${source}].${key}`, oldValue: oldVal });\n } else {\n changes.push({\n op: 'replace', path: `cvss[${source}].${key}`, oldValue: oldVal, newValue: newVal,\n });\n }\n }\n\n return changes;\n}\n\n/**\n * Diff old vs new cvss[] arrays. Entries are matched by `source` (CVE ID\n * or scoring authority); added/removed entries emit whole-entry add/remove\n * records; matched pairs are decomposed via diffCvssEntry.\n */\nfunction diffCvssArray(oldField: unknown, newField: unknown): FieldChange[] {\n const oldArr = Array.isArray(oldField) ? (oldField as CvssEntry[]) : [];\n const newArr = Array.isArray(newField) ? (newField as CvssEntry[]) : [];\n if (oldArr.length === 0 && newArr.length === 0) return [];\n\n const oldBySource = new Map<string, CvssEntry>();\n for (const e of oldArr) {\n if (typeof e?.source === 'string') oldBySource.set(e.source, e);\n }\n const newBySource = new Map<string, CvssEntry>();\n for (const e of newArr) {\n if (typeof e?.source === 'string') newBySource.set(e.source, e);\n }\n\n const changes: FieldChange[] = [];\n const allSources = new Set([...oldBySource.keys(), ...newBySource.keys()]);\n for (const source of allSources) {\n const o = oldBySource.get(source);\n const n = newBySource.get(source);\n if (o && !n) {\n changes.push({ op: 'remove', path: `cvss[${source}]`, oldValue: o });\n } else if (!o && n) {\n changes.push({ op: 'add', path: `cvss[${source}]`, newValue: n });\n } else if (o && n) {\n changes.push(...diffCvssEntry(source, o, n));\n }\n }\n return changes;\n}\n\n/** Diff the optional `epss` object (score, percentile, date). */\nfunction diffEpss(oldField: unknown, newField: unknown): FieldChange[] {\n if (oldField === undefined && newField === undefined) return [];\n if (oldField === undefined) {\n return [{ op: 'add', path: 'epss', newValue: newField }];\n }\n if (newField === undefined) {\n return [{ op: 'remove', path: 'epss', oldValue: oldField }];\n }\n if (typeof oldField !== 'object' || typeof newField !== 'object' || oldField === null || newField === null) {\n if (JSON.stringify(oldField) === JSON.stringify(newField)) return [];\n return [{ op: 'replace', path: 'epss', oldValue: oldField, newValue: newField }];\n }\n const oldObj = oldField as Record<string, unknown>;\n const newObj = newField as Record<string, unknown>;\n const changes: FieldChange[] = [];\n const allKeys = new Set([...Object.keys(oldObj), ...Object.keys(newObj)]);\n for (const key of allKeys) {\n const o = oldObj[key];\n const n = newObj[key];\n if (JSON.stringify(o) === JSON.stringify(n)) continue;\n if (o === undefined) {\n changes.push({ op: 'add', path: `epss.${key}`, newValue: n });\n } else if (n === undefined) {\n changes.push({ op: 'remove', path: `epss.${key}`, oldValue: o });\n } else {\n changes.push({ op: 'replace', path: `epss.${key}`, oldValue: o, newValue: n });\n }\n }\n return changes;\n}\n\n/**\n * Diff the optional `kev` object. Flips of `inKev` from false→true (or\n * fresh add with `inKev: true`) get an annotated `message` field calling\n * out the CISA KEV catalog inclusion.\n */\nfunction diffKev(oldField: unknown, newField: unknown): FieldChange[] {\n if (oldField === undefined && newField === undefined) return [];\n if (oldField === undefined) {\n const change: FieldChange = { op: 'add', path: 'kev', newValue: newField };\n const nObj = newField as Record<string, unknown> | null;\n if (nObj && nObj['inKev'] === true) {\n const dateAdded = typeof nObj['dateAdded'] === 'string' ? nObj['dateAdded'] : 'unknown date';\n change.message = `Newly added to CISA KEV catalog as of ${dateAdded}`;\n }\n return [change];\n }\n if (newField === undefined) {\n return [{ op: 'remove', path: 'kev', oldValue: oldField }];\n }\n if (typeof oldField !== 'object' || typeof newField !== 'object' || oldField === null || newField === null) {\n if (JSON.stringify(oldField) === JSON.stringify(newField)) return [];\n return [{ op: 'replace', path: 'kev', oldValue: oldField, newValue: newField }];\n }\n const oldObj = oldField as Record<string, unknown>;\n const newObj = newField as Record<string, unknown>;\n const changes: FieldChange[] = [];\n const allKeys = new Set([...Object.keys(oldObj), ...Object.keys(newObj)]);\n for (const key of allKeys) {\n const o = oldObj[key];\n const n = newObj[key];\n if (JSON.stringify(o) === JSON.stringify(n)) continue;\n let change: FieldChange;\n if (o === undefined) {\n change = { op: 'add', path: `kev.${key}`, newValue: n };\n } else if (n === undefined) {\n change = { op: 'remove', path: `kev.${key}`, oldValue: o };\n } else {\n change = { op: 'replace', path: `kev.${key}`, oldValue: o, newValue: n };\n }\n // Annotate the significant false→true inKev flip\n if (key === 'inKev' && o === false && n === true) {\n const dateAdded = typeof newObj['dateAdded'] === 'string' ? newObj['dateAdded'] : 'unknown date';\n change.message = `Newly added to CISA KEV catalog as of ${dateAdded}`;\n }\n changes.push(change);\n }\n return changes;\n}\n\n/** Diff the `cwe[]` field as a set — order does not matter. */\nfunction diffCweSet(oldField: unknown, newField: unknown): FieldChange[] {\n const toSet = (v: unknown): Set<string> => {\n if (!Array.isArray(v)) return new Set();\n return new Set(v.filter((x): x is string => typeof x === 'string'));\n };\n const oldSet = toSet(oldField);\n const newSet = toSet(newField);\n if (oldSet.size === 0 && newSet.size === 0) return [];\n const changes: FieldChange[] = [];\n for (const c of newSet) {\n if (!oldSet.has(c)) changes.push({ op: 'add', path: 'cwe', newValue: c });\n }\n for (const c of oldSet) {\n if (!newSet.has(c)) changes.push({ op: 'remove', path: 'cwe', oldValue: c });\n }\n return changes;\n}\n\ninterface AffectedPackage {\n name?: string;\n version?: string;\n cpe?: string;\n purl?: string;\n fixedInVersion?: string;\n [key: string]: unknown;\n}\n\n/** Build the natural key for an AffectedPackage: `name@version`. */\nfunction packageKey(pkg: AffectedPackage): string | null {\n const name = pkg?.name;\n const version = pkg?.version;\n if (typeof name !== 'string' || name.length === 0) return null;\n if (typeof version !== 'string' || version.length === 0) return null;\n return `${name}@${version}`;\n}\n\n/**\n * Diff a single pair of affectedPackages entries (matched by name+version).\n * Emits per-field changes for cpe / purl / fixedInVersion and any other\n * non-key fields that differ.\n */\nfunction diffAffectedPackageEntry(\n key: string,\n oldPkg: AffectedPackage,\n newPkg: AffectedPackage,\n): FieldChange[] {\n const changes: FieldChange[] = [];\n const allKeys = new Set([...Object.keys(oldPkg), ...Object.keys(newPkg)]);\n for (const k of allKeys) {\n if (k === 'name' || k === 'version') continue; // part of the match key\n const o = oldPkg[k];\n const n = newPkg[k];\n if (JSON.stringify(o) === JSON.stringify(n)) continue;\n if (o === undefined) {\n changes.push({ op: 'add', path: `affectedPackages[${key}].${k}`, newValue: n });\n } else if (n === undefined) {\n changes.push({ op: 'remove', path: `affectedPackages[${key}].${k}`, oldValue: o });\n } else {\n changes.push({\n op: 'replace', path: `affectedPackages[${key}].${k}`, oldValue: o, newValue: n,\n });\n }\n }\n return changes;\n}\n\n/**\n * Diff old vs new affectedPackages[] arrays. Entries are matched by the\n * `name@version` tuple; added/removed packages emit whole-entry records;\n * matched pairs are decomposed via diffAffectedPackageEntry.\n */\nfunction diffAffectedPackages(oldField: unknown, newField: unknown): FieldChange[] {\n const oldArr = Array.isArray(oldField) ? (oldField as AffectedPackage[]) : [];\n const newArr = Array.isArray(newField) ? (newField as AffectedPackage[]) : [];\n if (oldArr.length === 0 && newArr.length === 0) return [];\n\n const oldByKey = new Map<string, AffectedPackage>();\n for (const p of oldArr) {\n const k = packageKey(p);\n if (k) oldByKey.set(k, p);\n }\n const newByKey = new Map<string, AffectedPackage>();\n for (const p of newArr) {\n const k = packageKey(p);\n if (k) newByKey.set(k, p);\n }\n\n const changes: FieldChange[] = [];\n const allKeys = new Set([...oldByKey.keys(), ...newByKey.keys()]);\n for (const key of allKeys) {\n const o = oldByKey.get(key);\n const n = newByKey.get(key);\n if (o && !n) {\n changes.push({ op: 'remove', path: `affectedPackages[${key}]`, oldValue: o });\n } else if (!o && n) {\n changes.push({ op: 'add', path: `affectedPackages[${key}]`, newValue: n });\n } else if (o && n) {\n changes.push(...diffAffectedPackageEntry(key, o, n));\n }\n }\n return changes;\n}\n\n/**\n * Detect whether a document is a baseline (not results).\n * Baselines have `requirements` at the top level and lack `baselines`, `targets`, and `statistics`.\n */\nfunction isBaselineDocument(doc: Record<string, unknown>): boolean {\n return (\n Array.isArray(doc['requirements']) &&\n !Array.isArray(doc['baselines']) &&\n !Array.isArray(doc['targets']) &&\n doc['statistics'] === undefined\n );\n}\n\n/** Default tracked fields for baseline evolution comparisons. */\nconst BASELINE_TRACKED_FIELDS = ['title', 'impact', 'descriptions', 'tags'];\n\n/**\n * Compare two HDF baseline documents and produce a structured comparison\n * showing requirement changes between baseline versions.\n *\n * Unlike diffHdf (which compares results/evaluations), this compares baseline\n * definitions — requirements without results. There is no status-based classification\n * (fixed/regressed); only metadata changes (title, impact, descriptions, tags) are tracked.\n */\nexport function diffBaselines(\n oldBaseline: Record<string, unknown>,\n newBaseline: Record<string, unknown>,\n options?: DiffOptions,\n): HDFComparison {\n const trackedFields = options?.trackedFields ?? BASELINE_TRACKED_FIELDS;\n const matchOpts = buildMatchOptions(options);\n\n // Extract requirements from baseline documents\n const oldReqs = (oldBaseline['requirements'] as RequirementLike[] | undefined) ?? [];\n const newReqs = (newBaseline['requirements'] as RequirementLike[] | undefined) ?? [];\n\n // Use the matching system to pair requirements\n const matchResult = matchRequirements(\n oldReqs as unknown as Record<string, unknown>[],\n newReqs as unknown as Record<string, unknown>[],\n matchOpts,\n );\n\n // Build requirement diffs from match results\n const requirementDiffs: RequirementDiff[] = [];\n\n // Matched pairs\n for (const pair of matchResult.matched) {\n const oldReq = pair.oldReq as RequirementLike;\n const newReq = pair.newReq as RequirementLike;\n const id = (newReq.id ?? oldReq.id) as string;\n\n const fieldChanges = computeFieldChanges(oldReq, newReq, trackedFields);\n\n // For baseline evolution, state is determined by metadata changes only\n const state: 'unchanged' | 'updated' = fieldChanges.length > 0 ? 'updated' : 'unchanged';\n\n // Determine change reasons for baseline evolution\n const changeReasons: Array<'impactChanged' | 'metadataChanged'> = [];\n if (oldReq.impact !== newReq.impact) {\n changeReasons.push('impactChanged');\n }\n const oldTags = JSON.stringify(oldReq['tags'] ?? {});\n const newTags = JSON.stringify(newReq['tags'] ?? {});\n const oldDescs = JSON.stringify(oldReq['descriptions'] ?? []);\n const newDescs = JSON.stringify(newReq['descriptions'] ?? []);\n const oldTitle = oldReq['title'] as string | undefined;\n const newTitle = newReq['title'] as string | undefined;\n if (oldTags !== newTags || oldDescs !== newDescs || oldTitle !== newTitle) {\n changeReasons.push('metadataChanged');\n }\n\n requirementDiffs.push({\n id,\n title: newReq.title ?? oldReq.title,\n state,\n changeReasons,\n oldImpact: oldReq.impact,\n newImpact: newReq.impact,\n fieldChanges,\n before: oldReq as unknown as Record<string, unknown>,\n after: newReq as unknown as Record<string, unknown>,\n matchStrategy: pair.strategy,\n matchConfidence: roundConfidence(pair.confidence),\n });\n }\n\n // Unmatched old requirements (absent)\n for (const req of matchResult.unmatchedOld) {\n const oldReq = req as RequirementLike;\n requirementDiffs.push({\n id: oldReq.id,\n title: oldReq.title,\n state: 'absent',\n changeReasons: [],\n oldImpact: oldReq.impact,\n fieldChanges: [],\n before: oldReq as unknown as Record<string, unknown>,\n after: null,\n });\n }\n\n // Unmatched new requirements (new)\n for (const req of matchResult.unmatchedNew) {\n const newReq = req as RequirementLike;\n requirementDiffs.push({\n id: newReq.id,\n title: newReq.title,\n state: 'new',\n changeReasons: [],\n newImpact: newReq.impact,\n fieldChanges: [],\n before: null,\n after: newReq as unknown as Record<string, unknown>,\n });\n }\n\n // Sort by id\n requirementDiffs.sort((a, b) => a.id.localeCompare(b.id));\n\n // Build baseline diff from top-level baseline metadata\n const oldName = oldBaseline['name'] as string | undefined ?? '';\n const newName = newBaseline['name'] as string | undefined ?? '';\n const oldVersion = oldBaseline['version'] as string | undefined;\n const newVersion = newBaseline['version'] as string | undefined;\n\n const baselineDiffs: BaselineDiff[] = [];\n const baselineName = newName || oldName;\n if (baselineName) {\n const versionChanged = oldVersion !== newVersion;\n baselineDiffs.push({\n name: baselineName,\n oldVersion,\n newVersion,\n state: versionChanged ? 'updated' : 'unchanged',\n });\n }\n\n // Build sources\n const sources: Source[] = [\n { role: 'old', label: oldVersion ? `${baselineName} ${oldVersion}` : baselineName || 'Old baseline' },\n { role: 'new', label: newVersion ? `${baselineName} ${newVersion}` : baselineName || 'New baseline' },\n ];\n\n const comparison: HDFComparison = {\n formatVersion: '1.0.0',\n comparisonMode: 'baselineEvolution',\n timestamp: new Date().toISOString(),\n sources,\n matching: {\n primaryStrategy: resolveStrategyName(options),\n },\n summary: computeSummary(requirementDiffs),\n baselineDiffs,\n requirementDiffs,\n };\n\n if (options?.validateOutput) {\n const result = validateComparison(comparison);\n /* c8 ignore start */\n if (!result.valid) {\n throw new Error(`Output validation failed: ${result.errors?.join(', ')}`);\n }\n /* c8 ignore stop */\n }\n\n return comparison;\n}\n\n/**\n * Detect whether a document is a system document (has components[] but no baselines/requirements).\n */\nfunction isSystemDocument(doc: Record<string, unknown>): boolean {\n return (\n Array.isArray(doc['components']) &&\n !Array.isArray(doc['baselines']) &&\n !Array.isArray(doc['requirements']) &&\n doc['statistics'] === undefined\n );\n}\n\n/** Fields tracked for system-level field changes. */\nconst SYSTEM_TOP_LEVEL_FIELDS = ['authorizationStatus', 'categorizationLevel', 'description'];\n\n/** Fields tracked for component-level field changes. */\nconst COMPONENT_TRACKED_FIELDS = [\n 'type', 'description', 'baselineRefs', 'inputOverrides', 'boms', 'integrity', 'targetSelector',\n];\n\n/**\n * Compare two HDF system documents and produce a structured comparison\n * showing component-level changes between system versions.\n *\n * Components are matched by componentId (UUID) when available, falling back\n * to exact name matching. Top-level system fields, data flows, and embedded\n * SBOMs are also compared.\n */\nexport function diffSystems(\n oldSystem: Record<string, unknown>,\n newSystem: Record<string, unknown>,\n options?: DiffOptions,\n): HDFComparison {\n const oldComponents = (oldSystem['components'] as Record<string, unknown>[] | undefined) ?? [];\n const newComponents = (newSystem['components'] as Record<string, unknown>[] | undefined) ?? [];\n\n // Match components: prefer componentId, fall back to name\n const pairs = matchComponents(oldComponents, newComponents);\n const componentDiffs: ComponentDiff[] = [];\n\n for (const { oldComp, newComp, name } of pairs) {\n if (oldComp && newComp) {\n const fieldChanges = computeComponentFieldChanges(oldComp, newComp, COMPONENT_TRACKED_FIELDS);\n const state = fieldChanges.length > 0 ? 'updated' : 'unchanged';\n componentDiffs.push({ name, state, before: oldComp, after: newComp, fieldChanges });\n } else if (oldComp && !newComp) {\n componentDiffs.push({ name, state: 'absent', before: oldComp, after: null, fieldChanges: [] });\n } else if (!oldComp && newComp) {\n componentDiffs.push({ name, state: 'new', before: null, after: newComp, fieldChanges: [] });\n }\n }\n\n componentDiffs.sort((a, b) => a.name.localeCompare(b.name));\n\n // Compare top-level system fields\n const systemFieldChanges = computeComponentFieldChanges(\n oldSystem, newSystem, SYSTEM_TOP_LEVEL_FIELDS,\n );\n\n // Build summary counts based on component diffs\n const counts = { new: 0, absent: 0, unchanged: 0, updated: 0 };\n for (const cd of componentDiffs) {\n counts[cd.state]++;\n }\n\n const oldName = oldSystem['name'] as string | undefined ?? '';\n const newName = newSystem['name'] as string | undefined ?? '';\n const systemName = newName || oldName;\n\n const sources: Source[] = [\n { role: 'old', label: systemName ? `${systemName} (old)` : 'Old system' },\n { role: 'new', label: systemName ? `${systemName} (new)` : 'New system' },\n ];\n\n const comparison: HDFComparison = {\n formatVersion: '1.0.0',\n comparisonMode: 'systemDrift',\n timestamp: new Date().toISOString(),\n sources,\n summary: {\n total: pairs.length,\n matchedCount: counts.unchanged + counts.updated,\n unmatchedOldCount: counts.absent,\n unmatchedNewCount: counts.new,\n new: counts.new,\n absent: counts.absent,\n unchanged: counts.unchanged,\n updated: counts.updated,\n fixed: 0,\n regressed: 0,\n },\n baselineDiffs: [],\n requirementDiffs: [],\n componentDiffs,\n };\n\n // Extensions: system field changes + data flow changes\n const extensions: Record<string, unknown> = {};\n if (systemFieldChanges.length > 0) {\n extensions['systemFieldChanges'] = systemFieldChanges;\n }\n const dataFlowChanges = diffDataFlows(oldSystem, newSystem);\n if (dataFlowChanges.length > 0) {\n extensions['dataFlowChanges'] = dataFlowChanges;\n }\n if (Object.keys(extensions).length > 0) {\n comparison.extensions = extensions;\n }\n\n if (options?.validateOutput) {\n const result = validateComparison(comparison);\n /* c8 ignore start */\n if (!result.valid) {\n throw new Error(`Output validation failed: ${result.errors?.join(', ')}`);\n }\n /* c8 ignore stop */\n }\n\n return comparison;\n}\n\ninterface ComponentPair {\n name: string;\n oldComp: Record<string, unknown> | undefined;\n newComp: Record<string, unknown> | undefined;\n}\n\n/**\n * Match old and new components by componentId (when available) or name.\n */\nfunction matchComponents(\n oldComponents: Record<string, unknown>[],\n newComponents: Record<string, unknown>[],\n): ComponentPair[] {\n const matched = new Set<number>(); // indices of matched new components\n const pairs: ComponentPair[] = [];\n\n // First pass: match by componentId\n const newById = new Map<string, number>();\n for (let i = 0; i < newComponents.length; i++) {\n const id = newComponents[i]!['componentId'] as string | undefined;\n if (id) newById.set(id, i);\n }\n\n const oldMatched = new Set<number>();\n for (let i = 0; i < oldComponents.length; i++) {\n const oldId = oldComponents[i]!['componentId'] as string | undefined;\n if (oldId && newById.has(oldId)) {\n const ni = newById.get(oldId)!;\n const newComp = newComponents[ni]!;\n pairs.push({\n name: (newComp['name'] as string) || (oldComponents[i]!['name'] as string) || oldId,\n oldComp: oldComponents[i],\n newComp,\n });\n matched.add(ni);\n oldMatched.add(i);\n }\n }\n\n // Second pass: match remaining by name\n const newByName = new Map<string, number>();\n for (let i = 0; i < newComponents.length; i++) {\n if (matched.has(i)) continue;\n const name = newComponents[i]!['name'] as string;\n if (name) newByName.set(name, i);\n }\n\n for (let i = 0; i < oldComponents.length; i++) {\n if (oldMatched.has(i)) continue;\n const name = oldComponents[i]!['name'] as string;\n if (name && newByName.has(name)) {\n const ni = newByName.get(name)!;\n pairs.push({ name, oldComp: oldComponents[i], newComp: newComponents[ni] });\n matched.add(ni);\n oldMatched.add(i);\n newByName.delete(name);\n }\n }\n\n // Unmatched old → absent\n for (let i = 0; i < oldComponents.length; i++) {\n if (oldMatched.has(i)) continue;\n const name = (oldComponents[i]!['name'] as string) || `component-${i}`;\n pairs.push({ name, oldComp: oldComponents[i], newComp: undefined });\n }\n\n // Unmatched new → new\n for (let i = 0; i < newComponents.length; i++) {\n if (matched.has(i)) continue;\n const name = (newComponents[i]!['name'] as string) || `component-${i}`;\n pairs.push({ name, oldComp: undefined, newComp: newComponents[i] });\n }\n\n return pairs;\n}\n\n/**\n * Diff data flows between two system documents. Flows are keyed by from+to.\n */\nfunction diffDataFlows(\n oldSystem: Record<string, unknown>,\n newSystem: Record<string, unknown>,\n): Array<{ state: string; flow: Record<string, unknown> }> {\n const oldFlows = (oldSystem['dataFlows'] as Record<string, unknown>[] | undefined) ?? [];\n const newFlows = (newSystem['dataFlows'] as Record<string, unknown>[] | undefined) ?? [];\n\n if (oldFlows.length === 0 && newFlows.length === 0) return [];\n\n const flowKey = (f: Record<string, unknown>): string => {\n const from = f['from'] as string ?? '';\n const to = typeof f['to'] === 'string' ? f['to'] as string : JSON.stringify(f['to']);\n return `${from}→${to}`;\n };\n\n const oldMap = new Map<string, Record<string, unknown>>();\n for (const f of oldFlows) oldMap.set(flowKey(f), f);\n const newMap = new Map<string, Record<string, unknown>>();\n for (const f of newFlows) newMap.set(flowKey(f), f);\n\n const allKeys = new Set([...oldMap.keys(), ...newMap.keys()]);\n const changes: Array<{ state: string; flow: Record<string, unknown> }> = [];\n\n for (const key of allKeys) {\n const oldF = oldMap.get(key);\n const newF = newMap.get(key);\n if (oldF && newF) {\n if (JSON.stringify(oldF) !== JSON.stringify(newF)) {\n changes.push({ state: 'updated', flow: newF });\n }\n } else if (oldF && !newF) {\n changes.push({ state: 'removed', flow: oldF });\n } else if (!oldF && newF) {\n changes.push({ state: 'added', flow: newF });\n }\n }\n\n return changes;\n}\n\n/**\n * Compute field-level changes for component or system fields.\n * Uses JSON Patch-like op/path format.\n */\nfunction computeComponentFieldChanges(\n oldObj: Record<string, unknown>,\n newObj: Record<string, unknown>,\n trackedFields: string[],\n): FieldChange[] {\n const changes: FieldChange[] = [];\n\n for (const field of trackedFields) {\n const oldVal = oldObj[field];\n const newVal = newObj[field];\n\n if (JSON.stringify(oldVal) !== JSON.stringify(newVal)) {\n if (oldVal === undefined && newVal !== undefined) {\n changes.push({ op: 'add', path: field, newValue: newVal });\n } else if (oldVal !== undefined && newVal === undefined) {\n changes.push({ op: 'remove', path: field, oldValue: oldVal });\n } else {\n changes.push({ op: 'replace', path: field, oldValue: oldVal, newValue: newVal });\n }\n }\n }\n\n return changes;\n}\n","import { governingOverrideIndex, sha256, type StatusOverrideInput } from '@mitre/hdf-utilities';\nimport { computeEffectiveStatus } from './status.js';\n\ninterface ImpactOverrideLike {\n value: number;\n}\n\ninterface OverrideLike {\n type?: string;\n status?: string;\n impact?: ImpactOverrideLike;\n appliedAt?: string;\n expiresAt: string;\n}\n\nexport interface EffectiveChecksum {\n algorithm: 'sha256';\n value: string;\n}\n\n/** Maps overrides onto the shared neutral selection shape (applied/expiry\n * window only; eligibility is passed separately). */\nfunction overrideWindows(overrides: readonly OverrideLike[]): StatusOverrideInput[] {\n return overrides.map((o) => ({ appliedAt: o.appliedAt, expiresAt: o.expiresAt }));\n}\n\n/**\n * Resolves a requirement's impact for the effective checksum: the governing\n * impact override when one exists, else the requirement's own. With no\n * overrides at all it honours a stored effectiveImpact — deliberately, and\n * unlike computeEffectiveImpact in @mitre/hdf-utilities, which never reads the\n * cache. The checksum is an epoch-sensitive contract: a document whose producer\n * recorded a re-score without the override detail would otherwise change its\n * checksum on upgrade with nothing in it having changed. The field is a\n * fallback, not a source: any override at all makes it unread. Pinned by the\n * \"stored fallback\" test. (Go parity: ComputeEffectiveImpact in go/effective_checksum.go.)\n */\nexport function computeEffectiveImpact(\n requirement: Record<string, unknown>,\n referenceTimestamp?: string,\n): number {\n const baseImpact = (requirement['impact'] as number | undefined) ?? 0;\n const overrides = requirement['statusOverrides'] as OverrideLike[] | undefined;\n\n if (overrides && overrides.length > 0) {\n const i = governingOverrideIndex(\n overrideWindows(overrides),\n (idx) => overrides[idx]?.impact !== undefined,\n referenceTimestamp,\n );\n if (i >= 0) {\n return overrides[i]!.impact!.value;\n }\n return baseImpact;\n }\n\n const effectiveImpact = requirement['effectiveImpact'] as number | undefined;\n if (effectiveImpact !== undefined) {\n return effectiveImpact;\n }\n return baseImpact;\n}\n\n/**\n * Return the Override_Type of the governing (most recently applied\n * non-expired) override, a stored disposition field when no overrides are\n * present, or null. (Go parity: ComputeDisposition.)\n */\nexport function computeDisposition(\n requirement: Record<string, unknown>,\n referenceTimestamp?: string,\n): string | null {\n // Overrides and POA&Ms are ONE ordered set compared on appliedAt, not two\n // tiers — the schema defines disposition as 'the most recent non-expired\n // override or POAM governing this requirement', and both carry the same two\n // timestamp fields. Only the override half was ever implemented.\n // Parity: ComputeDisposition in hdf-diff/go/effective_checksum.go.\n const overrides = (requirement['statusOverrides'] as OverrideLike[] | undefined) ?? [];\n const poams = (requirement['poams'] as OverrideLike[] | undefined) ?? [];\n\n if (overrides.length > 0 || poams.length > 0) {\n const windows = [...overrideWindows(overrides), ...overrideWindows(poams)];\n const i = governingOverrideIndex(windows, () => true, referenceTimestamp);\n if (i < 0) return null;\n if (i < overrides.length) return overrides[i]?.type ?? null;\n // A POA&M's own kind is not a member of Override_Type, which disposition is\n // typed as, so every governing POA&M reports the flat 'poam'.\n return 'poam';\n }\n\n const disposition = requirement['disposition'] as string | undefined;\n return disposition ?? null;\n}\n\n/**\n * Hash the resolved effective posture of a requirement: sha256 over the\n * canonical JSON {\"status\":<resolved>,\"impact\":<resolved>,\"disposition\":<type|null>}.\n * Flips exactly when the operative status, impact, or disposition changes;\n * stable under all other document churn. Byte-identical with the Go\n * implementation (ComputeEffectiveChecksum) — the key order of the canonical\n * object is part of the contract. Pass the document timestamp as\n * referenceTimestamp for determinism. A missing or unparseable reference\n * falls back to the wall clock inside the shared governing-override helper,\n * so callers that need reproducible output must always supply a valid\n * timestamp.\n */\nexport async function computeEffectiveChecksum(\n requirement: Record<string, unknown>,\n referenceTimestamp?: string,\n): Promise<EffectiveChecksum> {\n const canonical = JSON.stringify({\n status: computeEffectiveStatus(requirement, referenceTimestamp),\n impact: computeEffectiveImpact(requirement, referenceTimestamp),\n disposition: computeDisposition(requirement, referenceTimestamp),\n });\n return { algorithm: 'sha256', value: await sha256(canonical) };\n}\n","import {\n computeEffectiveChecksum,\n computeEffectiveImpact,\n type EffectiveChecksum,\n} from './effective-checksum.js';\nimport { computeEffectiveStatus, classifyChangeReasons, classifyDiffStatus } from './status.js';\nimport type { ChangeReason } from './types.js';\n\n/**\n * The reconciler's per-key last-value state (ADR-0005 §1): the minimal\n * posture a producer compares against to decide whether a requirement moved.\n * Go parity: KeyState in hdf-diff/go/change_event.go.\n */\nexport interface KeyState {\n effectiveStatus: string;\n effectiveImpact: number;\n checksum: EffectiveChecksum;\n}\n\n/**\n * Caller-injected envelope identity for an emitted event. Everything is\n * supplied by the caller — the kernel touches no wall clock and no RNG, so\n * identical inputs always produce identical events. referenceTimestamp\n * anchors override expiry (pass the new document's timestamp); timestamp is\n * the event's occurrence time (RFC 3339, trimmed UTC).\n */\nexport interface EventInputs {\n eventId: string;\n source: string;\n sequence: number;\n systemRef: string;\n componentId: string;\n requirementId: string;\n timestamp: string;\n referenceTimestamp: string;\n /** Prior observation's timestamp — enables overrideExpired detection across the window. */\n prevReferenceTimestamp?: string;\n schemaRef?: string;\n}\n\n/** Batch ChangeReason → event-vocabulary mapping; unmapped reasons are batch-only. */\nconst EVENT_REASON_FOR: Partial<Record<ChangeReason, string>> = {\n resultChanged: 'resultChanged',\n overrideAdded: 'overrideAdded',\n overrideExpired: 'overrideExpired',\n overrideRemoved: 'overrideRemoved',\n impactChanged: 'impactChanged',\n effectiveImpactChanged: 'impactChanged',\n};\n\nfunction classifyEventReasons(\n prev: KeyState,\n newReq: Record<string, unknown>,\n prevReq: Record<string, unknown> | null,\n inputs: EventInputs,\n): string[] {\n const reasons: string[] = [];\n const add = (r: string | undefined): void => {\n if (r && !reasons.includes(r)) reasons.push(r);\n };\n\n if (prevReq) {\n const prevRef = inputs.prevReferenceTimestamp ?? inputs.referenceTimestamp;\n for (const r of classifyChangeReasons(prevReq, newReq, prevRef, inputs.referenceTimestamp)) {\n add(EVENT_REASON_FOR[r]);\n }\n return reasons;\n }\n\n if (computeEffectiveImpact(newReq, inputs.referenceTimestamp) !== prev.effectiveImpact) {\n add('impactChanged');\n }\n return reasons;\n}\n\n/**\n * The pure detection kernel (ADR-0005): compare a requirement's resolved\n * posture against the stored last-value state and emit a\n * Requirement_Change_Event when it moved, or null when it did not.\n *\n * - prev null → state \"new\" (chain start: null before/priorChecksum)\n * - newReq null → state \"absent\" (after null, thin before preserved)\n * - checksum match → null (no event; the steady-state majority)\n * - otherwise → fixed/regressed/updated per the effective-status\n * transition, with the full after requirement as payload\n *\n * prevReq (optional) is the full prior requirement when the caller's\n * materialized state has it; it enables complete changeReasons\n * classification via the batch classifier, filtered to the event\n * vocabulary. Without it, only reasons provable from the thin state\n * (impactChanged) are emitted. Byte-parity with the Go kernel\n * (ChangeEventFromPrevious) is pinned by shared test vectors.\n */\nexport async function changeEventFromPrevious(\n prev: KeyState | null,\n newReq: Record<string, unknown> | null,\n prevReq: Record<string, unknown> | null,\n inputs: EventInputs,\n): Promise<Record<string, unknown> | null> {\n if (!prev && !newReq) {\n return null;\n }\n\n const envelope: Record<string, unknown> = {\n eventId: inputs.eventId,\n source: inputs.source,\n sequence: inputs.sequence,\n systemRef: inputs.systemRef,\n componentId: inputs.componentId,\n requirementId: inputs.requirementId,\n timestamp: inputs.timestamp,\n ...(inputs.schemaRef !== undefined ? { schemaRef: inputs.schemaRef } : {}),\n };\n\n if (!prev) {\n return { ...envelope, priorChecksum: null, state: 'new', before: null, after: newReq };\n }\n\n const before = {\n effectiveStatus: prev.effectiveStatus,\n effectiveImpact: prev.effectiveImpact,\n };\n\n if (!newReq) {\n return {\n ...envelope,\n priorChecksum: { ...prev.checksum },\n state: 'absent',\n before,\n after: null,\n };\n }\n\n const newChecksum = await computeEffectiveChecksum(newReq, inputs.referenceTimestamp);\n if (newChecksum.value === prev.checksum.value) {\n return null;\n }\n\n const newStatus = computeEffectiveStatus(newReq, inputs.referenceTimestamp);\n const transition = classifyDiffStatus(prev.effectiveStatus, newStatus);\n // Status unchanged but the checksum moved: impact or disposition shifted.\n const state = transition === 'fixed' || transition === 'regressed' ? transition : 'updated';\n\n const changeReasons = classifyEventReasons(prev, newReq, prevReq, inputs);\n return {\n ...envelope,\n priorChecksum: { ...prev.checksum },\n state,\n ...(changeReasons.length > 0 ? { changeReasons } : {}),\n before,\n after: newReq,\n };\n}\n","import { computeEffectiveChecksum } from './effective-checksum.js';\n\ntype Doc = Record<string, unknown>;\n\n/** Extract the priorChecksum hex from an event ('' when null/absent). */\nexport function eventPriorValue(ev: Doc): string {\n const prior = ev['priorChecksum'] as { value?: string } | null | undefined;\n return prior?.value ?? '';\n}\n\n/** Effective checksum of a requirement ('' when absent). */\nexport async function requirementChecksum(req: Doc | null, referenceTimestamp: string): Promise<string> {\n if (!req) return '';\n return (await computeEffectiveChecksum(req, referenceTimestamp)).value;\n}\n\n/**\n * Drop duplicate (source, eventId) deliveries — the fold contract's\n * idempotency key (ADR-0005 §4). Go parity: dedupEvents.\n */\nexport function dedupEvents(events: Doc[]): Doc[] {\n const seen = new Set<string>();\n const deduped: Doc[] = [];\n for (const ev of events) {\n if (!ev) continue;\n const key = `${String(ev['source'])}|${String(ev['eventId'])}`;\n if (seen.has(key)) continue;\n seen.add(key);\n deduped.push(ev);\n }\n return deduped;\n}\n\n/**\n * Group events per entity key, each chain ordered by sequence (eventId\n * tie-break), keys sorted for deterministic iteration. Go parity:\n * groupEventChains.\n */\nexport function groupEventChains(events: Doc[]): { byKey: Map<string, Doc[]>; keys: string[] } {\n const byKey = new Map<string, Doc[]>();\n for (const ev of events) {\n const id = ev['requirementId'] as string;\n const chain = byKey.get(id) ?? [];\n chain.push(ev);\n byKey.set(id, chain);\n }\n const keys = [...byKey.keys()].sort();\n for (const [, chain] of byKey) {\n chain.sort((a, b) => {\n const seqA = a['sequence'] as number;\n const seqB = b['sequence'] as number;\n if (seqA !== seqB) return seqA - seqB;\n return String(a['eventId']).localeCompare(String(b['eventId']));\n });\n }\n return { byKey, keys };\n}\n\n/**\n * Walk a per-key chain's priorChecksum links from the seed posture forward,\n * reporting anomalies through keyWarn. Best-effort: expiry anchored to each\n * event's occurrence time. Unanchored chains (key not in seed, first event\n * not new) are left to the caller's application outcome. Go parity:\n * verifyEventChain.\n */\nexport async function verifyEventChain(\n chain: Doc[],\n seedReq: Doc | null,\n inSeed: boolean,\n keyWarn: (kind: string, message: string) => void,\n): Promise<void> {\n const first = chain[0];\n if (!first) return;\n if (!inSeed && first['state'] !== 'new') return;\n\n let expected = '';\n if (seedReq) {\n expected = await requirementChecksum(seedReq, first['timestamp'] as string);\n }\n for (const ev of chain) {\n const prior = eventPriorValue(ev);\n if (ev['state'] === 'new') {\n if (inSeed) {\n keyWarn('newOnExisting', 'state new for a key already present in the seed');\n } else if (prior !== '') {\n keyWarn('chainGap', 'new-state event carries a non-null priorChecksum');\n }\n } else if (prior !== expected) {\n // Two indistinguishable causes: events genuinely missing from the chain,\n // or a chain derived under an older effective-status semantics (a\n // checksum epoch — the resolved status the checksum hashes changed\n // across binary versions).\n keyWarn(\n 'chainGap',\n `priorChecksum \"${prior}\" does not match expected chain state \"${expected}\" — either events are missing from this chain, or it was derived under an older effective-status semantics (see status-determination.md); re-derive from a fresh rescan to re-anchor`,\n );\n }\n expected = await requirementChecksum(ev['after'] as Doc | null, ev['timestamp'] as string);\n }\n}\n","import { formatTimestamp, parseTimestamp, sha256 } from '@mitre/hdf-utilities';\nimport {\n dedupEvents,\n groupEventChains,\n verifyEventChain,\n} from './event-stream-common.js';\n\n/**\n * Caller-supplied identity for a reassembly run. Everything else in the\n * derivation block is computed from the seed text and the event batch — no\n * wall clock, no RNG. Go parity: ApplyInputs in hdf-diff/go/apply_events.go.\n */\nexport interface ApplyInputs {\n /** Names the reconciling tool — a reconciled document never masquerades as scanner output. */\n generator: { name: string; version: string };\n /** Locates the seed snapshot; its checksum is computed from the seed text. */\n seedUri: string;\n /** The event-stream producer context recorded in the derivation block. */\n source: string;\n}\n\n/**\n * A non-fatal per-key anomaly. Warnings never abort the fold: the key is\n * still applied last-value-wins and the warning marks it unverified\n * (ADR-0005 §4 fold contract).\n */\nexport interface ApplyWarning {\n requirementId: string;\n /** chainGap | newOnExisting | absentUnknown | multiBaseline */\n kind: string;\n message: string;\n}\n\nexport interface ApplyResult {\n results: Record<string, unknown>;\n warnings: ApplyWarning[];\n}\n\ntype Doc = Record<string, unknown>;\n\nfunction findRequirement(\n doc: Doc,\n id: string,\n): { baseline: Doc; requirements: Doc[]; index: number } | null {\n const baselines = (doc['baselines'] as Doc[] | undefined) ?? [];\n for (const baseline of baselines) {\n const requirements = (baseline['requirements'] as Doc[] | undefined) ?? [];\n const index = requirements.findIndex((r) => r['id'] === id);\n if (index >= 0) {\n return { baseline, requirements, index };\n }\n }\n return null;\n}\n\n/**\n * Reassemble the current posture from a seed hdf-results document plus a\n * batch of requirement-change events (ADR-0005 §§4-7): keyed last-value-wins\n * by sequence, idempotent via (source, eventId) dedup, tombstone-aware\n * (absent removes), total over the event-state enum. Delivery order and\n * duplicates never change the output. The result carries the caller's\n * generator and a derivation block (seed pinned by content, watermark,\n * count, asOf) so it can never masquerade as scan evidence. Chain gaps and\n * anomalies surface as warnings, never as refusal. Go parity:\n * ApplyChangeEvents.\n */\nexport async function applyChangeEvents(\n seedJson: string,\n events: Doc[],\n inputs: ApplyInputs,\n): Promise<ApplyResult> {\n const doc = JSON.parse(seedJson) as Doc;\n const seedChecksum = await sha256(seedJson);\n const docTimestamp = (doc['timestamp'] as string | undefined) ?? '';\n\n const { byKey, keys } = groupEventChains(dedupEvents(events));\n\n const warnings: ApplyWarning[] = [];\n let maxSequence = 0;\n let maxOccurredMs = Number.NEGATIVE_INFINITY;\n let asOfFromEvents = '';\n let eventsApplied = 0;\n const insertions: { sequence: number; id: string; payload: Doc }[] = [];\n\n for (const id of keys) {\n const chain = byKey.get(id) ?? [];\n const first = chain[0];\n const winner = chain[chain.length - 1];\n if (!first || !winner) continue;\n const inSeed = findRequirement(doc, id) !== null;\n\n // One warning per key, application anomalies taking priority over\n // chain-link mismatches.\n let keyWarned = false;\n const keyWarn = (kind: string, message: string): void => {\n if (!keyWarned) {\n keyWarned = true;\n warnings.push({ requirementId: id, kind, message });\n }\n };\n\n // Chain verification (shared with the fold): unanchored chains defer\n // to the application outcome below.\n const located = findRequirement(doc, id);\n await verifyEventChain(chain, located ? (located.requirements[located.index] ?? null) : null, inSeed, keyWarn);\n const verifyLinks = inSeed || first['state'] === 'new';\n\n // Apply the winner.\n const winnerSeq = winner['sequence'] as number;\n if (winnerSeq > maxSequence) maxSequence = winnerSeq;\n // parseTimestamp + formatTimestamp keep the occurrence host-independent\n // and render asOf as trimmed UTC, matching the Go peer's\n // winner.Timestamp.UTC().Format(RFC3339Nano).\n const occurred = parseTimestamp(winner['timestamp'] as string);\n if (occurred !== null && occurred.getTime() > maxOccurredMs) {\n maxOccurredMs = occurred.getTime();\n asOfFromEvents = formatTimestamp(occurred);\n }\n\n if (winner['state'] === 'absent') {\n const hit = findRequirement(doc, id);\n if (hit) {\n hit.requirements.splice(hit.index, 1);\n eventsApplied++;\n } else {\n keyWarn('absentUnknown', 'absent event for a key not present in the document');\n }\n continue;\n }\n\n if (!verifyLinks) {\n keyWarn('chainGap', 'non-new chain for a key the seed does not carry');\n }\n\n const payload = winner['after'] as Doc | null;\n if (!payload) {\n keyWarn('chainGap', 'winning event carries no applicable after payload');\n continue;\n }\n const hit = findRequirement(doc, id);\n if (hit) {\n hit.requirements[hit.index] = structuredClone(payload);\n eventsApplied++;\n } else {\n insertions.push({ sequence: winnerSeq, id, payload: structuredClone(payload) });\n }\n }\n\n // Deterministic insertion order regardless of delivery order.\n insertions.sort((a, b) => (a.sequence !== b.sequence ? a.sequence - b.sequence : a.id.localeCompare(b.id)));\n if (insertions.length > 0) {\n const baselines = (doc['baselines'] as Doc[] | undefined) ?? [];\n const firstBaseline = baselines[0];\n const firstInsertion = insertions[0];\n if (!firstBaseline || !firstInsertion) {\n throw new Error('seed document has no baselines to insert new requirements into');\n }\n if (baselines.length > 1) {\n warnings.push({\n requirementId: firstInsertion.id,\n kind: 'multiBaseline',\n message: 'seed has multiple baselines; new requirements appended to the first',\n });\n }\n const requirements = (firstBaseline['requirements'] as Doc[] | undefined) ?? [];\n for (const ins of insertions) {\n requirements.push(ins.payload);\n eventsApplied++;\n }\n firstBaseline['requirements'] = requirements;\n }\n\n const asOf = asOfFromEvents !== '' ? asOfFromEvents : docTimestamp;\n if (asOf === '') {\n throw new Error('cannot derive asOf: no events supplied and the seed document has no timestamp');\n }\n\n doc['generator'] = { name: inputs.generator.name, version: inputs.generator.version };\n doc['timestamp'] = asOf;\n doc['derivation'] = {\n seed: {\n uri: inputs.seedUri,\n checksum: { algorithm: 'sha256', value: seedChecksum },\n },\n source: inputs.source,\n throughSequence: maxSequence,\n eventsApplied,\n asOf,\n };\n\n return { results: doc, warnings };\n}\n","import { formatTimestamp, parseTimestamp } from '@mitre/hdf-utilities';\nimport { computeSummary } from './summary.js';\nimport { computeEffectiveStatus } from './status.js';\nimport { computeFieldChanges, extractDrift, DEFAULT_TRACKED_FIELDS } from './diff.js';\nimport { dedupEvents, groupEventChains, verifyEventChain } from './event-stream-common.js';\nimport type { ApplyWarning } from './apply-events.js';\nimport type { RequirementDiff, ChangeReason, RequirementState } from './types.js';\n\ntype Doc = Record<string, unknown>;\ntype FieldChangesInput = Parameters<typeof computeFieldChanges>[0];\n\nexport interface FoldResult {\n comparison: Record<string, unknown>;\n warnings: ApplyWarning[];\n}\n\nfunction findSeedRequirement(doc: Doc, id: string): Doc | null {\n const baselines = (doc['baselines'] as Doc[] | undefined) ?? [];\n for (const baseline of baselines) {\n const requirements = (baseline['requirements'] as Doc[] | undefined) ?? [];\n const hit = requirements.find((r) => r['id'] === id);\n if (hit) return hit;\n }\n return null;\n}\n\n/**\n * Materialize a change-event batch into a full systemDrift hdf-comparison\n * against the seed document (ADR-0005 §5): each winning event lifts into the\n * Requirement_Diff shape the batch engine produces — before from the seed,\n * after from the event payload, field changes derived by the batch engine's\n * own computeFieldChanges — under the same fold contract as\n * applyChangeEvents (dedup, last-value-wins by sequence, tombstone-aware,\n * warnings never abort). Deterministic: the comparison timestamp is the\n * latest event occurrence, and seed-side override expiry anchors to the\n * seed's own timestamp (falling back to the event occurrence when the seed\n * has none) — never wall clock. Go parity: FoldChangeEventsIntoComparison.\n */\nexport async function foldChangeEventsIntoComparison(\n seedJson: string,\n events: Doc[],\n): Promise<FoldResult> {\n const doc = JSON.parse(seedJson) as Doc;\n const docTimestamp = (doc['timestamp'] as string | undefined) ?? '';\n\n const { byKey, keys } = groupEventChains(dedupEvents(events));\n\n const warnings: ApplyWarning[] = [];\n const diffs: RequirementDiff[] = [];\n let maxOccurredMs = Number.NEGATIVE_INFINITY;\n let asOfFromEvents = '';\n let systemRef = '';\n\n for (const id of keys) {\n const chain = byKey.get(id) ?? [];\n const winner = chain[chain.length - 1];\n if (!winner) continue;\n if (systemRef === '') {\n systemRef = (winner['systemRef'] as string | undefined) ?? '';\n }\n\n let keyWarned = false;\n const keyWarn = (kind: string, message: string): void => {\n if (!keyWarned) {\n keyWarned = true;\n warnings.push({ requirementId: id, kind, message });\n }\n };\n\n const seedReq = findSeedRequirement(doc, id);\n const inSeed = seedReq !== null;\n await verifyEventChain(chain, seedReq, inSeed, keyWarn);\n\n // parseTimestamp + formatTimestamp keep the occurrence host-independent\n // and render timestamps as trimmed UTC, matching the Go peer's\n // winner.Timestamp.UTC().Format(RFC3339Nano).\n const occurred = parseTimestamp(winner['timestamp'] as string);\n if (occurred !== null && occurred.getTime() > maxOccurredMs) {\n maxOccurredMs = occurred.getTime();\n asOfFromEvents = formatTimestamp(occurred);\n }\n const newTs = occurred !== null ? formatTimestamp(occurred) : (winner['timestamp'] as string);\n // Seed-side override expiry needs a deterministic anchor: the seed's\n // own observation time, else the event occurrence — a timestamp-less\n // seed must never fall through to the wall clock.\n const seedRef = docTimestamp !== '' ? docTimestamp : newTs;\n\n if (winner['state'] === 'absent') {\n if (!seedReq) {\n keyWarn('absentUnknown', 'absent event for a key not present in the seed');\n continue;\n }\n diffs.push({\n id,\n title: seedReq['title'] as string | undefined,\n state: 'absent',\n oldEffectiveStatus: computeEffectiveStatus(seedReq, seedRef),\n changeReasons: [],\n oldImpact: seedReq['impact'] as number | undefined,\n fieldChanges: [],\n before: seedReq,\n after: null,\n });\n continue;\n }\n\n const after = winner['after'] as Doc | null;\n if (!after) {\n keyWarn('chainGap', 'winning event carries no applicable after payload');\n continue;\n }\n const newStatus = computeEffectiveStatus(after, newTs);\n\n // Content-bearing chain for a key the seed does not carry: the\n // comparison vocabulary allows a null before only on new, so the entry\n // is coerced to the batch engine's new shape; the warning records the\n // anomaly.\n if (!seedReq) {\n if (winner['state'] !== 'new') {\n keyWarn('chainGap', 'non-new chain for a key the seed does not carry; lifted as new');\n }\n diffs.push({\n id,\n title: after['title'] as string | undefined,\n state: 'new',\n newEffectiveStatus: newStatus,\n changeReasons: [],\n newImpact: after['impact'] as number | undefined,\n fieldChanges: [],\n before: null,\n after,\n });\n continue;\n }\n\n diffs.push({\n id,\n title: (after['title'] as string | undefined) ?? (seedReq['title'] as string | undefined),\n state: winner['state'] as RequirementState,\n oldEffectiveStatus: computeEffectiveStatus(seedReq, seedRef),\n newEffectiveStatus: newStatus,\n changeReasons: ((winner['changeReasons'] as string[] | undefined) ?? []) as ChangeReason[],\n oldImpact: seedReq['impact'] as number | undefined,\n newImpact: after['impact'] as number | undefined,\n fieldChanges: computeFieldChanges(\n seedReq as FieldChangesInput,\n after as FieldChangesInput,\n DEFAULT_TRACKED_FIELDS,\n ),\n before: seedReq,\n after,\n });\n }\n\n diffs.sort((a, b) => a.id.localeCompare(b.id));\n\n const asOf = asOfFromEvents !== '' ? asOfFromEvents : docTimestamp;\n if (asOf === '') {\n throw new Error(\n 'cannot derive a comparison timestamp: no events supplied and the seed document has no timestamp',\n );\n }\n\n return {\n comparison: {\n formatVersion: '1.0.0',\n comparisonMode: 'systemDrift',\n timestamp: asOf,\n ...(systemRef !== '' ? { systemRef } : {}),\n sources: [\n { role: 'old', label: 'Old evaluation' },\n { role: 'new', label: 'New evaluation' },\n ],\n matching: { primaryStrategy: 'exactId' },\n summary: computeSummary(diffs),\n baselineDiffs: [],\n requirementDiffs: diffs,\n drift: extractDrift(diffs),\n },\n warnings,\n };\n}\n","import type { ComparisonSummary } from './types.js';\n\n/** GNU diff compatible exit codes (--exit-code mode) */\nexport const EXIT_IDENTICAL = 0;\nexport const EXIT_DIFFERENCES = 1;\nexport const EXIT_ERROR = 2;\n\n/** Detailed exit codes (--detailed-exitcode mode) */\nexport const EXIT_DETAILED_IDENTICAL = 0;\nexport const EXIT_DETAILED_ERROR = 1;\nexport const EXIT_DETAILED_FIXES_ONLY = 10;\nexport const EXIT_DETAILED_REGRESSIONS_ONLY = 11;\nexport const EXIT_DETAILED_MIXED = 12;\nexport const EXIT_DETAILED_BASELINE_CHANGED = 13;\nexport const EXIT_DETAILED_DRIFT_ONLY = 14;\n\n/**\n * Compute the GNU diff compatible exit code from a comparison summary.\n *\n * Returns:\n * 0 = identical (no differences found)\n * 1 = differences found (any kind)\n *\n * Note: error (exit code 2) is not computed from the summary — callers\n * should return EXIT_ERROR directly when I/O or parse errors occur.\n */\nexport function computeExitCode(summary: ComparisonSummary): number {\n if (hasDifferences(summary)) {\n return EXIT_DIFFERENCES;\n }\n return EXIT_IDENTICAL;\n}\n\n/**\n * Compute the detailed exit code from a comparison summary.\n *\n * Returns:\n * 0 = identical (no differences found)\n * 10 = differences found, fixes only (security posture improved)\n * 11 = differences found, regressions only (security posture degraded)\n * 12 = differences found, mixed fixes and regressions\n * 13 = differences found, only new/absent controls (baseline changed)\n * 14 = differences found, only metadata drift (no status changes)\n *\n * Note: error (exit code 1) is not computed from the summary — callers\n * should return EXIT_DETAILED_ERROR directly when I/O or parse errors occur.\n *\n * Priority order: mixed(12) > regressions(11) > fixes(10) > baseline(13) > drift(14)\n */\nexport function computeDetailedExitCode(summary: ComparisonSummary): number {\n if (!hasDifferences(summary)) {\n return EXIT_DETAILED_IDENTICAL;\n }\n\n // Mixed: both fixes and regressions\n if (summary.regressed > 0 && summary.fixed > 0) {\n return EXIT_DETAILED_MIXED;\n }\n\n // Regressions only (no fixes)\n if (summary.regressed > 0) {\n return EXIT_DETAILED_REGRESSIONS_ONLY;\n }\n\n // Fixes only (no regressions)\n if (summary.fixed > 0) {\n return EXIT_DETAILED_FIXES_ONLY;\n }\n\n // Baseline changes: new or absent controls (but no status changes)\n if (summary.new > 0 || summary.absent > 0) {\n return EXIT_DETAILED_BASELINE_CHANGED;\n }\n\n // Everything else is metadata drift (updated tags, descriptions, etc.)\n return EXIT_DETAILED_DRIFT_ONLY;\n}\n\n/**\n * Returns true if the summary indicates any differences at all.\n */\nfunction hasDifferences(summary: ComparisonSummary): boolean {\n return summary.total !== summary.unchanged;\n}\n","import type { RequirementDiff } from '../types.js';\nimport type { RenderOptions } from './types.js';\n\n/**\n * Filter requirement diffs based on render options.\n *\n * Supports filtering by:\n * - `filterStates`: Only include requirements matching the given states\n * - `filterSeverity`: Only include requirements matching the given severity tag\n */\nexport function filterRequirements(\n diffs: RequirementDiff[],\n options?: RenderOptions,\n): RequirementDiff[] {\n let filtered = diffs;\n\n if (options?.filterStates && options.filterStates.length > 0) {\n const states = new Set(options.filterStates);\n filtered = filtered.filter((r) => states.has(r.state));\n }\n\n if (options?.filterSeverity) {\n const severity = options.filterSeverity.toLowerCase();\n filtered = filtered.filter((r) => {\n const before = r.before as Record<string, unknown> | null;\n const after = r.after as Record<string, unknown> | null;\n const tags =\n (after?.['tags'] as Record<string, unknown> | undefined) ??\n (before?.['tags'] as Record<string, unknown> | undefined);\n if (!tags) return false;\n return (\n typeof tags['severity'] === 'string' &&\n tags['severity'].toLowerCase() === severity\n );\n });\n }\n\n return filtered;\n}\n","import type { HDFComparison, RequirementDiff } from '../types.js';\nimport type { RenderOptions } from './types.js';\nimport { filterRequirements } from './filter.js';\n\n/**\n * Strip `before` and `after` from a RequirementDiff, keeping only\n * the summary fields (id, state, title, statuses, changeReasons, fieldChanges).\n */\nfunction stripSnapshots(\n req: RequirementDiff,\n): Omit<RequirementDiff, 'before' | 'after'> {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { before, after, ...rest } = req;\n return rest;\n}\n\n/**\n * Render an HDFComparison as a JSON string.\n *\n * - `detail: 'summary'` -- only `{ formatVersion, comparisonMode, summary }`\n * - `detail: 'control'` -- full document but `before`/`after` stripped from requirementDiffs\n * - `detail: 'full'` -- `JSON.stringify(comparison, null, 2)` (the complete document)\n *\n * Default detail level: `'control'`.\n */\nexport function renderJson(\n comparison: HDFComparison,\n options?: RenderOptions,\n): string {\n const detail = options?.detail ?? 'control';\n\n if (detail === 'summary') {\n return JSON.stringify(\n {\n formatVersion: comparison.formatVersion,\n comparisonMode: comparison.comparisonMode,\n summary: comparison.summary,\n },\n null,\n 2,\n );\n }\n\n if (detail === 'full') {\n const filtered = filterRequirements(\n comparison.requirementDiffs,\n options,\n );\n if (filtered.length !== comparison.requirementDiffs.length) {\n return JSON.stringify(\n { ...comparison, requirementDiffs: filtered },\n null,\n 2,\n );\n }\n return JSON.stringify(comparison, null, 2);\n }\n\n // detail === 'control' (default)\n const filtered = filterRequirements(\n comparison.requirementDiffs,\n options,\n );\n const strippedDiffs = filtered.map(stripSnapshots);\n\n return JSON.stringify(\n { ...comparison, requirementDiffs: strippedDiffs },\n null,\n 2,\n );\n}\n","import type { HDFComparison, RequirementDiff } from '../types.js';\nimport type { RenderOptions } from './types.js';\nimport { filterRequirements } from './filter.js';\n\n/**\n * Render the summary table in markdown format.\n */\nfunction renderSummaryTable(comparison: HDFComparison): string {\n const { summary } = comparison;\n const lines: string[] = [\n '## HDF Comparison Summary',\n '',\n '| Metric | Count |',\n '|--------|-------|',\n `| Fixed | ${summary.fixed} |`,\n `| Regressed | ${summary.regressed} |`,\n `| New | ${summary.new} |`,\n `| Absent | ${summary.absent} |`,\n `| Unchanged | ${summary.unchanged} |`,\n `| Updated | ${summary.updated} |`,\n `| **Total** | **${summary.total}** |`,\n ];\n return lines.join('\\n');\n}\n\n/**\n * Group requirement diffs by state.\n */\nfunction groupByState(\n diffs: RequirementDiff[],\n): Map<string, RequirementDiff[]> {\n const groups = new Map<string, RequirementDiff[]>();\n for (const diff of diffs) {\n const existing = groups.get(diff.state);\n if (existing) {\n existing.push(diff);\n } else {\n groups.set(diff.state, [diff]);\n }\n }\n return groups;\n}\n\n/**\n * Escape a value for use in a markdown table cell.\n * Replaces pipe characters with their HTML entity.\n */\nfunction escapeCell(value: string): string {\n return value.replace(/\\|/g, '&#124;');\n}\n\n/**\n * Format field changes for a markdown cell.\n */\nfunction formatFieldChanges(req: RequirementDiff): string {\n if (req.fieldChanges.length === 0) return '';\n return req.fieldChanges\n .map((fc) => {\n if (fc.op === 'add') return `+${fc.path}: ${JSON.stringify(fc.newValue)}`;\n if (fc.op === 'remove')\n return `-${fc.path}: ${JSON.stringify(fc.oldValue)}`;\n return `${fc.path}: ${JSON.stringify(fc.oldValue)} -> ${JSON.stringify(fc.newValue)}`;\n })\n .join('; ');\n}\n\n/**\n * Render a section for a single state group.\n */\nfunction renderStateSection(\n state: string,\n diffs: RequirementDiff[],\n detail: string,\n): string {\n const label = state.charAt(0).toUpperCase() + state.slice(1);\n const lines: string[] = [`### ${label} (${diffs.length})`];\n\n if (diffs.length === 0) {\n lines.push('', '(none)');\n return lines.join('\\n');\n }\n\n lines.push('');\n\n if (detail === 'full') {\n lines.push(\n '| ID | Title | Old Status | New Status | Change Reasons | Field Changes |',\n '|----|-------|------------|------------|----------------|---------------|',\n );\n for (const req of diffs) {\n const id = escapeCell(req.id);\n const title = escapeCell(req.title ?? '');\n const oldStatus = escapeCell(req.oldEffectiveStatus ?? '');\n const newStatus = escapeCell(req.newEffectiveStatus ?? '');\n const reasons = escapeCell(req.changeReasons.join(', '));\n const fieldChanges = escapeCell(formatFieldChanges(req));\n lines.push(\n `| ${id} | ${title} | ${oldStatus} | ${newStatus} | ${reasons} | ${fieldChanges} |`,\n );\n }\n } else {\n lines.push(\n '| ID | Title | Old Status | New Status |',\n '|----|-------|------------|------------|',\n );\n for (const req of diffs) {\n const id = escapeCell(req.id);\n const title = escapeCell(req.title ?? '');\n const oldStatus = escapeCell(req.oldEffectiveStatus ?? '');\n const newStatus = escapeCell(req.newEffectiveStatus ?? '');\n lines.push(`| ${id} | ${title} | ${oldStatus} | ${newStatus} |`);\n }\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Render an HDFComparison as a Markdown string.\n *\n * - `detail: 'summary'` -- summary table only\n * - `detail: 'control'` -- summary + per-requirement tables by state\n * - `detail: 'full'` -- summary + per-requirement tables with changeReasons and fieldChanges\n *\n * Default detail level: `'control'`.\n */\nexport function renderMarkdown(\n comparison: HDFComparison,\n options?: RenderOptions,\n): string {\n const detail = options?.detail ?? 'control';\n const parts: string[] = [renderSummaryTable(comparison)];\n\n if (detail === 'summary') {\n return parts.join('\\n');\n }\n\n // Determine which states to display\n const stateOrder: string[] = [\n 'fixed',\n 'regressed',\n 'new',\n 'absent',\n 'updated',\n 'unchanged',\n ];\n\n const filtered = filterRequirements(\n comparison.requirementDiffs,\n options,\n );\n const grouped = groupByState(filtered);\n\n // If filtering by states, only show those specific states\n const statesToShow =\n options?.filterStates && options.filterStates.length > 0\n ? stateOrder.filter((s) => options.filterStates!.includes(s))\n : stateOrder;\n\n for (const state of statesToShow) {\n parts.push('');\n const diffs = grouped.get(state) ?? [];\n parts.push(renderStateSection(state, diffs, detail));\n }\n\n return parts.join('\\n');\n}\n","import type { HDFComparison, RequirementDiff } from '../types.js';\nimport type { RenderOptions } from './types.js';\nimport { filterRequirements } from './filter.js';\n\n// ANSI color codes\nconst RESET = '\\x1b[0m';\nconst GREEN = '\\x1b[32m';\nconst RED = '\\x1b[31m';\nconst YELLOW = '\\x1b[33m';\nconst BOLD = '\\x1b[1m';\nconst DIM = '\\x1b[2m';\n\n/**\n * Get the symbol and color for a requirement state.\n */\nfunction getSymbolAndColor(\n state: string,\n useColor: boolean,\n): { symbol: string; colorFn: (s: string) => string } {\n const identity = (s: string): string => s;\n\n switch (state) {\n case 'fixed':\n case 'new':\n return {\n symbol: '+',\n colorFn: useColor ? (s) => `${GREEN}${s}${RESET}` : identity,\n };\n case 'regressed':\n case 'absent':\n return {\n symbol: '-',\n colorFn: useColor ? (s) => `${RED}${s}${RESET}` : identity,\n };\n case 'updated':\n return {\n symbol: '~',\n colorFn: useColor ? (s) => `${YELLOW}${s}${RESET}` : identity,\n };\n case 'unchanged':\n default:\n return {\n symbol: ' ',\n colorFn: useColor ? (s) => `${DIM}${s}${RESET}` : identity,\n };\n }\n}\n\n/**\n * Format the status transition for a requirement.\n */\nfunction formatStatusTransition(req: RequirementDiff): string {\n if (req.state === 'new') {\n return '(new)';\n }\n if (req.state === 'absent') {\n return '(absent)';\n }\n\n const parts: string[] = [];\n\n // Show status change if both exist\n if (req.oldEffectiveStatus && req.newEffectiveStatus) {\n parts.push(`${req.oldEffectiveStatus} → ${req.newEffectiveStatus}`);\n }\n\n // Add state label for non-obvious transitions\n if (req.state !== 'unchanged') {\n parts.push(`(${req.state})`);\n }\n\n return parts.join(' ');\n}\n\n/**\n * Format field changes for full detail.\n */\nfunction formatFieldChangesForTerminal(req: RequirementDiff): string {\n if (req.fieldChanges.length === 0) return '';\n\n const parts = req.fieldChanges.map((fc) => {\n if (fc.op === 'add') return `+${fc.path}: ${JSON.stringify(fc.newValue)}`;\n if (fc.op === 'remove') return `-${fc.path}: ${JSON.stringify(fc.oldValue)}`;\n return `${fc.path}: ${JSON.stringify(fc.oldValue)} → ${JSON.stringify(fc.newValue)}`;\n });\n\n return parts.join('; ');\n}\n\n/**\n * Render a single requirement line.\n */\nfunction renderRequirementLine(\n req: RequirementDiff,\n detail: string,\n useColor: boolean,\n): string {\n const { symbol, colorFn } = getSymbolAndColor(req.state, useColor);\n const title = req.title ?? '';\n const transition = formatStatusTransition(req);\n\n let line = ` ${symbol} ${req.id} ${title} ${transition}`;\n\n if (detail === 'full') {\n // Add change reasons\n if (req.changeReasons.length > 0) {\n line += ` [${req.changeReasons.join(', ')}]`;\n }\n // Add field changes\n const fieldChanges = formatFieldChangesForTerminal(req);\n if (fieldChanges) {\n line += ` ${fieldChanges}`;\n }\n }\n\n return colorFn(line);\n}\n\n/**\n * Build the summary line.\n */\nfunction buildSummaryLine(comparison: HDFComparison, useColor: boolean): string {\n const { summary } = comparison;\n\n const parts = [\n `${summary.fixed} fixed`,\n `${summary.regressed} regressed`,\n `${summary.new} new`,\n `${summary.absent} absent`,\n `${summary.unchanged} unchanged`,\n `${summary.updated} updated`,\n `(${summary.total} total)`,\n ];\n\n const line = `Summary: ${parts.join(', ')}`;\n\n if (useColor) {\n return `${BOLD}${line}${RESET}`;\n }\n return line;\n}\n\n/**\n * Build the header line.\n */\nfunction buildHeaderLine(comparison: HDFComparison, useColor: boolean): string {\n const mode = comparison.comparisonMode;\n const oldSource = comparison.sources.find((s) => s.role === 'old' || s.role === 'golden' || s.role === 'reference');\n const newSource = comparison.sources.find((s) => s.role === 'new' || s.role === 'system');\n\n let header = `HDF Comparison: ${mode}`;\n\n const oldTimestamp = oldSource?.assessmentTimestamp;\n const newTimestamp = newSource?.assessmentTimestamp;\n\n if (oldTimestamp && newTimestamp) {\n // Format as date-only if possible, otherwise use full timestamp\n // split() always returns at least one element, so [0] is safe\n const oldDate = oldTimestamp.split('T')[0]!;\n const newDate = newTimestamp.split('T')[0]!;\n header += ` (${oldDate} → ${newDate})`;\n }\n\n if (useColor) {\n return `${BOLD}${header}${RESET}`;\n }\n return header;\n}\n\n/**\n * Render an HDFComparison for terminal display with optional ANSI colors.\n *\n * - `detail: 'summary'` -- just the summary line\n * - `detail: 'control'` -- requirement list + summary (excludes unchanged)\n * - `detail: 'full'` -- all requirements including unchanged, with changeReasons and fieldChanges\n *\n * When `color: false`, no ANSI escape codes are emitted.\n * Default detail level: `'control'`. Default color: `true`.\n */\nexport function renderTerminal(\n comparison: HDFComparison,\n options?: RenderOptions,\n): string {\n const detail = options?.detail ?? 'control';\n const useColor = options?.color ?? true;\n\n const lines: string[] = [];\n\n // Header\n lines.push(buildHeaderLine(comparison, useColor));\n lines.push('');\n\n if (detail === 'summary') {\n lines.push(buildSummaryLine(comparison, useColor));\n return lines.join('\\n');\n }\n\n // Requirement lines\n const filtered = filterRequirements(comparison.requirementDiffs, options);\n\n for (const req of filtered) {\n // In 'control' mode, skip unchanged requirements\n if (detail === 'control' && req.state === 'unchanged') {\n continue;\n }\n lines.push(renderRequirementLine(req, detail, useColor));\n }\n\n lines.push('');\n lines.push(buildSummaryLine(comparison, useColor));\n\n return lines.join('\\n');\n}\n","import type { HDFComparison, RequirementDiff } from '../types.js';\nimport type { RenderOptions } from './types.js';\nimport { filterRequirements } from './filter.js';\n\n/**\n * Escape a value for CSV output.\n *\n * Per RFC 4180:\n * - Fields containing commas, double quotes, or newlines are enclosed in double quotes.\n * - Double quotes within a field are escaped by doubling them.\n */\nfunction escapeCsvField(value: string): string {\n if (value.includes(',') || value.includes('\"') || value.includes('\\n') || value.includes('\\r')) {\n return `\"${value.replace(/\"/g, '\"\"')}\"`;\n }\n return value;\n}\n\n/**\n * Format field changes as a human-readable string.\n */\nfunction formatFieldChanges(req: RequirementDiff): string {\n if (req.fieldChanges.length === 0) return '';\n return req.fieldChanges\n .map((fc) => {\n if (fc.op === 'add') return `+${fc.path}: ${JSON.stringify(fc.newValue)}`;\n if (fc.op === 'remove') return `-${fc.path}: ${JSON.stringify(fc.oldValue)}`;\n return `${fc.path}: ${JSON.stringify(fc.oldValue)} -> ${JSON.stringify(fc.newValue)}`;\n })\n .join('; ');\n}\n\n/**\n * Render an HDFComparison as a CSV string.\n *\n * One row per requirement. Columns:\n * - ID, Title, State, Old Status, New Status, Impact (Old), Impact (New), Change Reasons\n *\n * When `detail: 'full'`, an additional Field Changes column is included.\n *\n * Header row is always included. Standard CSV escaping (RFC 4180).\n * Default detail level: `'control'`.\n */\nexport function renderCsv(\n comparison: HDFComparison,\n options?: RenderOptions,\n): string {\n const detail = options?.detail ?? 'control';\n const filtered = filterRequirements(comparison.requirementDiffs, options);\n\n const headers = [\n 'ID',\n 'Title',\n 'State',\n 'Old Status',\n 'New Status',\n 'Impact (Old)',\n 'Impact (New)',\n 'Change Reasons',\n ];\n\n if (detail === 'full') {\n headers.push('Field Changes');\n }\n\n const lines: string[] = [headers.join(',')];\n\n for (const req of filtered) {\n const row = [\n escapeCsvField(req.id),\n escapeCsvField(req.title ?? ''),\n escapeCsvField(req.state),\n escapeCsvField(req.oldEffectiveStatus ?? ''),\n escapeCsvField(req.newEffectiveStatus ?? ''),\n escapeCsvField(req.oldImpact !== undefined ? String(req.oldImpact) : ''),\n escapeCsvField(req.newImpact !== undefined ? String(req.newImpact) : ''),\n escapeCsvField(req.changeReasons.join(', ')),\n ];\n\n if (detail === 'full') {\n row.push(escapeCsvField(formatFieldChanges(req)));\n }\n\n lines.push(row.join(','));\n }\n\n return lines.join('\\n');\n}\n","export { renderJson } from './json.js';\nexport { renderMarkdown } from './markdown.js';\nexport { renderTerminal } from './terminal.js';\nexport { renderCsv } from './csv.js';\nexport type { DetailLevel, RenderOptions } from './types.js';\n\nimport type { HDFComparison } from '../types.js';\nimport type { RenderOptions } from './types.js';\nimport { renderJson } from './json.js';\nimport { renderMarkdown } from './markdown.js';\nimport { renderTerminal } from './terminal.js';\nimport { renderCsv } from './csv.js';\n\n/**\n * Convenience function to render a comparison in any supported format.\n *\n * @param comparison - The HDFComparison document to render\n * @param format - Output format: 'json', 'markdown', 'terminal', or 'csv'\n * @param options - Rendering options (detail level, filters, color)\n * @returns The rendered string\n */\nexport function render(\n comparison: HDFComparison,\n format: 'json' | 'markdown' | 'terminal' | 'csv',\n options?: RenderOptions,\n): string {\n switch (format) {\n case 'json':\n return renderJson(comparison, options);\n case 'markdown':\n return renderMarkdown(comparison, options);\n case 'terminal':\n return renderTerminal(comparison, options);\n case 'csv':\n return renderCsv(comparison, options);\n }\n}\n","/**\n * SBOM comparison for the HDF diff engine.\n *\n * Compares two SBOM documents (CycloneDX or SPDX JSON) and produces\n * package-level diffs: added, removed, updated, unchanged packages.\n *\n * Format auto-detection:\n * - CycloneDX: has `bomFormat: \"CycloneDX\"`, packages in `components[]`\n * - SPDX: has `spdxVersion`, packages in `packages[]`\n */\n\n/**\n * The comparison result for a single package between two SBOMs.\n */\nexport interface PackageDiff {\n purl: string;\n name: string;\n state: 'added' | 'removed' | 'updated' | 'unchanged';\n oldVersion?: string;\n newVersion?: string;\n licenses?: string[];\n}\n\n/**\n * The complete result of comparing two SBOM documents.\n */\nexport interface SbomDiffResult {\n packageDiffs: PackageDiff[];\n added: number;\n removed: number;\n updated: number;\n unchanged: number;\n}\n\n/**\n * Internal representation of a parsed package from any SBOM format.\n */\ninterface ParsedPackage {\n purl: string;\n name: string;\n version: string;\n licenses: string[];\n}\n\n/**\n * Compare two SBOM documents (CycloneDX or SPDX JSON strings) and return\n * package-level diffs.\n *\n * @param oldJson - JSON string of the old SBOM document\n * @param newJson - JSON string of the new SBOM document\n * @returns Structured diff result with per-package state and aggregate counts\n * @throws Error if either input is not valid JSON or not a recognized SBOM format\n */\nexport function diffSboms(oldJson: string, newJson: string): SbomDiffResult {\n const oldParsed = JSON.parse(oldJson) as Record<string, unknown>;\n const newParsed = JSON.parse(newJson) as Record<string, unknown>;\n\n const oldPackages = extractPackages(oldParsed);\n const newPackages = extractPackages(newParsed);\n\n const oldMap = buildPackageMap(oldPackages);\n const newMap = buildPackageMap(newPackages);\n\n const diffs: PackageDiff[] = [];\n const seen = new Set<string>();\n\n // Check old packages against new\n for (const [key, oldPkg] of oldMap) {\n seen.add(key);\n const newPkg = newMap.get(key);\n if (newPkg) {\n if (oldPkg.version !== newPkg.version) {\n diffs.push({\n purl: newPkg.purl || newPkg.name,\n name: newPkg.name,\n state: 'updated',\n oldVersion: oldPkg.version,\n newVersion: newPkg.version,\n licenses: newPkg.licenses.length > 0 ? newPkg.licenses : undefined,\n });\n } else {\n diffs.push({\n purl: oldPkg.purl || oldPkg.name,\n name: oldPkg.name,\n state: 'unchanged',\n });\n }\n } else {\n diffs.push({\n purl: oldPkg.purl || oldPkg.name,\n name: oldPkg.name,\n state: 'removed',\n oldVersion: oldPkg.version,\n });\n }\n }\n\n // Check for added packages\n for (const [key, newPkg] of newMap) {\n if (!seen.has(key)) {\n diffs.push({\n purl: newPkg.purl || newPkg.name,\n name: newPkg.name,\n state: 'added',\n newVersion: newPkg.version,\n licenses: newPkg.licenses.length > 0 ? newPkg.licenses : undefined,\n });\n }\n }\n\n // Sort by name for deterministic output\n diffs.sort((a, b) => a.name.localeCompare(b.name));\n\n // Count states\n let added = 0;\n let removed = 0;\n let updated = 0;\n let unchanged = 0;\n for (const d of diffs) {\n switch (d.state) {\n case 'added': added++; break;\n case 'removed': removed++; break;\n case 'updated': updated++; break;\n case 'unchanged': unchanged++; break;\n }\n }\n\n return { packageDiffs: diffs, added, removed, updated, unchanged };\n}\n\n/**\n * Extract packages from an SBOM document, auto-detecting the format.\n */\nfunction extractPackages(doc: Record<string, unknown>): ParsedPackage[] {\n if (doc['bomFormat'] === 'CycloneDX') {\n return extractCycloneDXPackages(doc);\n }\n if (typeof doc['spdxVersion'] === 'string') {\n return extractSPDXPackages(doc);\n }\n throw new Error(\n 'Unrecognized SBOM format: expected CycloneDX (bomFormat) or SPDX (spdxVersion)',\n );\n}\n\n/**\n * Extract packages from a CycloneDX document.\n * Reads components[] with purl, name, version fields.\n */\nfunction extractCycloneDXPackages(doc: Record<string, unknown>): ParsedPackage[] {\n const components = doc['components'] as Array<Record<string, unknown>> | undefined;\n if (!Array.isArray(components)) {\n return [];\n }\n\n return components.map((comp): ParsedPackage => {\n const licenses = extractCycloneDXLicenses(comp);\n return {\n purl: (comp['purl'] as string) ?? '',\n name: (comp['name'] as string) ?? '',\n version: (comp['version'] as string) ?? '',\n licenses,\n };\n });\n}\n\n/**\n * Extract license strings from a CycloneDX component.\n * CycloneDX licenses can be in `licenses[].license.id` or `licenses[].license.name`.\n */\nfunction extractCycloneDXLicenses(comp: Record<string, unknown>): string[] {\n const licensesArr = comp['licenses'] as Array<Record<string, unknown>> | undefined;\n if (!Array.isArray(licensesArr)) {\n return [];\n }\n const result: string[] = [];\n for (const entry of licensesArr) {\n const license = entry['license'] as Record<string, unknown> | undefined;\n if (license) {\n const id = license['id'] as string | undefined;\n const name = license['name'] as string | undefined;\n if (id) {\n result.push(id);\n } else if (name) {\n result.push(name);\n }\n }\n }\n return result;\n}\n\n/**\n * Extract packages from an SPDX document.\n * Reads packages[] with name, versionInfo, and externalRefs (for PURL).\n */\nfunction extractSPDXPackages(doc: Record<string, unknown>): ParsedPackage[] {\n const packages = doc['packages'] as Array<Record<string, unknown>> | undefined;\n if (!Array.isArray(packages)) {\n return [];\n }\n\n return packages.map((pkg): ParsedPackage => {\n const purl = extractSPDXPurl(pkg);\n const license = (pkg['licenseConcluded'] as string) ?? (pkg['licenseDeclared'] as string) ?? '';\n return {\n purl,\n name: (pkg['name'] as string) ?? '',\n version: (pkg['versionInfo'] as string) ?? '',\n licenses: license && license !== 'NOASSERTION' ? [license] : [],\n };\n });\n}\n\n/**\n * Extract a PURL from an SPDX package's externalRefs array.\n */\nfunction extractSPDXPurl(pkg: Record<string, unknown>): string {\n const refs = pkg['externalRefs'] as Array<Record<string, unknown>> | undefined;\n if (!Array.isArray(refs)) {\n return '';\n }\n for (const ref of refs) {\n const refType = ref['referenceType'] as string | undefined;\n if (refType === 'purl') {\n return (ref['referenceLocator'] as string) ?? '';\n }\n }\n return '';\n}\n\n/**\n * Build a lookup map of packages indexed by name (version-independent key).\n */\nfunction buildPackageMap(packages: ParsedPackage[]): Map<string, ParsedPackage> {\n const map = new Map<string, ParsedPackage>();\n for (const pkg of packages) {\n const key = pkg.name || pkg.purl;\n if (key) {\n map.set(key, pkg);\n }\n }\n return map;\n}\n"],"mappings":";;;;AAIA,MAAM,mCAAmB,IAAI,IAAI,CAAC,QAAQ,CAAC;;AAG3C,MAAM,mCAAmB,IAAI,IAAI;CAAC;CAAU;CAAS;AAAa,CAAC;;;;;;;;;;;;;AAwBnE,SAAgB,uBACd,aACA,oBACQ;CACR,MAAM,UAAW,YAAY,cAA2C,CAAC;CACzE,MAAM,YAAa,YAAY,sBAAqD,CAAC;CACrF,OAAOA,yBACL;EAEE,QAAS,YAAY,aAAoC;EACzD,gBAAgB,QAAQ,KAAK,MAAM,EAAE,MAAM;EAC3C,WAAW,UAAU,KAAK,OAAO;GAC/B,QAAQ,EAAE;GACV,WAAW,EAAE;GACb,WAAW,EAAE;EACf,EAAE;CACJ,GACA,kBACF;AACF;;;;;AAMA,SAAgB,sBACd,QACA,QACA,cACA,cACgB;CAChB,MAAM,UAA0B,CAAC;CAGjC,MAAM,aAAc,OAAO,cAA2C,CAAC;CACvE,MAAM,aAAc,OAAO,cAA2C,CAAC;CACvE,MAAM,oBAAoB,WAAW,KAAK,MAAM,EAAE,MAAM,CAAC,CAAC,KAAK;CAC/D,MAAM,oBAAoB,WAAW,KAAK,MAAM,EAAE,MAAM,CAAC,CAAC,KAAK;CAC/D,IAAI,KAAK,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