@mitre/hdf-engine 3.8.0-next.42656981889.1 → 3.8.0-next.42665732325.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.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +6 -6
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { StatusOverrideInput } from "@mitre/hdf-utilities";
|
|
2
2
|
import { EvaluatedRequirement, HDFBaseline, HDFResults, RequirementResult, Severity } from "@mitre/hdf-schema";
|
|
3
|
-
export declare const engineVersion = "3.8.0-next.
|
|
3
|
+
export declare const engineVersion = "3.8.0-next.42665732325.1";
|
|
4
4
|
/** One input to merge: a results document and the name it is recorded under. */
|
|
5
5
|
interface MergeSource {
|
|
6
6
|
name: string;
|
package/dist/index.js
CHANGED
|
@@ -3,7 +3,7 @@ import { parseBaseline, parseResults } from "@mitre/hdf-parsers";
|
|
|
3
3
|
import { blake3 } from "@noble/hashes/blake3.js";
|
|
4
4
|
import { bytesToHex } from "@noble/hashes/utils.js";
|
|
5
5
|
// src/version.ts
|
|
6
|
-
const engineVersion = "3.8.0-next.
|
|
6
|
+
const engineVersion = "3.8.0-next.42665732325.1";
|
|
7
7
|
// src/merge.ts
|
|
8
8
|
/** Provenance label keys written on every merged baseline (ADR-0016 §3). */
|
|
9
9
|
const LABEL_TOOL = "tool";
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["describe"],"sources":["../src/version.ts","../src/merge.ts","../src/detect.ts","../src/effective.ts","../src/compliance.ts","../src/vocabulary.ts","../src/safematch.ts","../src/values.ts","../src/query.ts","../src/rules.ts","../src/loader.ts","../src/evidence.ts"],"sourcesContent":["// Library version, kept on the workspace lockstep with package.json (the Go\n// peer is hdf-engine/go/engine.go Version(); index.test.ts pins both to\n// package.json). It lives in its own module so engines that stamp it into\n// documents (merge.ts) can import it without a cycle through index.ts.\nexport const engineVersion = '3.8.0-next.42656981889.1';\n","// Merge engine — the TypeScript peer of hdf-engine/go/merge.go (ADR-0016).\n// Combines several results documents into one multi-baseline results document:\n// one baseline per input baseline renamed `<tool>/<original>`, per-baseline\n// provenance in labels, each input's root provenance verbatim under\n// extensions.passthrough[\"hdf-merge\"]. Union semantics — nothing deduplicated, re-keyed or\n// dropped. Deterministic for the same inputs in the same order. Kept at\n// behavioural parity with Go (see test/merge.test.ts / go/merge_test.go).\n\nimport type { HDFResults, EvaluatedBaseline, Component } from '@mitre/hdf-schema';\nimport { engineVersion } from './version.js';\n\n/** One input to merge: a results document and the name it is recorded under. */\nexport interface MergeSource {\n name: string;\n doc: HDFResults;\n}\n\nexport type MergeWarningKind = 'duplicate-baseline-name' | 'label-overwritten';\n\n/** A non-fatal condition merge reports rather than silently resolving. */\nexport interface MergeWarning {\n kind: MergeWarningKind;\n /** Merged baseline name. */\n name: string;\n /** Merged baseline positions. */\n indices: number[];\n /** Set for label warnings only: the label key that was replaced or removed. */\n label?: string;\n}\n\nexport interface MergeResult {\n results: HDFResults;\n warnings: MergeWarning[];\n}\n\n/** Provenance label keys written on every merged baseline (ADR-0016 §3). */\nexport const LABEL_TOOL = 'tool';\nexport const LABEL_TOOL_VERSION = 'toolVersion';\nexport const LABEL_SOURCE_DOCUMENT = 'sourceDocument';\n\nconst MERGE_GENERATOR_NAME = 'hdf-merge';\nconst MERGE_EXTENSION_KEY = 'hdf-merge';\n\n/**\n * merge combines the sources, in order, into one results document. Returns the\n * document and any warnings (a collision or overwrite is never an error);\n * throws only when there is nothing to merge. Inputs are not mutated.\n */\nexport function merge(sources: MergeSource[]): MergeResult {\n if (sources.length === 0) {\n throw new Error('merge: no sources');\n }\n\n const baselines: EvaluatedBaseline[] = [];\n const components: Component[] = [];\n const warnings: MergeWarning[] = [];\n const seenComponent = new Set<string>();\n const provenance: Record<string, unknown>[] = [];\n const positionsByName = new Map<string, number[]>();\n let latest: HDFResults['timestamp'];\n\n sources.forEach((src, index) => {\n const prefix = toolPrefix(src.doc, index);\n const version = toolVersion(src.doc);\n\n for (const b of src.doc.baselines ?? []) {\n const name = `${prefix}/${b.name}`;\n const pos = baselines.length;\n const labels: Record<string, string> = { ...(b.labels ?? {}) };\n\n setLabel(warnings, labels, LABEL_TOOL, prefix, name, pos);\n if (version !== '') {\n setLabel(warnings, labels, LABEL_TOOL_VERSION, version, name, pos);\n } else if (LABEL_TOOL_VERSION in labels) {\n delete labels[LABEL_TOOL_VERSION];\n warnings.push({ kind: 'label-overwritten', name, indices: [pos], label: LABEL_TOOL_VERSION });\n }\n setLabel(warnings, labels, LABEL_SOURCE_DOCUMENT, src.name, name, pos);\n\n const positions = positionsByName.get(name);\n if (positions) positions.push(pos);\n else positionsByName.set(name, [pos]);\n\n baselines.push({ ...b, name, labels });\n }\n\n for (const c of src.doc.components ?? []) {\n if (c.componentId !== undefined) {\n if (seenComponent.has(c.componentId)) continue;\n seenComponent.add(c.componentId);\n }\n components.push(c);\n }\n\n if (src.doc.timestamp !== undefined && (latest === undefined || millis(src.doc.timestamp) > millis(latest))) {\n latest = src.doc.timestamp;\n }\n\n provenance.push(sourceProvenance(index, src));\n });\n\n for (const [name, positions] of positionsByName) {\n if (positions.length > 1) {\n warnings.push({ kind: 'duplicate-baseline-name', name, indices: positions });\n }\n }\n\n // Key order is fixed so the same inputs serialize identically on every run.\n const results: HDFResults = {\n baselines,\n ...(components.length > 0 ? { components } : {}),\n extensions: {\n passthrough: { [MERGE_EXTENSION_KEY]: { version: engineVersion, sources: provenance } },\n },\n generator: { name: MERGE_GENERATOR_NAME, version: engineVersion },\n ...(latest !== undefined ? { timestamp: latest } : {}),\n };\n return { results, warnings };\n}\n\nfunction setLabel(\n warnings: MergeWarning[],\n labels: Record<string, string>,\n key: string,\n value: string,\n name: string,\n pos: number,\n): void {\n if (key in labels) {\n warnings.push({ kind: 'label-overwritten', name, indices: [pos], label: key });\n }\n labels[key] = value;\n}\n\n/** `<tool>` of a merged baseline name: tool.name → generator.name → doc<N>, lower-cased and trimmed. */\nfunction toolPrefix(doc: HDFResults, index: number): string {\n const tool = normalizeName(doc.tool?.name);\n if (tool !== '') return tool;\n const generator = normalizeName(doc.generator?.name);\n if (generator !== '') return generator;\n return `doc${index}`;\n}\n\nfunction normalizeName(s: string | undefined): string {\n return (s ?? '').trim().toLowerCase();\n}\n\n/**\n * millis reads a document timestamp for comparison. The schema type is Date,\n * but a document parsed from JSON carries the RFC 3339 string verbatim (the\n * loader does not revive dates), so both are accepted; the value itself is\n * carried through unchanged so output stays byte-faithful to the input.\n */\nfunction millis(ts: Date | string): number {\n return ts instanceof Date ? ts.getTime() : Date.parse(ts);\n}\n\nfunction toolVersion(doc: HDFResults): string {\n return (doc.tool?.version ?? '').trim();\n}\n\n/** One input's root metadata, verbatim, for extensions.passthrough[\"hdf-merge\"].sources[]. */\nfunction sourceProvenance(index: number, src: MergeSource): Record<string, unknown> {\n const entry: Record<string, unknown> = { index, name: src.name };\n if (src.doc.tool !== undefined) entry.tool = src.doc.tool;\n if (src.doc.generator !== undefined) entry.generator = src.doc.generator;\n if (src.doc.timestamp !== undefined) entry.timestamp = src.doc.timestamp;\n if (src.doc.runner !== undefined) entry.runner = src.doc.runner;\n return entry;\n}\n","// Document-type detection — the TypeScript peer of hdf-engine/go/detect.go.\n// Fingerprints an HDF document by its root keys and returns the schema type\n// string. Kept at behavioural parity with the Go implementation (see\n// go/detect_test.go and src/detect.test.ts, which assert both against the same\n// bundled schema examples).\n\n/** The eight HDF document type strings, matching validators.Type* in Go. */\nexport type HdfDocType =\n | 'results'\n | 'baseline'\n | 'system'\n | 'plan'\n | 'amendments'\n | 'evidence-package'\n | 'comparison'\n | 'requirement-change-event'\n | '';\n\n/**\n * Detect fingerprints an HDF document by its root keys and returns the schema\n * type string, or '' when the input is not a JSON object or matches no known\n * HDF document type.\n */\nexport function detect(input: string): HdfDocType {\n let parsed: unknown;\n try {\n parsed = JSON.parse(input);\n } catch {\n return '';\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n return '';\n }\n const doc = parsed as Record<string, unknown>;\n const has = (...keys: string[]): boolean =>\n keys.every((k) => Object.prototype.hasOwnProperty.call(doc, k));\n\n // Most specific first. A requirement-change-event carries the singular\n // requirementId together with the state/before/after triad — a combination\n // no other HDF document type has — so it is checked ahead of the rest.\n if (has('requirementId', 'state', 'before', 'after')) return 'requirement-change-event';\n\n if (has('contents')) return 'evidence-package';\n if (has('overrides')) return 'amendments';\n if (has('assessments')) return 'plan';\n if (has('comparisonMode')) return 'comparison';\n if (has('baselines')) return 'results';\n if (has('components')) return 'system';\n if (has('requirements')) return 'baseline';\n return '';\n}\n","// Amendments-layer resolution for schema-typed requirements: the engine's bridge\n// onto the canonical ladders in @mitre/hdf-utilities. Its own module because\n// query.ts and compliance.ts both need it and query.ts already imports\n// compliance.ts — putting it in either would either fork the mapping or make the\n// two import each other. Parity: EffectiveImpactOf and statusOverrideInputs in\n// go/filter.go.\n\nimport type { EvaluatedRequirement } from '@mitre/hdf-schema';\nimport { computeEffectiveImpact, parseTimestamp, type StatusOverrideInput, isGoZeroTime } from '@mitre/hdf-utilities';\n\n/**\n * Maps a requirement's schema overrides onto the shared helper's neutral shape,\n * whose timestamps are the RFC3339 strings the schema's Date fields came from.\n */\nexport function overrideInputs(control: EvaluatedRequirement): StatusOverrideInput[] {\n // One entry per override, slot preserved even for a member that carries\n // nothing: governingPoamType reads the index past this array's length as a\n // poam index, so dropping a slot would name the wrong poam.\n return (control.statusOverrides ?? []).map((o) => ({\n status: o?.status as string | undefined,\n appliedAt: rfc3339(o?.appliedAt),\n expiresAt: rfc3339(o?.expiresAt),\n // Carried so effective IMPACT resolves from the same overrides; eligibility\n // is per-field, so one override may govern one and not the other.\n impact: o?.impact?.value,\n }));\n}\n\n/**\n * The schema types these as Date, but a parsed document carries the RFC3339\n * strings they came from, so both shapes arrive here. A string passes through\n * for the helper's parseTimestamp to read, which keeps a zone-less value UTC\n * instead of host-local.\n *\n * Absent, unparseable, and Go's zero time all yield undefined, matching Go:\n * its timestamps are non-pointer time.Time, so an unset one round-trips as\n * 0001-01-01T00:00:00Z and decodes back to IsZero, and its ladder reads that as\n * never expiring rather than as a real instant in year 1.\n */\nfunction rfc3339(value: Date | string | undefined): string | undefined {\n if (!value) return undefined;\n const parsed = typeof value === 'string' ? parseTimestamp(value) : value;\n if (parsed === null || Number.isNaN(parsed.getTime())) return undefined;\n if (isGoZeroTime(parsed)) return undefined;\n return typeof value === 'string' ? value : parsed.toISOString();\n}\n\n/**\n * The requirement's impact after its governing non-expired impact override, else\n * its own. Computed rather than injected the way status is, because impact has\n * no competing display conventions to reconcile — the ladder in hdf-utilities is\n * canonical. An undefined reference means now.\n */\nexport function effectiveImpactOf(control: EvaluatedRequirement, now?: string): number {\n return computeEffectiveImpact({ impact: control.impact, overrides: overrideInputs(control) }, now);\n}\n","// Compliance & threshold engine — the TypeScript peer of\n// hdf-engine/go/compliance.go. Pure functions, kept at behavioural parity with\n// the Go implementation (see test/compliance.test.ts, which runs both over the\n// same fixture). Violation message formats match the Go fmt.Sprintf output.\n\nimport type { HDFResults, EvaluatedRequirement, RequirementResult, Severity } from '@mitre/hdf-schema';\nimport { worstStatus, impactToSeverity } from '@mitre/hdf-utilities';\nimport { effectiveImpactOf } from './effective.js';\nimport type { ThresholdRule } from './rules.js';\nimport type { Match } from './query.js';\n\n/** Threshold status-key constants (SAF CLI-compatible keys). */\nexport const THRESHOLD_PASSED = 'passed';\nexport const THRESHOLD_FAILED = 'failed';\nexport const THRESHOLD_SKIPPED = 'skipped';\nexport const THRESHOLD_ERROR = 'error';\nexport const THRESHOLD_NOT_APPLICABLE = 'not_applicable';\n\n/**\n * SAF CLI's name for the notApplicable bucket. It names a severity score\n * rather than the status the bucket counts, so this tool emits\n * not_applicable, but SAF's own threshold files are a supported input — so it\n * is a permanent second spelling on input, not a deprecation.\n * Parity: safNotApplicableKey in go/compliance.go.\n */\nexport const SAF_NOT_APPLICABLE_KEY = 'no_impact';\n\n/**\n * The name the informational severity bucket had before 3.7.0 renamed it.\n * Accepted on input and echoed back in violations written with it, never\n * emitted by generate.\n */\nconst LEGACY_INFORMATIONAL_KEY = 'none';\n\nexport interface SeverityCounts {\n critical: number;\n high: number;\n medium: number;\n low: number;\n /** The schema's fifth severity; also absorbs a severity that cannot be derived or is not in the enum. */\n informational: number;\n total: number;\n}\n\nexport interface StatusCounts {\n passed: SeverityCounts;\n failed: SeverityCounts;\n skipped: SeverityCounts;\n error: SeverityCounts;\n notApplicable: SeverityCounts;\n}\n\nexport interface ControlIDMapping {\n id: string;\n status: string;\n /**\n * The counting BUCKET, not the requirement's raw severity string: always one\n * of `critical`, `high`, `medium`, `low`, `informational`, having gone through\n * severityBucket. Anything else would name a bucket the counts do not have,\n * and a bound listing the control would report a mismatch against the bucket\n * that control was counted in.\n */\n severity: string;\n /**\n * The requirement's title when it has one, carried so a breached count bound\n * can name its offenders the way a rule violation does. A reader should not\n * have to know which kind of bound produced a line to know whether it will be\n * readable. Parity: ControlIDMapping.Title in go/compliance.go.\n */\n title?: string;\n}\n\nexport interface ThresholdBound {\n min?: number;\n max?: number;\n controls?: string[];\n}\n\nexport interface ThresholdSeverity {\n critical?: ThresholdBound;\n high?: ThresholdBound;\n medium?: ThresholdBound;\n low?: ThresholdBound;\n informational?: ThresholdBound;\n /** The name `informational` replaced in 3.7.0; resolved on read, never written. */\n none?: ThresholdBound;\n total?: ThresholdBound;\n}\n\nexport interface ComplianceBound {\n min?: number;\n max?: number;\n}\n\nexport interface ThresholdConfig {\n compliance?: ComplianceBound;\n passed?: ThresholdSeverity;\n failed?: ThresholdSeverity;\n skipped?: ThresholdSeverity;\n error?: ThresholdSeverity;\n notApplicable?: ThresholdSeverity;\n /** SAF CLI's spelling of notApplicable, accepted so a SAF threshold file\n * validates unchanged. Resolved by resolveSafSection; never written. */\n noImpact?: ThresholdSeverity;\n /**\n * The additive half: a filter predicate plus a bound, for the policies the\n * fixed grid above cannot express. See rules.ts.\n */\n rules?: ThresholdRule[];\n}\n\nfunction newSeverityCounts(): SeverityCounts {\n return { critical: 0, high: 0, medium: 0, low: 0, informational: 0, total: 0 };\n}\n\nfunction newStatusCounts(): StatusCounts {\n return {\n passed: newSeverityCounts(),\n failed: newSeverityCounts(),\n skipped: newSeverityCounts(),\n error: newSeverityCounts(),\n notApplicable: newSeverityCounts(),\n };\n}\n\n/**\n * overallStatus is the canonical worst-wins roll-up of a requirement's result\n * statuses, delegated to @mitre/hdf-utilities worstStatus (error > failed >\n * passed > notApplicable > notReviewed; empty → notReviewed). No local rank\n * switch — the TS peer of the Go overallStatus dedup (supersedes hdf-libs-ixhx).\n */\nexport function overallStatus(results: RequirementResult[]): string {\n return worstStatus(results.map((r) => String(r.status)));\n}\n\n/**\n * deriveSeverity determines the severity string from impact and optional explicit\n * severity, using impactToSeverity. Both paths yield a value from the schema's\n * severity enum: an explicit informational and an impact-derived one are the same\n * thing and must not land in different buckets.\n */\nexport function deriveSeverity(impact: number, severity?: Severity | null): string {\n // Presence-based, matching Go DeriveSeverity's `if severity != nil`: an explicit\n // severity — including an empty string — is returned verbatim; only a\n // null/undefined severity derives from impact. Testing truthiness here would\n // send \"\" through the impact path and diverge from Go (bead 4908.20).\n if (severity != null) {\n return String(severity);\n }\n return impactToSeverity(impact);\n}\n\n/**\n * severityBucket folds a severity string into the bucket the threshold grid\n * counts it in. The schema's four named levels pass through; informational and\n * anything outside the enum land in informational, so a malformed severity is\n * counted rather than dropped and a document still gates.\n *\n * Exported because ControlIDMapping.severity is the bucket, not the raw string:\n * a caller assembling its own control map has to apply the same rule or its\n * listing and its counts will disagree. Parity: SeverityBucket in\n * go/compliance.go.\n */\nexport function severityBucket(severity: string): string {\n switch (severity) {\n case 'critical':\n case 'high':\n case 'medium':\n case 'low':\n return severity;\n default:\n return 'informational';\n }\n}\n\nfunction statusBucket(counts: StatusCounts, status: string): SeverityCounts {\n switch (status) {\n case 'passed':\n return counts.passed;\n case 'failed':\n return counts.failed;\n case 'error':\n return counts.error;\n case 'notApplicable':\n return counts.notApplicable;\n case 'notReviewed':\n return counts.skipped;\n default:\n return counts.skipped;\n }\n}\n\nfunction addCount(counts: StatusCounts, status: string, severity: string): void {\n const sc = statusBucket(counts, status);\n sc.total++;\n switch (severityBucket(severity)) {\n case 'critical':\n sc.critical++;\n break;\n case 'high':\n sc.high++;\n break;\n case 'medium':\n sc.medium++;\n break;\n case 'low':\n sc.low++;\n break;\n default:\n sc.informational++;\n }\n}\n\n/**\n * statusToThresholdKey's inverse, for reporting a requirement found via the\n * control map. A finding line describes the REQUIREMENT, so it names the\n * requirement's own status — which is also the only vocabulary\n * `hdf query --status` accepts, so a reader can paste the value straight into a\n * query. The threshold key is a bucket name and is refused there.\n * Parity: thresholdKeyToStatus in go/compliance.go.\n */\nfunction thresholdKeyToStatus(key: string): string {\n switch (key) {\n case THRESHOLD_PASSED:\n return 'passed';\n case THRESHOLD_FAILED:\n return 'failed';\n case THRESHOLD_SKIPPED:\n return 'notReviewed';\n case THRESHOLD_ERROR:\n return 'error';\n case THRESHOLD_NOT_APPLICABLE:\n case SAF_NOT_APPLICABLE_KEY:\n return 'notApplicable';\n default:\n return key;\n }\n}\n\nfunction statusToThresholdKey(status: string): string {\n switch (status) {\n case 'passed':\n return THRESHOLD_PASSED;\n case 'failed':\n return THRESHOLD_FAILED;\n case 'notReviewed':\n return THRESHOLD_SKIPPED;\n case 'error':\n return THRESHOLD_ERROR;\n case 'notApplicable':\n return THRESHOLD_NOT_APPLICABLE;\n default:\n return THRESHOLD_SKIPPED;\n }\n}\n\n/**\n * countControlsByStatusSeverity counts requirements by overall status and severity.\n * Reads each requirement's OWN impact and raw result statuses by design: this is the\n * no-override-awareness twin of countControlsByStatus, which is its purpose.\n */\nexport function countControlsByStatusSeverity(results: HDFResults): StatusCounts {\n const counts = newStatusCounts();\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n addCount(counts, overallStatus(req.results ?? []), deriveSeverity(req.impact, reqSeverity(req)));\n }\n }\n return counts;\n}\n\n/**\n * countControlsByStatus counts requirements by a caller-resolved status — the\n * injected-resolver twin of countControlsByStatusSeverity (which counts raw\n * result statuses with no override awareness). statusOf returns each\n * requirement's status in the schema vocabulary (passed/failed/notApplicable/\n * notReviewed/error); an empty or unrecognized value counts as skipped, and an\n * absent resolver yields all-skipped. Callers build effective-status rollups\n * (e.g. compliance with and without agent-attributed overrides) without the\n * engine binding to any one status convention. Parity: go/compliance.go.\n */\nexport function countControlsByStatus(\n results: HDFResults,\n statusOf?: (req: EvaluatedRequirement) => string,\n now?: string,\n): StatusCounts {\n const counts = newStatusCounts();\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n const status = statusOf ? statusOf(req) : '';\n // Effective impact, so a governing riskAdjustment moves the requirement\n // into the band it was re-scored into. This function already resolves\n // STATUS through the injected resolver; deriving severity from the raw\n // impact counted one post-adjudication and the other pre-adjudication.\n // As of now, so an impact override judged expired by a threshold's reference\n // time stops re-scoring here too. Parity: CountControlsByStatusAt in go.\n addCount(counts, status, deriveSeverity(effectiveImpactOf(req, now), reqSeverity(req)));\n }\n }\n return counts;\n}\n\n/**\n * agentOverrideCount counts the status overrides across a result set whose\n * applied-by identity type is \"agent\" — the detective count. Deterministic\n * from_vex/system overrides are excluded so the count is a meaningful AI-scrutiny\n * signal. Parity: go/compliance.go AgentOverrideCount.\n */\nexport function agentOverrideCount(results: HDFResults): number {\n let count = 0;\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n for (const o of req.statusOverrides ?? []) {\n if (o.appliedBy?.type === 'agent') {\n count++;\n }\n }\n }\n }\n return count;\n}\n\n/** MapControlIDs builds control ID → status/severity mappings from a result set. */\nexport function mapControlIDs(results: HDFResults): ControlIDMapping[] {\n const mappings: ControlIDMapping[] = [];\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n const status = overallStatus(req.results ?? []);\n mappings.push({\n id: req.id,\n status: statusToThresholdKey(status),\n severity: severityBucket(deriveSeverity(req.impact, reqSeverity(req))),\n title: req.title ?? '',\n });\n }\n }\n return mappings;\n}\n\n/**\n * mapControlIDsByStatus builds control ID → status/severity mappings using a\n * caller-resolved status — the injected-resolver twin of mapControlIDs (which\n * maps raw result statuses). statusOf returns each requirement's status in the\n * schema vocabulary; an empty or unrecognized value maps to skipped, and an\n * absent resolver yields all-skipped. Callers build effective-status control\n * listings (the same injection pattern as countControlsByStatus). Parity:\n * go/compliance.go MapControlIDsByStatus.\n */\nexport function mapControlIDsByStatus(\n results: HDFResults,\n statusOf?: (req: EvaluatedRequirement) => string,\n now?: string,\n): ControlIDMapping[] {\n const mappings: ControlIDMapping[] = [];\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n const status = statusOf ? statusOf(req) : '';\n mappings.push({\n id: req.id,\n status: statusToThresholdKey(status),\n // Effective impact, matching countControlsByStatus, so a control\n // listing and the counts it is listed alongside cannot disagree.\n severity: severityBucket(deriveSeverity(effectiveImpactOf(req, now), reqSeverity(req))),\n title: req.title ?? '',\n });\n }\n }\n return mappings;\n}\n\nfunction reqSeverity(req: EvaluatedRequirement): Severity | null {\n return (req.severity ?? null) as Severity | null;\n}\n\n/**\n * normalizeThresholdConfig folds SAF's scalar count bound into the object form a\n * bound is otherwise written in: a bare `total: 19` means EXACTLY 19, measured in\n * SAF's own validate-threshold command, which guards the scalar path with\n * `typeof !== 'object'` and then fails on inequality.\n *\n * Go reaches this rule through ThresholdBound's YAML decoding; TypeScript does no\n * YAML decoding of its own, so a consumer that parsed a SAF file itself calls\n * this before evaluating. Both are pinned by testdata/saf-bound-shorthand-cases.json.\n * The input is not mutated.\n */\nexport function normalizeThresholdConfig(config: ThresholdConfig): ThresholdConfig {\n const bound = (value: unknown): ThresholdBound | undefined => {\n if (value === undefined || value === null) return undefined;\n if (typeof value === 'number') {\n if (!Number.isInteger(value)) {\n throw new Error(`a bound written as a bare value must be a whole number of controls, got ${value}`);\n }\n return { min: value, max: value };\n }\n // Anything that is not a mapping is refused rather than passed through: a\n // \"bound\" whose min and max read undefined applies to nothing, which is the\n // silent no-op this function exists to close. An array counts — it is\n // typeof 'object' and carries no bound. Go refuses both for the same reason\n // (a non-!!int scalar, and any node that is not a mapping).\n if (typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(\n `a bound must be a whole number of controls or a min/max mapping, got ${JSON.stringify(value)}`,\n );\n }\n // Mirror Go's unmarshaller: only min, max and controls are keys, min and\n // max are whole numbers, controls a list of strings. Passing anything else\n // through typed as a bound is how {min: \"abc\"} came to compare a count\n // against text and never fire.\n for (const [key, v] of Object.entries(value as Record<string, unknown>)) {\n if (key === 'min' || key === 'max') {\n if (!Number.isInteger(v)) {\n throw new Error(`a bound's ${key} must be a whole number of controls, got ${JSON.stringify(v)}`);\n }\n } else if (key === 'controls') {\n if (!Array.isArray(v) || !v.every((x) => typeof x === 'string')) {\n throw new Error(`a bound's controls must be a list of control ids, got ${JSON.stringify(v)}`);\n }\n } else {\n throw new Error(`field ${key} is not a known bound`);\n }\n }\n return value as ThresholdBound;\n };\n\n const section = (ts: ThresholdSeverity | undefined): ThresholdSeverity | undefined => {\n if (!ts) return ts;\n const out: ThresholdSeverity = {};\n for (const key of ['critical', 'high', 'medium', 'low', 'informational', 'none', 'total'] as const) {\n const normalized = bound((ts as Record<string, unknown>)[key]);\n if (normalized !== undefined) out[key] = normalized;\n }\n return out;\n };\n\n return {\n ...config,\n passed: section(config.passed),\n failed: section(config.failed),\n skipped: section(config.skipped),\n error: section(config.error),\n notApplicable: section(config.notApplicable),\n noImpact: section(config.noImpact),\n };\n}\n\n/**\n * A count set's five status buckets, so a bucket-wise operation is written once\n * and cannot miss one. Parity: statusBuckets in go/compliance.go.\n */\nfunction statusBuckets(counts: StatusCounts): SeverityCounts[] {\n return [counts.passed, counts.failed, counts.skipped, counts.error, counts.notApplicable];\n}\n\nfunction addSeverities(dst: SeverityCounts, src: SeverityCounts): void {\n dst.critical += src.critical;\n dst.high += src.high;\n dst.medium += src.medium;\n dst.low += src.low;\n dst.informational += src.informational;\n dst.total += src.total;\n}\n\n/**\n * addCounts sums count sets bucket by bucket and severity by severity, returning\n * a new set and leaving its arguments untouched — a caller that reports the parts\n * beside the whole is summing the very objects it still has to print. Each\n * bucket's `total` is added, never recomputed from the severity fields.\n *\n * The counting functions above measure one document at a time, so a caller that\n * composes documents — the HTML report rolling baselines into a source and\n * sources into a whole, each evaluated as of its own assessment time — needs this\n * rather than a second counting pass. Combining whole DOCUMENTS is merge's job,\n * not this function's (ADR-0016 §1). Parity: AddCounts in go/compliance.go,\n * pinned by testdata/status-counts-rollup-cases.json.\n */\nexport function addCounts(...counts: StatusCounts[]): StatusCounts {\n const out = newStatusCounts();\n const dst = statusBuckets(out);\n for (const c of counts) {\n // Skipped, not treated as a zero set: these are exported helpers, so a\n // JavaScript caller reaches them without the compiler's non-null guarantee,\n // and AddCounts in go/compliance.go skips a nil the same way.\n if (c == null) continue;\n statusBuckets(c).forEach((bucket, i) => addSeverities(dst[i]!, bucket));\n }\n return out;\n}\n\n/**\n * severityTotals projects a count set onto severity alone, summing each severity\n * across every status — so `total` is the whole set's requirement count. A\n * severity breakdown answers \"how much risk is in this document\", which is a\n * question about all of it, not about its failures. Parity: SeverityTotals in\n * go/compliance.go.\n */\nexport function severityTotals(counts: StatusCounts): SeverityCounts {\n const out = newSeverityCounts();\n if (counts == null) return out;\n for (const bucket of statusBuckets(counts)) addSeverities(out, bucket);\n return out;\n}\n\n/**\n * calculateCompliance returns the compliance percentage rounded to two decimals:\n * passed / (passed + failed + skipped + error) * 100; notApplicable excluded.\n */\nexport function calculateCompliance(counts: StatusCounts): number {\n const relevant = counts.passed.total + counts.failed.total + counts.skipped.total + counts.error.total;\n if (relevant === 0) {\n return 0;\n }\n const pct = (counts.passed.total / relevant) * 100;\n return Math.round(pct * 100) / 100;\n}\n\n/** One status category of a spec after the former severity name has been resolved. */\ninterface ResolvedSection {\n name: string;\n threshold: ThresholdSeverity | undefined;\n counts: SeverityCounts;\n wroteNone: boolean;\n}\n\n/**\n * Picks the notApplicable section from whichever of the two accepted spellings\n * the author wrote, carrying that spelling into the section's name so a\n * violation names the key they will find in their own file. A spec setting both\n * is refused rather than resolved: they name one bucket, so honouring one would\n * drop a bound the author wrote.\n * Parity: resolveSAFSection in go/compliance.go.\n */\nfunction resolveSafSection(\n config: ThresholdConfig,\n counts: StatusCounts\n): { section: ResolvedSection; refusal: string } {\n const base = { counts: counts.notApplicable, wroteNone: false };\n if (config.notApplicable !== undefined && config.noImpact !== undefined) {\n return {\n section: { name: THRESHOLD_NOT_APPLICABLE, threshold: config.notApplicable, ...base },\n refusal: `both '${SAF_NOT_APPLICABLE_KEY}' and '${THRESHOLD_NOT_APPLICABLE}' are set; they name the same bucket`,\n };\n }\n if (config.noImpact !== undefined) {\n return {\n section: { name: SAF_NOT_APPLICABLE_KEY, threshold: config.noImpact, ...base },\n refusal: '',\n };\n }\n return {\n section: { name: THRESHOLD_NOT_APPLICABLE, threshold: config.notApplicable, ...base },\n refusal: '',\n };\n}\n\n/**\n * Renders a control map's status in the spelling the spec's section used, so\n * both halves of an \"expected X but found Y\" message speak one vocabulary. Only\n * the notApplicable bucket has two spellings.\n * Parity: statusKeyFor in go/compliance.go.\n */\nfunction statusKeyFor(mapped: string, sectionKey: string): string {\n if (mapped === THRESHOLD_NOT_APPLICABLE && sectionKey === SAF_NOT_APPLICABLE_KEY) {\n return SAF_NOT_APPLICABLE_KEY;\n }\n return mapped;\n}\n\n/**\n * Folds a section's pre-3.7 `none` key into `informational`, reporting whether\n * the bound was written that way so a violation can name the key the author will\n * find in their own file. A spec setting both is refused rather than resolved:\n * 3.7.0 renamed the bucket, so the two name one thing and silently honouring one\n * would drop a bound the author wrote.\n *\n * The caller's section is COPIED, never rewritten. Folding in place made the\n * name a one-shot property of the config object: the same spec reported the\n * author's key on its first validate pass and the canonical one on every pass\n * after, which is the confusion naming the author's key exists to remove.\n *\n * Parity: resolveLegacySeverity in go/compliance.go.\n */\nfunction resolveLegacySeverity(\n name: string,\n ts: ThresholdSeverity | undefined,\n): { threshold: ThresholdSeverity | undefined; wroteNone: boolean; refusal: string } {\n if (!ts?.none) {\n return { threshold: ts, wroteNone: false, refusal: '' };\n }\n if (ts.informational) {\n return {\n threshold: ts,\n wroteNone: false,\n refusal: `${name}: both 'none' and 'informational' are set; 'informational' replaced 'none' in 3.7.0 and both name the same bucket`,\n };\n }\n const resolved: ThresholdSeverity = { ...ts, informational: ts.none };\n delete resolved.none;\n return { threshold: resolved, wroteNone: true, refusal: '' };\n}\n\n/**\n * Violation is one breached bound together with the requirements that breached\n * it. `findings` is empty in two cases, for two different reasons: a compliance\n * percentage is a property of the whole document, so it has no offending\n * requirement to name; and a controls list already names its requirement in the\n * message, so repeating it would say the same thing twice.\n *\n * Findings from a RULE are the filter's own matches and carry every field. Those\n * from a COUNT bound are rebuilt from the control map, which holds only id,\n * title, status and severity — so `impact`, `baseline`, `baselineIndex` and\n * `index` are zero there rather than the requirement's real values. The CLI\n * prints none of them; a consumer serializing `findings` should not read them as\n * data. Parity: Violation in go/rules.go.\n */\nexport interface Violation {\n message: string;\n findings: Match[];\n}\n\n/** The messages of a violation list, for a caller that wants the verdict alone. */\nexport function violationMessages(violations: Violation[]): string[] {\n return violations.map((v) => v.message);\n}\n\n/**\n * validateThresholds checks all threshold bounds against observed counts and\n * compliance, returning human-readable violation messages (empty when all pass).\n */\nexport function validateThresholds(\n config: ThresholdConfig,\n counts: StatusCounts,\n compliance: number,\n controlMap: ControlIDMapping[],\n): string[] {\n const violations = violationMessages(validateGrid(config, counts, compliance, controlMap));\n // A config carrying rules cannot be judged by the grid alone. Returning the\n // grid's verdict as though the rules were satisfied would report a passing\n // gate over policy nobody applied, so the caller is told rather than quietly\n // getting half an answer. Appended, not prepended, so the two languages order\n // violations alike. Parity: ValidateThresholds in go/compliance.go.\n if (config.rules && config.rules.length > 0) {\n violations.push(ruleRefusal(config.rules.length));\n }\n return violations;\n}\n\n/**\n * ruleRefusal is what a caller is told when a policy carries rules the path it\n * used cannot evaluate. It reaches end users, so it names the spec and what to do\n * about it rather than an internal function. Parity: ruleRefusal in go/rules.go.\n */\nexport function ruleRefusal(count: number): string {\n const noun = count === 1 ? 'rule' : 'rules';\n return (\n `this spec declares ${count} ${noun}, which this evaluation path cannot apply; ` +\n `the tool must evaluate rules against the document, not against counts alone`\n );\n}\n\n/**\n * validateGrid is the status x severity half of a policy, shared by\n * validateThresholds and evaluate. Parity: validateGrid in go/compliance.go.\n */\nexport function validateGrid(\n config: ThresholdConfig,\n counts: StatusCounts,\n compliance: number,\n controlMap: ControlIDMapping[],\n): Violation[] {\n const violations: Violation[] = [];\n\n // Normalized here rather than in each caller: a consumer that parsed a SAF\n // threshold file itself hands over a scalar bound, and a bound whose min and max\n // both read undefined applies to nothing — a gate that reports green because it\n // checked nothing. Go cannot reach that state because its YAML decoding\n // normalizes on the way in; this is where TypeScript gets the same guarantee.\n config = normalizeThresholdConfig(config);\n\n // Every construction path lands here, so the former name is resolved once\n // rather than in each caller. Resolved before the compliance bounds so a\n // refusal is reported ahead of them.\n const { section: naSection, refusal: naRefusal } = resolveSafSection(config, counts);\n if (naRefusal) {\n violations.push({ message: naRefusal, findings: [] });\n }\n\n const sections: ResolvedSection[] = [\n { name: THRESHOLD_PASSED, threshold: config.passed, counts: counts.passed, wroteNone: false },\n { name: THRESHOLD_FAILED, threshold: config.failed, counts: counts.failed, wroteNone: false },\n { name: THRESHOLD_SKIPPED, threshold: config.skipped, counts: counts.skipped, wroteNone: false },\n { name: THRESHOLD_ERROR, threshold: config.error, counts: counts.error, wroteNone: false },\n naSection,\n ];\n for (const section of sections) {\n const { threshold, wroteNone, refusal } = resolveLegacySeverity(section.name, section.threshold);\n if (refusal) {\n violations.push({ message: refusal, findings: [] });\n }\n section.threshold = threshold;\n section.wroteNone = wroteNone;\n }\n\n // A requirement id names the requirement, not one finding, so several entries\n // legitimately carry it (one CVE reported against several packages). Keeping\n // every entry is what lets a named-control assertion be judged against all of\n // them rather than whichever one was indexed last.\n const actualControls = new Map<string, ControlIDMapping[]>();\n for (const m of controlMap) {\n const existing = actualControls.get(m.id);\n if (existing) {\n existing.push(m);\n } else {\n actualControls.set(m.id, [m]);\n }\n }\n\n if (config.compliance) {\n // No findings: a compliance percentage is a property of the whole document,\n // so there is no offending requirement to name.\n if (config.compliance.min !== undefined && compliance < config.compliance.min) {\n violations.push({\n message: `compliance ${compliance.toFixed(2)}% is below minimum ${config.compliance.min.toFixed(2)}%`,\n findings: [],\n });\n }\n if (config.compliance.max !== undefined && compliance > config.compliance.max) {\n violations.push({\n message: `compliance ${compliance.toFixed(2)}% exceeds maximum ${config.compliance.max.toFixed(2)}%`,\n findings: [],\n });\n }\n }\n\n for (const section of sections) {\n violations.push(\n ...checkSeverityThreshold(\n section.name,\n section.threshold,\n section.counts,\n actualControls,\n section.wroteNone,\n controlMap,\n ),\n );\n }\n\n return violations;\n}\n\nfunction checkSeverityThreshold(\n status: string,\n threshold: ThresholdSeverity | undefined,\n actual: SeverityCounts,\n actualControls: Map<string, ControlIDMapping[]>,\n wroteNone: boolean,\n controlMap: ControlIDMapping[],\n): Violation[] {\n if (!threshold) {\n return [];\n }\n // The path names the key the author wrote; the comparison below keeps the\n // canonical bucket name, because informational is where the control was\n // actually counted. Reporting `expected no_impact/none` would name a bucket\n // that does not exist.\n const pathLabel = (label: string): string =>\n wroteNone && label === 'informational' ? LEGACY_INFORMATIONAL_KEY : label;\n\n // Both sides are normalized to the schema status, because a bucket has two\n // accepted key spellings and the section carries whichever one the author\n // wrote while the control map always records the canonical one.\n const wantStatus = thresholdKeyToStatus(status);\n\n // The requirements a count bound counted, so a breached bound can name them.\n // `total` is the whole status bucket; a severity label narrows it further.\n const inBucket = (label: string): Match[] =>\n controlMap\n .filter(\n (m) =>\n thresholdKeyToStatus(m.status) === wantStatus && (label === 'total' || m.severity === label)\n )\n .map((m) => ({\n id: m.id,\n title: m.title ?? '',\n status: thresholdKeyToStatus(m.status),\n impact: 0,\n severity: m.severity,\n baseline: '',\n baselineIndex: 0,\n index: 0,\n }));\n\n const violations: Violation[] = [];\n const check = (label: string, bound: ThresholdBound | undefined, actualCount: number): void => {\n if (!bound) {\n return;\n }\n const path = `${status}.${pathLabel(label)}`;\n if (bound.min !== undefined && actualCount < bound.min) {\n violations.push({ message: `${path}: ${actualCount} is below minimum ${bound.min}`, findings: inBucket(label) });\n }\n if (bound.max !== undefined && actualCount > bound.max) {\n violations.push({ message: `${path}: ${actualCount} exceeds maximum ${bound.max}`, findings: inBucket(label) });\n }\n for (const expectedID of bound.controls ?? []) {\n // A controls list already names its requirement in the message, so these\n // carry no findings: repeating the id underneath would say it twice.\n const matches = actualControls.get(expectedID) ?? [];\n if (matches.length === 0) {\n violations.push({ message: `${path}: expected control ${expectedID} not found in results`, findings: [] });\n continue;\n }\n // Fail-closed: every entry carrying the id must satisfy the assertion. One\n // passing finding out of three must not green a gate.\n matches.forEach((ac, i) => {\n if (thresholdKeyToStatus(ac.status) === wantStatus && ac.severity === label) {\n return;\n }\n const entry = matches.length > 1 ? ` (entry ${i + 1} of ${matches.length})` : '';\n violations.push({\n message: `${path}: control ${expectedID} expected ${status}/${label} but found ${statusKeyFor(ac.status, status)}/${ac.severity}${entry}`,\n findings: [],\n });\n });\n }\n };\n\n check('critical', threshold.critical, actual.critical);\n check('high', threshold.high, actual.high);\n check('medium', threshold.medium, actual.medium);\n check('low', threshold.low, actual.low);\n check('informational', threshold.informational, actual.informational);\n check('total', threshold.total, actual.total);\n\n return violations;\n}\n","// The closed vocabularies a filter value may name, and the aliases accepted for\n// them — the TypeScript peer of hdf-engine/go/vocabulary.go, pinned at parity by\n// testdata/filter-vocabulary-cases.json, which both suites read.\n\nimport { DISPOSITION_VALUES, POAM_VALID, POAM_NONE_VALID, validPoamFilter } from './query.js';\n\n/**\n * The closed vocabulary a status filter may name: the schema's Result_Status\n * enum. It is the EFFECTIVE status that is compared — the resolver a caller\n * injects runs the override ladder first — so these are the values a requirement\n * can present after its amendments are applied.\n */\nexport const STATUS_VALUES = ['passed', 'failed', 'notApplicable', 'notReviewed', 'error'] as const;\n\n/** The schema's Severity enum, which is also what deriveSeverity returns. */\nexport const SEVERITY_VALUES = ['critical', 'high', 'medium', 'low', 'informational'] as const;\n\n/**\n * The forms a value has legitimately arrived under, enumerated rather than\n * derived. An earlier version stripped separators to fold them together, which\n * also silently repaired typos: 'wai-ver' became 'waiver'. A closed vocabulary\n * that quietly corrects a misspelling is not closed.\n *\n * The status and disposition entries are separator variants of one name. The\n * severity entry is not: 3.7.0 renamed the bucket, and 'none' is the name it had\n * before, kept so a command line or spec written against the old vocabulary\n * selects what it always did.\n */\n/**\n * `advertise` records which forms help text should TEACH, so that is a property of\n * the entry rather than of whichever string literal a command happens to hold. A\n * separator variant is part of the CLI's display vocabulary and is taught; a\n * retired name is honoured and never taught, because advertising it would hand a\n * new user the name a release replaced. Parity: FilterAlias in go/vocabulary.go.\n */\nexport interface FilterAlias {\n form: string;\n means: string;\n advertise: boolean;\n}\n\nconst STATUS_ALIAS_LIST: FilterAlias[] = [\n { form: 'not_applicable', means: 'notApplicable', advertise: true },\n { form: 'not_reviewed', means: 'notReviewed', advertise: true },\n];\nconst SEVERITY_ALIAS_LIST: FilterAlias[] = [{ form: 'none', means: 'informational', advertise: false }];\nconst DISPOSITION_ALIAS_LIST: FilterAlias[] = [\n { form: 'false_positive', means: 'falsePositive', advertise: true },\n];\n\n/** Derived from the lists, so an alias cannot be accepted without declaring whether it is advertised. */\nfunction aliasMap(aliases: FilterAlias[]): Record<string, string> {\n return Object.fromEntries(aliases.map((a) => [a.form, a.means]));\n}\n\nconst STATUS_ALIASES = aliasMap(STATUS_ALIAS_LIST);\nconst SEVERITY_ALIASES = aliasMap(SEVERITY_ALIAS_LIST);\nconst DISPOSITION_ALIASES = aliasMap(DISPOSITION_ALIAS_LIST);\n\n/** The accepted non-canonical forms for a field, or undefined when it has no closed vocabulary. */\nexport function filterAliases(field: string): FilterAlias[] | undefined {\n switch (field) {\n case 'status':\n return STATUS_ALIAS_LIST;\n case 'severity':\n return SEVERITY_ALIAS_LIST;\n case 'disposition':\n return DISPOSITION_ALIAS_LIST;\n default:\n return undefined;\n }\n}\n\n/** The canonical vocabulary for a field, or undefined when it has no closed one. */\nexport function filterValues(field: string): readonly string[] | undefined {\n switch (field) {\n case 'status':\n return STATUS_VALUES;\n case 'severity':\n return SEVERITY_VALUES;\n case 'disposition':\n return DISPOSITION_VALUES;\n default:\n return undefined;\n }\n}\n\n/**\n * The forms a help string or tool schema should name for a field: the canonical\n * vocabulary, then the aliases marked for teaching. Every value here is accepted,\n * but not everything accepted is here — a retired name is deliberately absent.\n * Parity: AdvertisedFilterValues in go/vocabulary.go.\n */\nexport function advertisedFilterValues(field: string): string[] | undefined {\n const canonical = filterValues(field);\n if (!canonical) return undefined;\n return [...canonical, ...(filterAliases(field) ?? []).filter((a) => a.advertise).map((a) => a.form)];\n}\n\n/**\n * Folds a value to the form comparisons use. Case only: two spellings are the\n * same value because this file says so, not because enough punctuation was\n * removed to make them collide.\n */\nexport function normalizeKey(s: string): string {\n return s.trim().toLowerCase();\n}\n\nfunction canonical(\n vocabulary: readonly string[],\n aliases: Record<string, string> | null,\n value: string\n): string {\n const key = normalizeKey(value);\n if (aliases && aliases[key]) return aliases[key];\n return vocabulary.find((member) => normalizeKey(member) === key) ?? '';\n}\n\n/** Whether s names a status the filter understands, in any accepted form. */\nexport function validStatus(s: string): boolean {\n return canonical(STATUS_VALUES, STATUS_ALIASES, s) !== '';\n}\n\n/** Whether s names an override type the filter understands, in any accepted form. */\nexport function validDisposition(s: string): boolean {\n return canonical(DISPOSITION_VALUES, DISPOSITION_ALIASES, s) !== '';\n}\n\n/** Whether s names a severity the filter understands, in any accepted form. */\nexport function validSeverity(s: string): boolean {\n return canonical(SEVERITY_VALUES, SEVERITY_ALIASES, s) !== '';\n}\n\n/**\n * The canonical form of a filter value for the named field, or the value\n * unchanged when the field has no closed vocabulary or the value names no\n * member. Normalizing here rather than in one caller is what makes a threshold\n * rule and an `hdf query` invocation mean the same thing.\n */\nexport function normalizeFilterValue(field: string, value: string): string {\n switch (field) {\n case 'status':\n return canonical(STATUS_VALUES, STATUS_ALIASES, value) || value;\n case 'severity':\n return canonical(SEVERITY_VALUES, SEVERITY_ALIASES, value) || value;\n case 'disposition':\n return canonical(DISPOSITION_VALUES, DISPOSITION_ALIASES, value) || value;\n case 'poams':\n if (!validPoamFilter(value)) return value;\n return normalizeKey(value) === normalizeKey(POAM_VALID) ? POAM_VALID : POAM_NONE_VALID;\n default:\n return value;\n }\n}\n","// Glob matching — the TypeScript peer of hdf-engine/go/safematch.go. Kept at\n// behavioural parity with the Go matcher.\n\nconst MAX_PATTERN_LENGTH = 256;\n\nconst REGEX_SPECIAL = new Set(['.', '+', '^', '$', '(', ')', '[', ']', '{', '}', '|', '\\\\']);\n\n/**\n * globToRegex converts a glob pattern (with * and ? wildcards) to an anchored\n * regular expression, escaping every other regex metacharacter exactly once. A\n * single pass avoids re-escaping the backslash introduced by escaping an earlier\n * metacharacter (the doubled-backslash defect that made any dotted pattern match\n * nothing).\n */\nexport function globToRegex(glob: string): string {\n let result = '^';\n for (const ch of glob) {\n if (ch === '*') {\n result += '.*';\n } else if (ch === '?') {\n result += '.';\n } else if (REGEX_SPECIAL.has(ch)) {\n result += '\\\\' + ch;\n } else {\n result += ch;\n }\n }\n return result + '$';\n}\n\n/**\n * safeGlobMatch converts a glob pattern to a regex and matches case-insensitively.\n * Returns false for over-length or invalid patterns (fail-safe), mirroring the\n * Go matcher's length cap and error handling.\n */\nconst byteEncoder = new TextEncoder();\n\n/** byteLength returns the UTF-8 byte length, matching Go's len(string). */\nfunction byteLength(s: string): number {\n return byteEncoder.encode(s).length;\n}\n\nexport function safeGlobMatch(s: string, pattern: string): boolean {\n // Cap on UTF-8 byte length (matching Go's len(pattern)), and — like Go's\n // compileSafeRegex — re-cap the EXPANDED regex, so an over-length glob or a\n // small glob that expands past the limit is rejected identically in both\n // languages (not just capped on the raw glob's UTF-16 length).\n if (byteLength(pattern) > MAX_PATTERN_LENGTH) {\n return false;\n }\n const rx = globToRegex(pattern);\n if (byteLength(rx) > MAX_PATTERN_LENGTH) {\n return false;\n }\n let re: RegExp;\n try {\n re = new RegExp(rx, 'i');\n } catch {\n return false;\n }\n return re.test(s);\n}\n","/**\n * A predicate field's value set, and the normalizer that accepts the three\n * spellings a policy may use for it: a bare scalar for the common single-value\n * case, a list, and a `{not: [...]}` object for exclusion.\n *\n * Negation is PURE: `not` means \"does not match any of these\", and a requirement\n * whose field is ABSENT satisfies it. The alternative — requiring the field to\n * be present — silently weakens gates, because the requirement a gate most needs\n * to catch is usually the one nobody has touched. `{status: [failed],\n * disposition: {not: [waiver]}}` with `max: 0` must catch a failure nobody\n * adjudicated; under a presence-requiring reading that requirement is excluded\n * and the bound passes.\n *\n * Parity: Values in go/values.go.\n */\n/**\n * What a policy may write for a multi-value field: a scalar, a list, or a\n * {not: [...]} object. Normalized to Values before it reaches a matcher.\n */\nexport type PredicateValue = string | string[] | { not: string | string[] };\n\nexport interface Values {\n in: string[];\n not: string[];\n}\n\n// NOTE: there is deliberately no exported constructor for a Values here. One\n// existed and was a trap: {in: [...]} is the decoder's OUTPUT shape and is\n// refused as a policy form, so its result threw when passed back to filter().\n// TypeScript callers pass the policy spellings — a scalar, a list, or\n// {not: [...]} — and normalizeValues turns them into this. Go's In() is safe\n// because Go reaches the decoder by type rather than by normalizing a literal.\n\n/** Whether the field constrains anything at all. */\nexport function valuesActive(v: Values | undefined): boolean {\n return v !== undefined && (v.in.length > 0 || v.not.length > 0);\n}\n\n/**\n * Every value the field names, in either mode, for callers that validate the\n * vocabulary — a value inside `not` must be refused exactly as one outside it\n * is, or a typo there excludes nothing and the predicate matches everything.\n */\nexport function valuesAll(v: Values | undefined): string[] {\n return v === undefined ? [] : [...v.in, ...v.not];\n}\n\n/**\n * Applies the field's own per-value test. `test` reports whether the requirement\n * matches ONE named value; this combines those the way the vocabulary always has\n * — values within a field OR — and then applies the exclusion.\n */\nexport function valuesMatch(v: Values, test: (value: string) => boolean): boolean {\n if (v.in.length > 0 && !v.in.some(test)) return false;\n if (v.not.length > 0 && v.not.some(test)) return false;\n return true;\n}\n\n/**\n * Normalizes whatever a policy carried into a Values. Throws on a shape that is\n * none of the three, so a malformed predicate is refused rather than silently\n * asserting nothing. Parity: Values.UnmarshalYAML / UnmarshalJSON in\n * go/values.go, and the shared case table pins the accepted forms.\n */\nexport function normalizeValues(raw: unknown): Values {\n if (raw === undefined || raw === null) return { in: [], not: [] };\n if (typeof raw === 'string') return { in: [raw], not: [] };\n if (Array.isArray(raw)) {\n if (!raw.every((v) => typeof v === 'string')) {\n throw new Error('a predicate value is a value, a list, or {not: ...}');\n }\n return { in: raw as string[], not: [] };\n }\n if (typeof raw === 'object') {\n const keys = Object.keys(raw as Record<string, unknown>);\n const other = keys.find((k) => k !== 'not');\n if (other !== undefined) {\n throw new Error(`field \"${other}\" is not a known form; a predicate value is a value, a list, or {not: ...}`);\n }\n const inner = normalizeValues((raw as { not?: unknown }).not);\n if (inner.not.length > 0) throw new Error('not cannot be nested inside not');\n if (inner.in.length === 0) {\n throw new Error('not excludes nothing; a predicate that asserts nothing is refused');\n }\n return { in: [], not: inner.in };\n }\n throw new Error('a predicate value is a value, a list, or {not: ...}');\n}\n","// Requirements query engine — the TypeScript peer of hdf-engine/go/filter.go.\n// A pure filter(results, options) with no shared mutable state, kept at\n// behavioural parity with the Go implementation (see test/query.test.ts, which\n// runs both over the same fixture).\n\nimport type { HDFResults, EvaluatedRequirement } from '@mitre/hdf-schema';\nimport {\n governingOverrideIndex,\n parseTimestamp,\n extractCWEIDs,\n type StatusOverrideInput,\n} from '@mitre/hdf-utilities';\nimport { deriveSeverity } from './compliance.js';\nimport { effectiveImpactOf, overrideInputs } from './effective.js';\nimport { normalizeKey, normalizeFilterValue } from './vocabulary.js';\nimport { safeGlobMatch } from './safematch.js';\nimport { valuesActive, valuesMatch, normalizeValues, type Values, type PredicateValue } from './values.js';\n\n/**\n * FilterOptions configures a requirements query. Every filter input arrives here;\n * distinct filters combine with AND, repeated values within a filter with OR.\n * statusOf resolves a requirement's display status, injected so the engine stays\n * agnostic to the caller's status-string convention (undefined → empty status).\n */\nexport interface FilterOptions {\n status?: PredicateValue;\n severity?: PredicateValue;\n /**\n * Compares the EFFECTIVE impact — the governing non-expired impact override's\n * value, else the requirement's own.\n */\n impact?: string;\n /**\n * Compares the requirement's own impact, ignoring overrides. It exists because\n * impact resolves them: the governance policy \"an override may not move a\n * critical below 0.7\" needs both scores, and no other key reaches the\n * unadjusted one.\n */\n rawImpact?: string;\n /**\n * Compares the requirement's authoritative CVSS score, using the same\n * comparison grammar as impact. See cvssScoreOf for what \"authoritative\"\n * resolves to and how several CVSS entries collapse to one number.\n */\n cvss?: string;\n /**\n * Compares the EPSS exploit PROBABILITY (epss.score), not the percentile\n * rank. They share a 0-1 scale and mean very different things.\n */\n epss?: string;\n /**\n * CISA Known Exploited Vulnerabilities membership: 'true' for kev.inKev,\n * 'false' for everything else — including a requirement carrying no kev block\n * at all, which is not known-exploited either.\n */\n kev?: string;\n /**\n * Selects by CWE identifier, OR across values, matched numerically so CWE-79,\n * 'CWE 79' and cwe79 are one value. Reads the first-class cwe[] field ONLY and\n * never falls back to tags.cwe.\n */\n cwe?: PredicateValue;\n cci?: PredicateValue;\n nist?: PredicateValue;\n id?: string;\n tag?: PredicateValue;\n search?: string;\n baseline?: string;\n /**\n * Selects requirements by the labels of the baseline they sit in, as\n * `key:value`, OR across values, with the value globbable exactly as a tag\n * value is. Named for the baseline rather than `label` alone because there is\n * no requirement-level label, and because system documents carry component\n * labels that may one day want their own key.\n *\n * A label is a property of the BASELINE, so this is applied once per baseline\n * beside `baseline` rather than per requirement. A baseline carrying no labels\n * therefore matches nothing: an absent label is not a wildcard.\n * Parity: Options.BaselineLabel in go/filter.go.\n */\n baselineLabel?: PredicateValue;\n /**\n * The TYPE of the override that governs the requirement (waiver,\n * falsePositive, riskAdjustment, …), OR across values. The governing override\n * is the most recent non-expired one of ANY kind, so it may differ from the one\n * that set the status — see governingDisposition. Resolved rather than read\n * from the stored disposition field, which is an output cache.\n */\n disposition?: PredicateValue;\n /**\n * Remediation-plan validity: 'valid' for a requirement carrying a POA&M still\n * in force, 'none-valid' for one carrying none, an empty list, or only lapsed\n * ones. Absence and expiry are one concept on purpose.\n */\n poams?: string;\n /** Kind of the governing POA&M: remediation|mitigation|riskAcceptance|vendorDependency. */\n poamType?: PredicateValue;\n /** RFC3339 reference clock for expiry; undefined means now. */\n now?: string;\n limit?: number;\n count?: boolean;\n statusOf?: (control: EvaluatedRequirement) => string;\n}\n\n/**\n * A single query result row. baselineIndex and index are the match's position in\n * the result set (results.baselines[baselineIndex].requirements[index]) and are\n * the only unique identity a match has: baseline names repeat in shipped\n * converter output and requirement ids repeat within a baseline, so (baseline,\n * id) is not a key. Address the source requirement by position, never by name.\n */\nexport interface Match {\n id: string;\n title: string;\n status: string;\n impact: number;\n severity: string;\n baseline: string;\n baselineIndex: number;\n index: number;\n}\n\ntype FilterFunc = (control: EvaluatedRequirement, status: string, severity: string) => boolean;\n\n/**\n * filter returns the requirements across the result set's baselines that satisfy\n * options. Applies to requirement collections (results/baseline documents); the\n * calling adapter rejects document types that carry no requirements.\n */\nexport function filter(results: HDFResults, rawOptions: FilterOptions): Match[] {\n // Normalized ONCE here, so every caller — a decoded policy, the CLI, the MCP,\n // or a TypeScript consumer passing a plain array — reaches the matchers with\n // the same shape. Parity: Go reaches it by type, through Values' unmarshaller.\n const options = normalizeOptions(rawOptions);\n const filters = buildFilters(options);\n const matches: Match[] = [];\n\n for (const [baselineIndex, baseline] of (results.baselines ?? []).entries()) {\n if (options.baseline && !matchesGlob(baseline.name, options.baseline)) {\n continue;\n }\n if (!baselineLabelsMatch(baseline.labels, options.baselineLabel)) {\n continue;\n }\n for (const [index, control] of (baseline.requirements ?? []).entries()) {\n if (options.limit && options.limit > 0 && matches.length >= options.limit && !options.count) {\n return matches;\n }\n\n const status = options.statusOf ? options.statusOf(control) : '';\n // Explicit STIG severity wins; impact-derived only as a fallback — the\n // canonical rule shared with the compliance counts (deriveSeverity), so\n // query rows and compliance never disagree on a requirement's severity.\n // Effective impact for the same reason the impact filter uses it: a\n // governing riskAdjustment moves the requirement into the band it was\n // re-scored into, and filter is an override-aware surface.\n const impact = effectiveImpactOf(control, options.now);\n const severity = deriveSeverity(impact, control.severity ?? null);\n\n if (!applyFilters(control, status, severity, filters)) {\n continue;\n }\n\n matches.push({\n id: control.id,\n title: control.title ?? '',\n status,\n // The effective impact, for the same reason status carries the\n // effective status and a Match has no raw twin of either.\n impact,\n severity,\n baseline: baseline.name,\n baselineIndex,\n index,\n });\n }\n }\n return matches;\n}\n\n/** The value fields, normalized; every other option passes through unchanged. */\ntype NormalizedOptions = Omit<FilterOptions, (typeof VALUE_FIELDS)[number]> & {\n [K in (typeof VALUE_FIELDS)[number]]?: Values;\n};\n\nexport const VALUE_FIELDS = [\n 'status',\n 'severity',\n 'cwe',\n 'cci',\n 'nist',\n 'tag',\n 'baselineLabel',\n 'disposition',\n 'poamType',\n] as const;\n\nfunction normalizeOptions(options: FilterOptions): NormalizedOptions {\n const out: Record<string, unknown> = { ...options };\n for (const field of VALUE_FIELDS) {\n if (out[field] !== undefined) out[field] = normalizeValues(out[field]);\n }\n return out as NormalizedOptions;\n}\n\nfunction buildFilters(options: NormalizedOptions): FilterFunc[] {\n const filters: FilterFunc[] = [];\n\n // Compared through normalizeKey so the CLI's display spelling and the schema's\n // camelCase are one value: a filter copied from `hdf query` and a rule written\n // against the schema must select the same requirements.\n if (valuesActive(options.status)) {\n // BOTH sides go through the same alias map: the injected resolver may speak\n // the CLI's display vocabulary while the spec speaks the schema's.\n filters.push((_c, s) => {\n const actual = normalizeKey(normalizeFilterValue('status', s));\n return valuesMatch(options.status!, (want) => actual === normalizeKey(normalizeFilterValue('status', want)));\n });\n }\n\n // Normalized the same way, and through the alias map as well, so 'none' — the\n // name informational replaced in 3.7.0 — keeps selecting it on every surface,\n // not only in the CLI.\n if (valuesActive(options.severity)) {\n filters.push((_c, _s, severity) => {\n const actual = normalizeKey(normalizeFilterValue('severity', severity));\n return valuesMatch(options.severity!, (want) => actual === normalizeKey(normalizeFilterValue('severity', want)));\n });\n }\n\n // Disposition (OR across values). A requirement with no governing override\n // matches nothing, which is what makes \"waived\" and \"not waived\" opposites.\n if (valuesActive(options.disposition)) {\n filters.push((c) => {\n const governing = governingDisposition(c, options.now);\n // Nothing governing matches no VALUE, which is what makes an inclusive\n // predicate exclude it and a negation accept it — a failure nobody\n // adjudicated is correctly 'not waived'.\n const actual = normalizeKey(normalizeFilterValue('disposition', governing));\n return valuesMatch(\n options.disposition!,\n (want) => governing !== '' && actual === normalizeKey(normalizeFilterValue('disposition', want)),\n );\n });\n }\n\n if (valuesActive(options.poamType)) {\n filters.push((c) => {\n const kind = governingPoamType(c, options.now);\n return valuesMatch(options.poamType!, (want) => kind !== '' && normalizeKey(kind) === normalizeKey(want));\n });\n }\n\n // POA&M validity. An unrecognized value matches NOTHING rather than silently\n // degrading, matching the impact filter's posture — callers validate with\n // validPoamFilter and reject before filtering.\n if (options.poams) {\n const wantValid = poamFilterWantsValid(options.poams);\n filters.push((c) => wantValid !== undefined && hasValidPoam(c, options.now) === wantValid);\n }\n\n // Compared against EFFECTIVE impact, so a governing riskAdjustment is\n // honoured. Status has resolved overrides all along; an impact filter that\n // ignored a formal re-score was the same amendments-blindness in the field\n // nobody looked at.\n if (options.impact) {\n const [op, val] = parseImpactFilter(options.impact);\n filters.push((c) => compareImpact(effectiveImpactOf(c, options.now), op, val));\n }\n\n // The unadjusted twin, same grammar and same safe-degradation.\n if (options.rawImpact) {\n const [op, val] = parseImpactFilter(options.rawImpact);\n filters.push((c) => compareImpact(c.impact, op, val));\n }\n\n // The vulnerability numbers, through the SAME comparison parser — a second\n // grammar would be a second thing to learn and a second thing to get wrong. A\n // requirement carrying no such score matches no comparison on it, rather than\n // defaulting to zero and matching '<5' for the wrong reason.\n if (options.cvss) {\n const [op, val] = parseImpactFilter(options.cvss);\n filters.push((c) => {\n const score = cvssScoreOf(c);\n return score !== undefined && compareImpact(score, op, val);\n });\n }\n if (options.epss) {\n const [op, val] = parseImpactFilter(options.epss);\n filters.push((c) => c.epss != null && compareImpact(c.epss.score, op, val));\n }\n if (options.kev) {\n const want = parseKevFilter(options.kev);\n filters.push((c) => want !== undefined && inKev(c) === want);\n }\n if (valuesActive(options.cwe)) {\n filters.push((c) => {\n const carried = new Set((c.cwe ?? []).flatMap((raw) => extractCWEIDs(String(raw))));\n return valuesMatch(options.cwe!, (want) => extractCWEIDs(want).some((id) => carried.has(id)));\n });\n }\n\n if (valuesActive(options.cci)) {\n filters.push((c) => valuesMatch(options.cci!, (want) => tagContains(c.tags, 'cci', want.toUpperCase())));\n }\n\n if (valuesActive(options.nist)) {\n filters.push((c) => valuesMatch(options.nist!, (want) => tagMatchesGlob(c.tags, 'nist', want)));\n }\n\n if (options.id) {\n const id = options.id;\n // A wildcard opts into glob matching; without one this stays the exact,\n // case-sensitive lookup it has always been. Parity: go/filter.go. The id a user\n // knows is often not the id the document carries — converters mint prefixed ids\n // (Grype/CVE-...) — while `search` reaches title, description and code and so\n // also matches a CVE merely cross-referenced in another finding's prose. A glob\n // reads only the identifier, so it can be precise about which one it names.\n if (/[*?]/.test(id)) {\n filters.push(\n (c) =>\n tagMatchesGlob(c.tags, 'stig_id', id) ||\n tagMatchesGlob(c.tags, 'gid', id) ||\n tagMatchesGlob(c.tags, 'gtitle', id) ||\n matchesGlob(c.id, id),\n );\n } else {\n filters.push(\n (c) =>\n tagContains(c.tags, 'stig_id', id) ||\n tagContains(c.tags, 'gid', id) ||\n tagContains(c.tags, 'gtitle', id) ||\n c.id === id,\n );\n }\n }\n\n if (valuesActive(options.tag)) {\n filters.push((c) =>\n valuesMatch(options.tag!, (want) => {\n // A colonless value names no key, so it matches nothing rather than\n // disappearing and letting the whole document through. The CLI refuses\n // one before it reaches here; this is the safe floor for any caller\n // that does not.\n const idx = want.indexOf(':');\n return idx > 0 && tagMatchesGlob(c.tags, want.slice(0, idx), want.slice(idx + 1));\n }),\n );\n }\n\n if (options.search) {\n const search = options.search.toLowerCase();\n filters.push((c) => {\n if (c.id.toLowerCase().includes(search)) return true;\n if (c.title && c.title.toLowerCase().includes(search)) return true;\n for (const desc of c.descriptions ?? []) {\n if (desc.data.toLowerCase().includes(search)) return true;\n }\n return false;\n });\n }\n\n return filters;\n}\n\nfunction applyFilters(\n control: EvaluatedRequirement,\n status: string,\n severity: string,\n filters: FilterFunc[],\n): boolean {\n return filters.every((f) => f(control, status, severity));\n}\n\n// DECIMAL_FLOAT is the shared impact-filter operand grammar — a plain decimal:\n// optional sign, digits with an optional fraction (or a leading-dot fraction),\n// optional decimal exponent. It excludes the forms JS Number() accepts but that\n// make no sense as a 0.0–1.0 threshold and diverge from Go strconv.ParseFloat:\n// hex/binary/octal integers (0x1f→31, 0b101→5, 0o17→15) and Infinity. The Go\n// engine applies the identical pattern so a filter is accepted or rejected the\n// same in both languages (bead 4908.15).\nconst DECIMAL_FLOAT = /^[+-]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?$/;\n\n// parseDecimal parses a plain-decimal operand, returning null for anything\n// outside the shared grammar (including overflow to Infinity, e.g. '1e400', so\n// Go's ParseFloat ErrRange rejection is mirrored).\nfunction parseDecimal(s: string): number | null {\n if (!DECIMAL_FLOAT.test(s)) return null;\n const v = Number(s);\n return Number.isFinite(v) ? v : null;\n}\n\n// An invalid operand safe-degrades to ('=', NaN), which compareImpact treats as\n// matching NOTHING — mirroring the Go engine's `return ok && compareImpact(...)`.\n// It must never coerce to ('=', 0), which silently returns confidently-wrong\n// impact==0 rows for a typo'd or garbage filter.\nexport function parseImpactFilter(f: string): [string, number] {\n const trimmed = f.trim();\n for (const op of ['>=', '<=', '>', '<', '=']) {\n if (trimmed.startsWith(op)) {\n const v = parseDecimal(trimmed.slice(op.length).trim());\n return v === null ? ['=', NaN] : [op, v];\n }\n }\n const v = parseDecimal(trimmed);\n return v === null ? ['=', NaN] : ['=', v];\n}\n\nexport function compareImpact(impact: number, op: string, val: number): boolean {\n switch (op) {\n case '>':\n return impact > val;\n case '>=':\n return impact >= val;\n case '<':\n return impact < val;\n case '<=':\n return impact <= val;\n case '=':\n return impact === val;\n default:\n return false;\n }\n}\n\nexport function tagContains(tags: Record<string, unknown>, key: string, value: string): boolean {\n const tagVal = tags?.[key];\n if (tagVal === undefined) {\n return false;\n }\n const want = value.toLowerCase();\n if (typeof tagVal === 'string') {\n return tagVal.toLowerCase() === want;\n }\n if (Array.isArray(tagVal)) {\n return tagVal.some((item) => typeof item === 'string' && item.toLowerCase() === want);\n }\n return false;\n}\n\nexport function tagMatchesGlob(tags: Record<string, unknown>, key: string, pattern: string): boolean {\n const tagVal = tags?.[key];\n if (tagVal === undefined) {\n return false;\n }\n if (typeof tagVal === 'string') {\n return safeGlobMatch(tagVal, pattern);\n }\n if (Array.isArray(tagVal)) {\n return tagVal.some((item) => typeof item === 'string' && safeGlobMatch(item, pattern));\n }\n return false;\n}\n\n/**\n * validTag reports whether s is a tag expression at all. A value carrying no\n * colon names no key, so it can never match — and unlike the label filter, which\n * merely selected nothing, a colonless tag was DROPPED from the filter list\n * entirely, so a predicate made only of colonless values matched the whole\n * document. Refused rather than tolerated in either direction.\n * Parity: ValidTag in go/filter.go.\n */\n/**\n * validKeyValue is the one \"key:value with a non-empty key\" test behind every\n * expression the filter takes in that shape; the exported names keep the\n * vocabulary each flag advertises. Parity: validKeyValue in go/filter.go.\n */\nfunction validKeyValue(s: string): boolean {\n return s.indexOf(':') > 0;\n}\n\nexport function validTag(s: string): boolean {\n return validKeyValue(s);\n}\n\n/**\n * The KIND of the governing POA&M, or '' when the governing entry is an override\n * or nothing governs. Resolves through the same index governingDisposition uses,\n * so disposition and poamType can never name different entries.\n *\n * Reading the GOVERNING plan rather than any carried plan is the whole point: a\n * requirement carrying a lapsed remediation under a live mitigation is governed\n * by the mitigation, and matching it on 'remediation' would let a dead plan\n * answer for a live one.\n * Parity: governingPoamType in go/filter.go.\n */\nfunction governingPoamType(control: EvaluatedRequirement, now?: string): string {\n const overrides = control.statusOverrides ?? [];\n const entries = [...overrideInputs(control), ...poamInputs(control)];\n const index = governingOverrideIndex(entries, () => true, now);\n if (index < overrides.length) return '';\n return (control.poams ?? [])[index - overrides.length]?.type ?? '';\n}\n\n/**\n * validBaselineLabel reports whether s is a label expression at all. A value\n * carrying no colon names no key, so it can never match any document — the same\n * forever-green gate a misspelled status value produces, which is why it is\n * refused rather than allowed to select nothing.\n * Parity: ValidBaselineLabel in go/filter.go.\n */\nexport function validBaselineLabel(s: string): boolean {\n return validKeyValue(s);\n}\n\n/**\n * baselineLabelsMatch reports whether a baseline satisfies any of the\n * `key:value` label predicates. No predicates means every baseline qualifies;\n * otherwise one must match, so several values OR the way every other multi-value\n * filter does.\n *\n * A predicate without a colon is refused at the boundary by validBaselineLabel\n * rather than handled here, because selecting nothing and being ignored produce\n * the SAME false green under a max bound: the gate passes while the caller\n * believes a filter was applied. Reaching this function it selects nothing,\n * which is the safe half of that pair.\n * Parity: baselineLabelsMatch in go/filter.go.\n */\nexport function baselineLabelsMatch(\n labels: Record<string, string> | undefined,\n predicates: Values | undefined,\n): boolean {\n if (!valuesActive(predicates)) return true;\n return valuesMatch(predicates!, (p) => {\n const colon = p.indexOf(':');\n return colon > 0 && labelMatchesGlob(labels, p.slice(0, colon), p.slice(colon + 1));\n });\n}\n\n/**\n * labelMatchesGlob reports whether a label KEY is present and its value matches\n * the pattern. Deliberately not tagMatchesGlob: a tag value may be a list, which\n * is why that one goes through the tag helpers, while a label is exactly one\n * string by schema (`additionalProperties: {type: string}`). An absent key\n * matches nothing, including against `*` — the predicate asks about a label the\n * baseline does not carry, and there is nothing to match.\n * Parity: labelMatchesGlob in go/filter.go.\n */\nexport function labelMatchesGlob(\n labels: Record<string, string> | undefined,\n key: string,\n pattern: string,\n): boolean {\n const value = labels?.[key];\n if (value === undefined) return false;\n return safeGlobMatch(value, pattern);\n}\n\n/** matchesGlob reports whether s matches the glob pattern (case-insensitive). */\nexport function matchesGlob(s: string, pattern: string): boolean {\n return safeGlobMatch(s, pattern);\n}\n\n/**\n * The closed vocabulary the disposition filter accepts: the schema's\n * Override_Type enum. A value outside it can only ever match nothing, which\n * would report a clean run over a filter the caller believed was applied.\n * Parity: DispositionValues in go/filter.go, pinned by the shared case table.\n * Membership is not pinned to the schema: an eighth override type would be\n * silently unfilterable in both languages until someone adds it here.\n */\nexport const DISPOSITION_VALUES = [\n 'waiver',\n 'attestation',\n 'poam',\n 'inherited',\n 'falsePositive',\n 'riskAdjustment',\n 'operationalRequirement',\n] as const;\n\n/**\n * The closed vocabulary the poamType filter accepts: the schema's POA&M type\n * enum. Deliberately NOT merged into DISPOSITION_VALUES — disposition answers\n * which Override_Type governs, and a plan's kind is not an override type.\n * Parity: PoamTypeValues in go/filter.go, pinned by the shared case table.\n */\nexport const POAM_TYPE_VALUES = ['remediation', 'mitigation', 'riskAcceptance', 'vendorDependency'] as const;\n\n/**\n * Reports whether s names a POA&M kind. A value outside the vocabulary can only\n * ever match nothing, so callers refuse it rather than letting it read as\n * \"asked and found none\".\n * Parity: ValidPoamType in go/filter.go.\n */\nexport function validPoamType(s: string): boolean {\n return POAM_TYPE_VALUES.some((v) => normalizeKey(v) === normalizeKey(s));\n}\n\n/**\n * Reports whether s names an override type. Callers validate with this and\n * reject, rather than letting a typo match nothing and pass — the same contract\n * validPoamFilter provides for the other amendment filter.\n */\n// Re-exported from vocabulary.ts, where all four validators share one canonical()\n// rather than this one inferring \"is an alias\" from \"the normalizer changed it\".\nexport { validDisposition } from './vocabulary.js';\n\n/**\n * The two values the poams filter accepts. 'none-valid' covers a requirement\n * with no POA&M, with an empty list, and with only lapsed ones: a plan that has\n * expired is not a plan, and splitting the two cases would create a value whose\n * only use is to be chosen by mistake.\n */\nexport const POAM_VALID = 'valid';\nexport const POAM_NONE_VALID = 'none-valid';\n\n/**\n * Reports whether s is a POA&M validity value the filter understands. Callers\n * validate with this and reject, rather than letting an unrecognized value match\n * nothing and pass.\n */\nexport function validPoamFilter(s: string): boolean {\n return poamFilterWantsValid(s) !== undefined;\n}\n\nfunction poamFilterWantsValid(s: string): boolean | undefined {\n switch (s.trim().toLowerCase()) {\n case POAM_VALID:\n return true;\n case POAM_NONE_VALID:\n return false;\n default:\n return undefined;\n }\n}\n\n/**\n * The type of the override that governs the requirement, or '' when none does:\n * the most recently applied non-expired override, whatever it carries. That is\n * the schema's own definition, and the rule hdf-diff has always used to compute\n * the effective checksum.\n *\n * Eligibility is deliberately unfiltered here, unlike the status and impact\n * ladders. Requiring a status — as this did — meant an override carrying only an\n * impact governed nothing, so `--disposition riskAdjustment` could not match the\n * shape a riskAdjustment normally has. The cost is that disposition may name a\n * different override than the one that decided the status, which is what\n * per-field eligibility means rather than a contradiction.\n */\nfunction governingDisposition(control: EvaluatedRequirement, now?: string): string {\n // Overrides and POA&Ms are ONE ordered set, not two tiers: the schema defines\n // disposition as 'the most recent non-expired override or POAM governing this\n // requirement'. Both carry appliedAt and expiresAt with the same meaning, so\n // the existing resolver decides between them without inventing a comparison.\n // Parity: governingDisposition in go/filter.go.\n const overrides = control.statusOverrides ?? [];\n const entries = [...overrideInputs(control), ...poamInputs(control)];\n\n const index = governingOverrideIndex(entries, () => true, now);\n if (index < 0) return '';\n if (index < overrides.length) return overrides[index]?.type ?? '';\n // A POA&M's own kind — remediation, mitigation, riskAcceptance,\n // vendorDependency — is not a member of Override_Type, which is what\n // disposition is typed as, so every governing POA&M reports the flat 'poam'.\n return 'poam';\n}\n\n/**\n * Projects POA&Ms onto the shape the override resolver compares, carrying no\n * status or impact because a POA&M changes neither: it tracks the work being\n * done about a failure rather than adjudicating it.\n * Parity: poamInputs in go/filter.go.\n */\nfunction poamInputs(control: EvaluatedRequirement): StatusOverrideInput[] {\n return (control.poams ?? []).map((p) => ({\n appliedAt: new Date(p.appliedAt).toISOString(),\n expiresAt: new Date(p.expiresAt).toISOString(),\n }));\n}\n\n/**\n * Whether the requirement carries a POA&M still in force. expiresAt is required\n * by the schema, so a POA&M always has a deadline to judge; one exactly at the\n * reference instant has passed, matching how an override's expiry is judged.\n */\n// Note the inverted zero: hdfutil treats an override with no expiresAt as never\n// expiring, while a POA&M without a deadline is treated as already lapsed. The\n// schema requires poams[].expiresAt so it should not arise, but the two\n// same-shaped fields mean opposite things when empty.\nfunction hasValidPoam(control: EvaluatedRequirement, now?: string): boolean {\n // parseTimestamp returns null on an unparseable value; falling back to the\n // wall clock there is wrong in the other direction, so an unusable reference\n // is treated as no reference and the caller's own validation catches it.\n const parsed = now ? parseTimestamp(now) : null;\n const ref = parsed ? parsed.getTime() : Date.now();\n // A poam-typed statusOverride IS a filed plan, and it is the only form the\n // toolchain actually produces: `hdf amend apply` writes statusOverrides[], no\n // importer emits poams[], and no committed fixture carries one. Reading only\n // poams[] made this predicate dead — \"every failure has a current plan\" could\n // never pass however many POA&Ms were filed.\n //\n // \"Carries\" is not the question disposition answers: disposition names the\n // GOVERNING adjudication, so a newer override outranks an older plan without\n // cancelling it and the two can disagree. Parity: go/filter.go hasValidPoam.\n const overridePlan = (control.statusOverrides ?? []).some(\n (o) => o.type === 'poam' && new Date(o.expiresAt).getTime() > ref\n );\n return overridePlan || (control.poams ?? []).some((poam) => new Date(poam.expiresAt).getTime() > ref);\n}\n\n/**\n * The requirement's authoritative CVSS score, or undefined when it carries none.\n *\n * Two decisions live here. An entry's score is its computedScore when the\n * producer supplied one, else its baseScore: the schema calls computedScore \"the\n * score consumers should treat as authoritative for risk decisions when\n * present\", and converters populate it: nessus-to-hdf writes a requirement-level\n * computedScore when it has the metrics to recompute one, and hdf-to-csv already\n * resolves computedScore-else-baseScore for its own column, so a gate reading\n * baseScore alone would disagree with both. It does NOT reach\n * `hdf enrich --recompute-cvss`, which writes its recomputed score into a\n * riskAdjustment OVERRIDE's cvss block rather than the requirement's own cvss[].\n * And a\n * requirement may carry one entry per CVE, resolving to the HIGHEST of them: a\n * finding matching several CVEs is as dangerous as its worst.\n *\n * Parity: cvssScoreOf in go/filter.go.\n */\nexport function cvssScoreOf(control: EvaluatedRequirement): number | undefined {\n let best: number | undefined;\n for (const entry of control.cvss ?? []) {\n const score = entry.computedScore ?? entry.baseScore;\n if (typeof score === 'number' && (best === undefined || score > best)) best = score;\n }\n return best;\n}\n\n/**\n * CISA Known Exploited Vulnerabilities membership. An absent kev block reads as\n * false: a requirement nobody checked against the catalog is not\n * known-exploited, and treating absence as unknown would leave 'kev: false'\n * unable to express \"everything CISA does not list\".\n */\nfunction inKev(control: EvaluatedRequirement): boolean {\n return control.kev?.inKev === true;\n}\n\n/** Accepts only 'true' and 'false'; anything else yields undefined. */\nfunction parseKevFilter(s: string): boolean | undefined {\n switch (s.trim().toLowerCase()) {\n case 'true':\n return true;\n case 'false':\n return false;\n default:\n return undefined;\n }\n}\n\n/**\n * Whether a kev filter value is one this engine understands, for callers to\n * reject up front rather than matching nothing.\n */\nexport function validKevFilter(s: string): boolean {\n return parseKevFilter(s) !== undefined;\n}\n","// Threshold rules — the TypeScript peer of hdf-engine/go/rules.go. A rule is a\n// filter predicate plus a bound on how many requirements may match it, for the\n// policies the fixed status × severity grid cannot express. Kept at behavioural\n// parity with the Go implementation by the shared case table both suites read\n// (testdata/threshold-rule-cases.json).\n\nimport type { HDFResults, EvaluatedRequirement } from '@mitre/hdf-schema';\nimport { filter, type FilterOptions } from './query.js';\nimport type { Violation } from './compliance.js';\nimport { normalizeValues, type PredicateValue } from './values.js';\nimport {\n validateGrid,\n type ThresholdConfig,\n type StatusCounts,\n type ControlIDMapping,\n} from './compliance.js';\n\n/**\n * The predicate surface, in one place. Go maps these onto the filter explicitly\n * while TypeScript spreads them, so a field known to one language and not the\n * other is silently inert on one side; the shared case table pins this list, and\n * the assertion below stops the interface drifting away from it.\n */\nexport const PREDICATE_FIELDS = [\n 'status',\n 'severity',\n 'impact',\n 'rawImpact',\n 'cvss',\n 'epss',\n 'kev',\n 'cwe',\n 'cci',\n 'nist',\n 'id',\n 'tag',\n 'search',\n 'baseline',\n 'baselineLabel',\n 'disposition',\n 'poamType',\n 'poams',\n] as const;\n\n/**\n * The vocabulary a rule may name. It is deliberately the filter engine's own\n * vocabulary rather than a second one: a rule and an `hdf query` invocation then\n * mean the same thing. Values within a field OR; fields AND.\n */\nexport interface RulePredicate {\n status?: PredicateValue;\n severity?: PredicateValue;\n impact?: string;\n rawImpact?: string;\n cvss?: string;\n epss?: string;\n kev?: string;\n cwe?: PredicateValue;\n cci?: PredicateValue;\n nist?: PredicateValue;\n id?: string;\n tag?: PredicateValue;\n search?: string;\n baseline?: string;\n /**\n * Selects by the labels of the baseline a requirement sits in, which is what\n * makes 'nothing fails in anything labelled environment=production'\n * expressible as a policy rather than only as a query.\n */\n baselineLabel?: PredicateValue;\n disposition?: PredicateValue;\n /**\n * The KIND of the governing POA&M, which disposition collapses to the flat\n * 'poam' because it is typed Override_Type and a plan's kind is not one.\n */\n poamType?: PredicateValue;\n poams?: string;\n}\n\n/**\n * A policy the grid cannot express. Two decisions, recorded because a policy\n * author will otherwise assume one of them: a rule bounds a COUNT and not a\n * percentage — the grid's compliance min/max remains the only percentage bound,\n * and extending rules to percentages is deferred rather than excluded — and a\n * rule evaluates over the WHOLE document, not per baseline. A policy that wants\n * one baseline says so with the baseline predicate.\n *\n * `name` is optional and exists for the\n * violation message; a rule without one is identified by its predicate, which is\n * the only other handle a reader has.\n */\nexport interface ThresholdRule {\n name?: string;\n where: RulePredicate;\n min?: number;\n max?: number;\n}\n\n/**\n * What rule evaluation needs beyond the document: the reference clock for\n * expiry, and the status resolver. statusOf is injected rather than assumed so a\n * rule and the grid's counts cannot disagree about what 'failed' means on the\n * same document.\n */\nexport interface RuleOptions {\n now?: string;\n statusOf?: (control: EvaluatedRequirement) => string;\n}\n\n/**\n * Maps a predicate onto the engine filter. Every field is a pass-through: the\n * point of reusing the vocabulary is that there is nothing to translate, and a\n * new filter field becomes a rule field by adding it here.\n */\nfunction filterOptions(where: RulePredicate, options: RuleOptions): FilterOptions {\n return {\n ...where,\n now: options.now,\n // count so a limit can never truncate the population a bound is judged\n // against — a rule counts matches, it does not list them.\n count: true,\n statusOf: options.statusOf,\n };\n}\n\n/**\n * Renders a predicate for a violation message, fields sorted so the same rule\n * always reads the same way. Values within a field join with '|', which is what\n * they mean. Parity: describe() in go/rules.go.\n */\nfunction describe(where: RulePredicate): string {\n const parts: string[] = [];\n for (const [key, value] of Object.entries(where)) {\n if (value === undefined || value === null || value === '') continue;\n if (typeof value === 'string') {\n // A scalar is the one-element list, and reads as one.\n parts.push(`${key}: ${value}`);\n continue;\n }\n if (Array.isArray(value)) {\n if (value.length > 0) parts.push(`${key}: ${value.join('|')}`);\n continue;\n }\n // A negated field renders as \"not X|Y\" so an unnamed rule's identity says\n // which way round its predicate ran — without this it rendered\n // \"[object Object]\". Parity: add() in go/rules.go.\n const v = normalizeValues(value);\n if (v.in.length > 0) parts.push(`${key}: ${v.in.join('|')}`);\n if (v.not.length > 0) parts.push(`${key}: not ${v.not.join('|')}`);\n }\n parts.sort();\n return `{${parts.join(', ')}}`;\n}\n\nfunction label(rule: ThresholdRule): string {\n return rule.name && rule.name !== '' ? rule.name : `rule ${describe(rule.where)}`;\n}\n\n/**\n * Applies every rule to the document and returns one violation per breached\n * bound. Evaluation is filter → count → compare, calling the engine's own filter\n * rather than a second matcher.\n */\nexport function evaluateRules(\n config: ThresholdConfig,\n results: HDFResults,\n options: RuleOptions = {}\n): Violation[] {\n const violations: Violation[] = [];\n for (const rule of config.rules ?? []) {\n // The matches, not just their count: naming which requirements broke a gate\n // is the difference between a red check a reader can act on and one that\n // sends them to an artifact and a script. This filter already ran.\n const matches = filter(results, filterOptions(rule.where, options));\n const matched = matches.length;\n if (rule.max !== undefined && matched > rule.max) {\n violations.push({ message: `${label(rule)}: ${matched} matched, maximum ${rule.max}`, findings: matches });\n }\n if (rule.min !== undefined && matched < rule.min) {\n // A minimum is breached by what is ABSENT, so the matches are the\n // requirements that DID qualify — fewer than required. Naming them still\n // says what the gate found rather than what it wanted.\n violations.push({ message: `${label(rule)}: ${matched} matched, minimum ${rule.min}`, findings: matches });\n }\n }\n return violations;\n}\n\n/**\n * Everything an evaluation needs. A shape rather than a parameter list because\n * rules made the list long enough that a caller could transpose two arguments of\n * the same type without the compiler noticing. Parity: ThresholdInput in\n * go/rules.go.\n */\nexport interface ThresholdInput {\n results: HDFResults;\n counts: StatusCounts;\n compliance: number;\n controlMap: ControlIDMapping[];\n now?: string;\n statusOf?: (control: EvaluatedRequirement) => string;\n}\n\n/**\n * Applies a whole policy — the grid and the rules — and returns every violation.\n * This is the entry point a surface should call: validateThresholds evaluates the\n * grid alone and refuses a config carrying rules, so a caller cannot\n * half-implement a policy without being told. Parity: Evaluate in go/rules.go.\n */\nexport function evaluate(config: ThresholdConfig, input: ThresholdInput): Violation[] {\n const violations = validateGrid(config, input.counts, input.compliance, input.controlMap);\n return violations.concat(\n evaluateRules(config, input.results, { now: input.now, statusOf: input.statusOf })\n );\n}\n\n// Compile-time guard: a field added to RulePredicate and not to PREDICATE_FIELDS\n// would reach the TypeScript filter through the spread and never reach Go, which\n// is the drift the shared field list exists to prevent. This fails the build\n// rather than waiting for a test nobody wrote.\ntype UnlistedPredicateField = Exclude<keyof RulePredicate, (typeof PREDICATE_FIELDS)[number]>;\nconst _everyPredicateFieldIsListed: UnlistedPredicateField extends never ? true : never = true;\nvoid _everyPredicateFieldIsListed;\n","// Document loader engine core — the TypeScript peer of hdf-engine/go/loader.go,\n// kept at behavioural parity (see loader.test.ts + the Go parity test, which\n// run both over the same fixtures). Pure and schema-typed: size-guard first,\n// wire-format + document-type detection, then the canonical parse for the\n// results/baseline types. No cache, no degraded envelope — those are MCP\n// concerns layered on top in hdf-cli/internal/mcp/loader.\n\nimport type { HDFResults, HDFBaseline } from '@mitre/hdf-schema';\nimport { validateInputSize } from '@mitre/hdf-utilities';\nimport { parseResults, parseBaseline } from '@mitre/hdf-parsers';\nimport { detect, type HdfDocType } from './detect.js';\n\n/** Wire encoding of loader input (parity with Go InputFormat). */\nexport type InputFormat = 'json' | 'ndjson';\n\nexport interface LoadResult {\n format: InputFormat;\n docType: HdfDocType;\n results?: HDFResults;\n baseline?: HDFBaseline;\n /** Non-empty when detected as results/baseline but the parse/validate failed. */\n parseError?: string;\n valid: boolean;\n}\n\n/**\n * load is the schema-typed loader core. In order: validateInputSize (FIRST,\n * before any parse; maxSize <= 0 uses the default), wire-format detection\n * (JSON vs NDJSON), document-type detection (detect), then the canonical\n * hdf-parsers parse for the results and baseline types. Other types are\n * detected but not parsed here.\n */\nexport function load(input: string | Uint8Array, maxSize = 0): LoadResult {\n validateInputSize(input, maxSize); // first op — throws on oversize\n\n const text = typeof input === 'string' ? input : new TextDecoder().decode(input);\n const result: LoadResult = {\n format: detectFormat(text),\n docType: detect(text),\n valid: false,\n };\n\n if (result.docType === 'results') {\n const r = parseResults(text);\n if (r.success && r.data) {\n result.results = r.data;\n result.valid = true;\n } else {\n result.parseError = r.error;\n }\n } else if (result.docType === 'baseline') {\n const r = parseBaseline(text);\n if (r.success && r.data) {\n result.baseline = r.data;\n result.valid = true;\n } else {\n result.parseError = r.error;\n }\n }\n\n return result;\n}\n\n/**\n * detectFormat classifies input as a single JSON document or newline-delimited\n * JSON, consistent with the Go core: NDJSON is two or more non-blank lines that\n * each independently parse as a complete JSON value. A pretty-printed single\n * object stays 'json' (its first line is not itself a complete JSON value).\n */\nexport function detectFormat(text: string): InputFormat {\n const lines = text.split('\\n').filter((l) => l.trim() !== '');\n const [first, second] = lines;\n if (first === undefined || second === undefined) {\n return 'json';\n }\n if (isCompleteJSON(first) && isCompleteJSON(second)) {\n return 'ndjson';\n }\n return 'json';\n}\n\n// isCompleteJSON reports whether s is a single complete JSON value with no\n// trailing content — the per-line test the NDJSON classifier applies. JSON.parse\n// already rejects trailing garbage, so a successful parse is sufficient.\nfunction isCompleteJSON(s: string): boolean {\n try {\n JSON.parse(s);\n return true;\n } catch {\n return false;\n }\n}\n","// Evidence-verify engine — the TypeScript peer of hdf-engine/go/evidence.go.\n// Pure, filesystem-agnostic core of `hdf evidence info --verify` (ADR-0007 §11):\n// content-checksum classification and plan/results completeness. All filesystem\n// IO and path confinement stay in the caller, injected as a FetchFn. Kept at\n// behavioural parity with the Go implementation (see test/evidence.test.ts,\n// which runs both over the same fixtures).\n\nimport { blake3 } from '@noble/hashes/blake3.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport { generateHash, type HashAlgorithm } from '@mitre/hdf-utilities';\nimport { agentOverrideCount } from './compliance.js';\nimport type { HDFResults } from '@mitre/hdf-schema';\n\n/** Classifies a single content entry's checksum verification. 'unsupported' is a\n * recorded algorithm this build cannot compute — deliberately NOT 'error', since the\n * bytes may be intact and the package valid. Every consumer switching on this type\n * must handle it; leaving it to a default reports an unverified entry as verified. */\nexport type ChecksumStatus = 'match' | 'mismatch' | 'skipped' | 'error' | 'unsupported';\n\n/** One content entry of an evidence package: a referenced document and its\n * recorded checksum ('' when the entry carries none). */\nexport interface EvidenceContent {\n uri: string;\n type: string;\n checksum: string;\n /** The algorithm the package recorded, '' when it stated none. Optional so an\n * omitted field behaves exactly like Go's zero-valued string: absent means\n * sha256 at verification time. The sha256 default belongs to verification, not\n * to the parse, so an unstated algorithm is not invented here. */\n checksumAlgorithm?: string;\n /** Distinguishes an entry carrying no checksum object from one carrying a\n * checksum whose value is empty. `checksum` alone conflates them, and the\n * difference matters: a recorded-but-blank value is unverifiable, whereas an\n * absent checksum is simply not a claim. Optional so an omitted field behaves\n * like Go's zero-valued bool. */\n checksumRecorded?: boolean;\n /** Set for an `externalEvidence[]` entry and absent for a `contents[]` one;\n * `type` is the reverse. The schema gives the two arrays different fields — a\n * content entry records a Content_Type, an external entry records a native\n * Native_Format — so they are kept apart rather than collapsed into `type`,\n * which would put 'raw-log' in a field whose vocabulary is the seven document\n * types. Optional so an omitted field behaves like Go's zero-valued string. */\n format?: string;\n}\n\n/** The verification outcome for one content entry. */\nexport interface ChecksumResult {\n uri: string;\n type: string;\n /** Mirrors `EvidenceContent.format`: set for an `externalEvidence[]` entry,\n * absent for a `contents[]` one, so a caller can report what an artifact is\n * without reading `type`'s Content_Type vocabulary onto it. */\n format?: string;\n /** The algorithm this entry's checksum is recorded under, with an unstated one\n * reported as the sha256 it defaults to. Absent for a skipped entry — one with no\n * checksum VALUE to verify, whether it carries no checksum at all or one whose\n * value is blank (Checksum.value has no minLength, so a blank value is\n * schema-valid and may still name an algorithm). Nothing was hashed in either\n * case, and naming an algorithm would imply a computation that never ran. */\n algorithm?: string;\n status: ChecksumStatus;\n expected?: string;\n actual?: string;\n error?: string;\n}\n\n/** Reports which planned baselines are covered by results. */\nexport interface CompletenessResult {\n planned: string[];\n covered: string[];\n missing: string[];\n complete: boolean;\n}\n\n/** Resolves a content URI to its bytes. The caller owns path confinement\n * (HDF_MCP_ROOT for the MCP, the package directory for the CLI). Throws when the\n * uri cannot be read. */\nexport type FetchFn = (uri: string) => Uint8Array;\n\ntype RawObject = Record<string, unknown>;\n\n/** Go decodes into a typed struct, so a JSON `null` document leaves zero values\n * while a wrong-typed one is a decode error. These three helpers give the TS\n * peer the same split instead of asserting a shape onto untrusted input. */\nfunction parseDocument(text: string, what: string): RawObject {\n const doc: unknown = JSON.parse(text);\n if (doc === null) return {};\n if (typeof doc !== 'object' || Array.isArray(doc)) {\n throw new Error(`parse ${what}: cannot unmarshal ${describe(doc)} into an object`);\n }\n return doc as RawObject;\n}\n\nfunction objectArray(value: unknown, what: string, field: string): RawObject[] {\n if (value === undefined || value === null) return [];\n if (!Array.isArray(value)) {\n throw new Error(`parse ${what}: cannot unmarshal ${describe(value)} into ${field}`);\n }\n return value.map((entry: unknown) => {\n if (entry === null) return {};\n if (typeof entry !== 'object' || Array.isArray(entry)) {\n throw new Error(`parse ${what}: cannot unmarshal ${describe(entry)} into a ${field} entry`);\n }\n return entry as RawObject;\n });\n}\n\nfunction str(value: unknown): string {\n return typeof value === 'string' ? value : '';\n}\n\nfunction describe(value: unknown): string {\n return Array.isArray(value) ? 'array' : value === null ? 'null' : typeof value;\n}\n\n/** Extracts the planRef and content entries from an evidence-package document. */\nexport function parseEvidencePackage(pkg: string): { planRef: string; contents: EvidenceContent[] } {\n const doc = parseDocument(pkg, 'evidence package');\n const contents: EvidenceContent[] = objectArray(doc.contents, 'evidence package', 'contents').map((c) => {\n const checksum = c.checksum;\n const isObject = typeof checksum === 'object' && checksum !== null;\n return {\n uri: str(c.uri),\n type: str(c.type),\n checksum: isObject ? str((checksum as RawObject).value) : '',\n checksumAlgorithm: isObject ? str((checksum as RawObject).algorithm) : '',\n checksumRecorded: isObject,\n };\n });\n return { planRef: str(doc.planRef), contents };\n}\n\n/** Returns the `externalEvidence[]` entries as the same shape `contents[]` parses\n * to, so ONE verification pass covers both arrays. It exists because verify\n * examined `contents[]` only, and a wrong checksum in the other array passed at\n * exit 0 while bundle refused the same package — the two commands disagreeing\n * about one document.\n *\n * Additive on purpose: `verifyChecksums` is reused unchanged on what this returns,\n * so the hashing has one implementation rather than one per array. */\nexport function parseExternalEvidence(pkg: string): EvidenceContent[] {\n const doc = parseDocument(pkg, 'evidence package');\n return objectArray(doc.externalEvidence, 'evidence package', 'externalEvidence').map((e) => {\n const checksum = e.checksum;\n const isObject = typeof checksum === 'object' && checksum !== null;\n return {\n uri: str(e.uri),\n type: '',\n format: str(e.format),\n checksum: isObject ? str((checksum as RawObject).value) : '',\n checksumAlgorithm: isObject ? str((checksum as RawObject).algorithm) : '',\n checksumRecorded: isObject,\n };\n });\n}\n\n/** Verifies each content entry against fetch(uri) using the algorithm the entry\n * recorded, preserving entry order. No checksum → skipped; an algorithm this\n * build cannot compute → unsupported, never mismatch (that would say their evidence\n * changed when it did not) and never error, since the bytes may be intact; a fetch throw → error;\n * hash mismatch → mismatch (carrying expected+actual).\n *\n * Asynchronous because the SHA family is hashed through Web Crypto, which is what lets\n * this package bundle for the browser. */\nexport async function verifyChecksums(contents: EvidenceContent[], fetch: FetchFn): Promise<ChecksumResult[]> {\n const results: ChecksumResult[] = [];\n // One entry at a time, so only one fetched document is held in memory.\n for (const c of contents) {\n results.push(await verifyChecksum(c, fetch));\n }\n return results;\n}\n\nasync function verifyChecksum(c: EvidenceContent, fetch: FetchFn): Promise<ChecksumResult> {\n const r: ChecksumResult = { uri: c.uri, type: c.type, status: 'skipped' };\n if (c.format !== undefined && c.format !== '') {\n r.format = c.format;\n }\n if (c.checksum === '') {\n return r;\n }\n r.algorithm = effectiveAlgorithm(c.checksumAlgorithm);\n // The algorithm is checked before any IO: whether this build can compute it\n // is a property of the package, not of the filesystem.\n if (!supportedAlgorithm(c.checksumAlgorithm)) {\n return { ...r, status: 'unsupported', error: unsupportedAlgorithmMessage(c.checksumAlgorithm) };\n }\n let data: Uint8Array;\n try {\n data = fetch(c.uri);\n } catch (e) {\n return { ...r, status: 'error', error: e instanceof Error ? e.message : String(e) };\n }\n const actual = await checksumHex(c.checksumAlgorithm, data);\n if (actual === c.checksum) {\n return { ...r, status: 'match' };\n }\n return { ...r, status: 'mismatch', expected: c.checksum, actual };\n}\n\n/** Extracts assessment baselineRefs from a plan document, deduped in first-seen\n * order. */\nexport function plannedBaselineRefs(plan: string): string[] {\n const doc = parseDocument(plan, 'plan');\n const refs = objectArray(doc.assessments, 'plan', 'assessments')\n .map((a) => str(a.baselineRef))\n .filter((s) => s !== '');\n return dedupe(refs);\n}\n\n/** Extracts baseline names from a results document, deduped in first-seen order. */\nexport function coveredBaselineNames(results: string): string[] {\n const doc = parseDocument(results, 'results');\n const names = objectArray(doc.baselines, 'results', 'baselines')\n .map((b) => str(b.name))\n .filter((s) => s !== '');\n return dedupe(names);\n}\n\n/** Concatenates the covered baseline names of every hdf-results document the\n * package references, in entry order. An entry that cannot be fetched or parsed\n * is skipped: checksum verification is what reports a read failure, and a\n * partial coverage list is what the completeness diff needs. */\nexport function coveredBaselinesInPackage(contents: EvidenceContent[], fetch: FetchFn): string[] {\n const covered: string[] = [];\n forEachResultsDocument(contents, fetch, (text) => {\n try {\n covered.push(...coveredBaselineNames(text));\n } catch {\n return;\n }\n });\n return covered;\n}\n\n/** Sums the agent-attributed override count across every hdf-results document\n * the package references. Unreadable or unparseable entries are skipped. */\nexport function agentOverridesInPackage(contents: EvidenceContent[], fetch: FetchFn): number {\n let total = 0;\n forEachResultsDocument(contents, fetch, (text) => {\n try {\n total += agentOverrideCount(JSON.parse(text) as HDFResults);\n } catch {\n return;\n }\n });\n return total;\n}\n\n/** Fetches each referenced hdf-results document in entry order, skipping\n * entries that carry no uri or cannot be read. */\nfunction forEachResultsDocument(\n contents: EvidenceContent[],\n fetch: FetchFn,\n visit: (text: string) => void\n): void {\n for (const c of contents) {\n if (c.type !== 'hdf-results' || c.uri === '') {\n continue;\n }\n let data: Uint8Array;\n try {\n data = fetch(c.uri);\n } catch {\n continue;\n }\n visit(new TextDecoder().decode(data));\n }\n}\n\n/** Diffs planned baseline refs against covered baseline names. A planned ref is\n * covered when some results baseline shares its name. Missing is sorted so the\n * outcome is deterministic across languages and runs. */\nexport function completeness(planned: string[], covered: string[]): CompletenessResult {\n const coveredSet = new Set(covered);\n const missing = planned.filter((p) => !coveredSet.has(p)).sort();\n return { planned, covered, missing, complete: missing.length === 0 };\n}\n\n/** The algorithms this build can verify — every value Hash_Algorithm admits. An\n * algorithm outside the enum is refused by name rather than silently treated as\n * something else. Kept identical to Go's ChecksumHex. */\nconst SUPPORTED_ALGORITHMS = ['sha256', 'sha384', 'sha512', 'blake3'] as const;\n\n/** Names the algorithm an entry's checksum is verified under: an unstated\n * algorithm means sha256, so reporting '' would understate it. */\nfunction effectiveAlgorithm(recorded: string | undefined): string {\n return !recorded ? 'sha256' : recorded;\n}\n\nfunction supportedAlgorithm(algorithm: string | undefined): boolean {\n return !algorithm || (SUPPORTED_ALGORITHMS as readonly string[]).includes(algorithm);\n}\n\n/** Formats the algorithm list exactly as Go's ChecksumHex does, so the two languages\n * emit the SAME user-visible refusal rather than two spellings of it. */\nfunction algorithmList(): string {\n const all = SUPPORTED_ALGORITHMS as readonly string[];\n return `${all.slice(0, -1).join(', ')} and ${all[all.length - 1]}`;\n}\n\nfunction unsupportedAlgorithmMessage(algorithm: string | undefined): string {\n return `unsupported checksum algorithm \"${algorithm}\": this build computes ${algorithmList()}`;\n}\n\n/** Hashes data with the named Hash_Algorithm, hex-encoded. An empty algorithm\n * means sha256, so a package that records only a value keeps its meaning. Rejects\n * an algorithm this build cannot compute.\n *\n * The SHA family goes through the shared Web Crypto helper rather than node:crypto,\n * which is what lets this package bundle for the browser; blake3 has no Web Crypto\n * equivalent and keeps its own implementation. */\nexport async function checksumHex(algorithm: string | undefined, data: Uint8Array): Promise<string> {\n if (!supportedAlgorithm(algorithm)) {\n throw new Error(unsupportedAlgorithmMessage(algorithm));\n }\n if (algorithm === 'blake3') {\n // The 32-byte default-length digest is what the BLAKE3 reference vectors direct\n // implementations to compare.\n return bytesToHex(blake3(data));\n }\n return generateHash(data, { algorithm: (!algorithm ? 'sha256' : algorithm) as HashAlgorithm });\n}\n\n/**\n * Turns a recorded evidence reference into the path it names.\n *\n * A reference is a uri-reference — the schema says so on both `contents[].uri` and\n * `externalEvidence[].uri` — so its percent-escapes are part of the encoding, not part of\n * the name. The DECODED form is what the reference means. Before this, every consumer\n * treated the value as opaque bytes, so the legal spelling of a filename containing a\n * space failed while the illegal spelling worked: a producer following the declared\n * format wrote a package this toolchain could not read.\n *\n * ORDERING MATTERS AND THE CALLER OWNS IT. Decoding can CREATE a parent traversal —\n * `%2e%2e/x` becomes `../x` and `a%2Fb` gains a separator — so the decoded form, never the\n * raw one, is what a caller must put through its containment check.\n *\n * A value whose percent is not a valid escape cannot be decoded, and that throws rather\n * than being guessed at: falling back to the raw bytes would make resolution depend on\n * whether a filename happens to contain a `%`.\n *\n * Present here even though no TypeScript consumer resolves a reference to a filesystem\n * today — what a reference MEANS is language-independent, and a consumer that starts\n * resolving must not be free to disagree with Go. Pinned across both by\n * `testdata/reference-decode-vectors.json`.\n */\nexport function decodeReference(uri: string): string {\n if (uri === '') return '';\n // decodeURIComponent throws URIError on a malformed escape, which is the reporting\n // this contract wants; Go's url.PathUnescape returns an error for the same inputs.\n try {\n return decodeURIComponent(uri);\n } catch {\n throw new Error(`reference ${JSON.stringify(uri)} is not a valid uri-reference`);\n }\n}\n\nfunction dedupe(input: string[]): string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n for (const s of input) {\n if (!seen.has(s)) {\n seen.add(s);\n out.push(s);\n }\n }\n return out;\n}\n"],"mappings":";;;;;AAIA,MAAa,gBAAgB;;;ACgC7B,MAAa,aAAa;AAC1B,MAAa,qBAAqB;AAClC,MAAa,wBAAwB;AAErC,MAAM,uBAAuB;AAC7B,MAAM,sBAAsB;;;;;;AAO5B,SAAgB,MAAM,SAAqC;CACzD,IAAI,QAAQ,WAAW,GACrB,MAAM,IAAI,MAAM,mBAAmB;CAGrC,MAAM,YAAiC,CAAC;CACxC,MAAM,aAA0B,CAAC;CACjC,MAAM,WAA2B,CAAC;CAClC,MAAM,gCAAgB,IAAI,IAAY;CACtC,MAAM,aAAwC,CAAC;CAC/C,MAAM,kCAAkB,IAAI,IAAsB;CAClD,IAAI;CAEJ,QAAQ,SAAS,KAAK,UAAU;EAC9B,MAAM,SAAS,WAAW,IAAI,KAAK,KAAK;EACxC,MAAM,UAAU,YAAY,IAAI,GAAG;EAEnC,KAAK,MAAM,KAAK,IAAI,IAAI,aAAa,CAAC,GAAG;GACvC,MAAM,OAAO,GAAG,OAAO,GAAG,EAAE;GAC5B,MAAM,MAAM,UAAU;GACtB,MAAM,SAAiC,EAAE,GAAI,EAAE,UAAU,CAAC,EAAG;GAE7D,SAAS,UAAU,QAAQ,YAAY,QAAQ,MAAM,GAAG;GACxD,IAAI,YAAY,IACd,SAAS,UAAU,QAAQ,oBAAoB,SAAS,MAAM,GAAG;QAC5D,IAAA,iBAA0B,QAAQ;IACvC,OAAO,OAAO;IACd,SAAS,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AAI,MAAM,4BAA4B,SAAS,CAAC;CAExD,IAAI,cAAc,UAGhB,OAAO,WAAW,OAAO,IAAI,CAAC;CAEhC,OAAO,aAAa,MAAM,EAAE,WAAY,CAAC,YAAY,WAAW,UAA4B,CAAC;AAC/F;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,gBAAgB,KAAqB;CACnD,IAAI,QAAQ,IAAI,OAAO;CAGvB,IAAI;EACF,OAAO,mBAAmB,GAAG;CAC/B,QAAQ;EACN,MAAM,IAAI,MAAM,aAAa,KAAK,UAAU,GAAG,EAAE,8BAA8B;CACjF;AACF;AAEA,SAAS,OAAO,OAA2B;CACzC,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,MAAgB,CAAC;CACvB,KAAK,MAAM,KAAK,OACd,IAAI,CAAC,KAAK,IAAI,CAAC,GAAG;EAChB,KAAK,IAAI,CAAC;EACV,IAAI,KAAK,CAAC;CACZ;CAEF,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["describe"],"sources":["../src/version.ts","../src/merge.ts","../src/detect.ts","../src/effective.ts","../src/compliance.ts","../src/vocabulary.ts","../src/safematch.ts","../src/values.ts","../src/query.ts","../src/rules.ts","../src/loader.ts","../src/evidence.ts"],"sourcesContent":["// Library version, kept on the workspace lockstep with package.json (the Go\n// peer is hdf-engine/go/engine.go Version(); index.test.ts pins both to\n// package.json). It lives in its own module so engines that stamp it into\n// documents (merge.ts) can import it without a cycle through index.ts.\nexport const engineVersion = '3.8.0-next.42665732325.1';\n","// Merge engine — the TypeScript peer of hdf-engine/go/merge.go (ADR-0016).\n// Combines several results documents into one multi-baseline results document:\n// one baseline per input baseline renamed `<tool>/<original>`, per-baseline\n// provenance in labels, each input's root provenance verbatim under\n// extensions.passthrough[\"hdf-merge\"]. Union semantics — nothing deduplicated, re-keyed or\n// dropped. Deterministic for the same inputs in the same order. Kept at\n// behavioural parity with Go (see test/merge.test.ts / go/merge_test.go).\n\nimport type { HDFResults, EvaluatedBaseline, Component } from '@mitre/hdf-schema';\nimport { engineVersion } from './version.js';\n\n/** One input to merge: a results document and the name it is recorded under. */\nexport interface MergeSource {\n name: string;\n doc: HDFResults;\n}\n\nexport type MergeWarningKind = 'duplicate-baseline-name' | 'label-overwritten';\n\n/** A non-fatal condition merge reports rather than silently resolving. */\nexport interface MergeWarning {\n kind: MergeWarningKind;\n /** Merged baseline name. */\n name: string;\n /** Merged baseline positions. */\n indices: number[];\n /** Set for label warnings only: the label key that was replaced or removed. */\n label?: string;\n}\n\nexport interface MergeResult {\n results: HDFResults;\n warnings: MergeWarning[];\n}\n\n/** Provenance label keys written on every merged baseline (ADR-0016 §3). */\nexport const LABEL_TOOL = 'tool';\nexport const LABEL_TOOL_VERSION = 'toolVersion';\nexport const LABEL_SOURCE_DOCUMENT = 'sourceDocument';\n\nconst MERGE_GENERATOR_NAME = 'hdf-merge';\nconst MERGE_EXTENSION_KEY = 'hdf-merge';\n\n/**\n * merge combines the sources, in order, into one results document. Returns the\n * document and any warnings (a collision or overwrite is never an error);\n * throws only when there is nothing to merge. Inputs are not mutated.\n */\nexport function merge(sources: MergeSource[]): MergeResult {\n if (sources.length === 0) {\n throw new Error('merge: no sources');\n }\n\n const baselines: EvaluatedBaseline[] = [];\n const components: Component[] = [];\n const warnings: MergeWarning[] = [];\n const seenComponent = new Set<string>();\n const provenance: Record<string, unknown>[] = [];\n const positionsByName = new Map<string, number[]>();\n let latest: HDFResults['timestamp'];\n\n sources.forEach((src, index) => {\n const prefix = toolPrefix(src.doc, index);\n const version = toolVersion(src.doc);\n\n for (const b of src.doc.baselines ?? []) {\n const name = `${prefix}/${b.name}`;\n const pos = baselines.length;\n const labels: Record<string, string> = { ...(b.labels ?? {}) };\n\n setLabel(warnings, labels, LABEL_TOOL, prefix, name, pos);\n if (version !== '') {\n setLabel(warnings, labels, LABEL_TOOL_VERSION, version, name, pos);\n } else if (LABEL_TOOL_VERSION in labels) {\n delete labels[LABEL_TOOL_VERSION];\n warnings.push({ kind: 'label-overwritten', name, indices: [pos], label: LABEL_TOOL_VERSION });\n }\n setLabel(warnings, labels, LABEL_SOURCE_DOCUMENT, src.name, name, pos);\n\n const positions = positionsByName.get(name);\n if (positions) positions.push(pos);\n else positionsByName.set(name, [pos]);\n\n baselines.push({ ...b, name, labels });\n }\n\n for (const c of src.doc.components ?? []) {\n if (c.componentId !== undefined) {\n if (seenComponent.has(c.componentId)) continue;\n seenComponent.add(c.componentId);\n }\n components.push(c);\n }\n\n if (src.doc.timestamp !== undefined && (latest === undefined || millis(src.doc.timestamp) > millis(latest))) {\n latest = src.doc.timestamp;\n }\n\n provenance.push(sourceProvenance(index, src));\n });\n\n for (const [name, positions] of positionsByName) {\n if (positions.length > 1) {\n warnings.push({ kind: 'duplicate-baseline-name', name, indices: positions });\n }\n }\n\n // Key order is fixed so the same inputs serialize identically on every run.\n const results: HDFResults = {\n baselines,\n ...(components.length > 0 ? { components } : {}),\n extensions: {\n passthrough: { [MERGE_EXTENSION_KEY]: { version: engineVersion, sources: provenance } },\n },\n generator: { name: MERGE_GENERATOR_NAME, version: engineVersion },\n ...(latest !== undefined ? { timestamp: latest } : {}),\n };\n return { results, warnings };\n}\n\nfunction setLabel(\n warnings: MergeWarning[],\n labels: Record<string, string>,\n key: string,\n value: string,\n name: string,\n pos: number,\n): void {\n if (key in labels) {\n warnings.push({ kind: 'label-overwritten', name, indices: [pos], label: key });\n }\n labels[key] = value;\n}\n\n/** `<tool>` of a merged baseline name: tool.name → generator.name → doc<N>, lower-cased and trimmed. */\nfunction toolPrefix(doc: HDFResults, index: number): string {\n const tool = normalizeName(doc.tool?.name);\n if (tool !== '') return tool;\n const generator = normalizeName(doc.generator?.name);\n if (generator !== '') return generator;\n return `doc${index}`;\n}\n\nfunction normalizeName(s: string | undefined): string {\n return (s ?? '').trim().toLowerCase();\n}\n\n/**\n * millis reads a document timestamp for comparison. The schema type is Date,\n * but a document parsed from JSON carries the RFC 3339 string verbatim (the\n * loader does not revive dates), so both are accepted; the value itself is\n * carried through unchanged so output stays byte-faithful to the input.\n */\nfunction millis(ts: Date | string): number {\n return ts instanceof Date ? ts.getTime() : Date.parse(ts);\n}\n\nfunction toolVersion(doc: HDFResults): string {\n return (doc.tool?.version ?? '').trim();\n}\n\n/** One input's root metadata, verbatim, for extensions.passthrough[\"hdf-merge\"].sources[]. */\nfunction sourceProvenance(index: number, src: MergeSource): Record<string, unknown> {\n const entry: Record<string, unknown> = { index, name: src.name };\n if (src.doc.tool !== undefined) entry.tool = src.doc.tool;\n if (src.doc.generator !== undefined) entry.generator = src.doc.generator;\n if (src.doc.timestamp !== undefined) entry.timestamp = src.doc.timestamp;\n if (src.doc.runner !== undefined) entry.runner = src.doc.runner;\n return entry;\n}\n","// Document-type detection — the TypeScript peer of hdf-engine/go/detect.go.\n// Fingerprints an HDF document by its root keys and returns the schema type\n// string. Kept at behavioural parity with the Go implementation (see\n// go/detect_test.go and src/detect.test.ts, which assert both against the same\n// bundled schema examples).\n\n/** The eight HDF document type strings, matching validators.Type* in Go. */\nexport type HdfDocType =\n | 'results'\n | 'baseline'\n | 'system'\n | 'plan'\n | 'amendments'\n | 'evidence-package'\n | 'comparison'\n | 'requirement-change-event'\n | '';\n\n/**\n * Detect fingerprints an HDF document by its root keys and returns the schema\n * type string, or '' when the input is not a JSON object or matches no known\n * HDF document type.\n */\nexport function detect(input: string): HdfDocType {\n let parsed: unknown;\n try {\n parsed = JSON.parse(input);\n } catch {\n return '';\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n return '';\n }\n const doc = parsed as Record<string, unknown>;\n const has = (...keys: string[]): boolean =>\n keys.every((k) => Object.prototype.hasOwnProperty.call(doc, k));\n\n // Most specific first. A requirement-change-event carries the singular\n // requirementId together with the state/before/after triad — a combination\n // no other HDF document type has — so it is checked ahead of the rest.\n if (has('requirementId', 'state', 'before', 'after')) return 'requirement-change-event';\n\n if (has('contents')) return 'evidence-package';\n if (has('overrides')) return 'amendments';\n if (has('assessments')) return 'plan';\n if (has('comparisonMode')) return 'comparison';\n if (has('baselines')) return 'results';\n if (has('components')) return 'system';\n if (has('requirements')) return 'baseline';\n return '';\n}\n","// Amendments-layer resolution for schema-typed requirements: the engine's bridge\n// onto the canonical ladders in @mitre/hdf-utilities. Its own module because\n// query.ts and compliance.ts both need it and query.ts already imports\n// compliance.ts — putting it in either would either fork the mapping or make the\n// two import each other. Parity: EffectiveImpactOf and statusOverrideInputs in\n// go/filter.go.\n\nimport type { EvaluatedRequirement } from '@mitre/hdf-schema';\nimport { computeEffectiveImpact, parseTimestamp, type StatusOverrideInput, isGoZeroTime } from '@mitre/hdf-utilities';\n\n/**\n * Maps a requirement's schema overrides onto the shared helper's neutral shape,\n * whose timestamps are the RFC3339 strings the schema's Date fields came from.\n */\nexport function overrideInputs(control: EvaluatedRequirement): StatusOverrideInput[] {\n // One entry per override, slot preserved even for a member that carries\n // nothing: governingPoamType reads the index past this array's length as a\n // poam index, so dropping a slot would name the wrong poam.\n return (control.statusOverrides ?? []).map((o) => ({\n status: o?.status as string | undefined,\n appliedAt: rfc3339(o?.appliedAt),\n expiresAt: rfc3339(o?.expiresAt),\n // Carried so effective IMPACT resolves from the same overrides; eligibility\n // is per-field, so one override may govern one and not the other.\n impact: o?.impact?.value,\n }));\n}\n\n/**\n * The schema types these as Date, but a parsed document carries the RFC3339\n * strings they came from, so both shapes arrive here. A string passes through\n * for the helper's parseTimestamp to read, which keeps a zone-less value UTC\n * instead of host-local.\n *\n * Absent, unparseable, and Go's zero time all yield undefined, matching Go:\n * its timestamps are non-pointer time.Time, so an unset one round-trips as\n * 0001-01-01T00:00:00Z and decodes back to IsZero, and its ladder reads that as\n * never expiring rather than as a real instant in year 1.\n */\nfunction rfc3339(value: Date | string | undefined): string | undefined {\n if (!value) return undefined;\n const parsed = typeof value === 'string' ? parseTimestamp(value) : value;\n if (parsed === null || Number.isNaN(parsed.getTime())) return undefined;\n if (isGoZeroTime(parsed)) return undefined;\n return typeof value === 'string' ? value : parsed.toISOString();\n}\n\n/**\n * The requirement's impact after its governing non-expired impact override, else\n * its own. Computed rather than injected the way status is, because impact has\n * no competing display conventions to reconcile — the ladder in hdf-utilities is\n * canonical. An undefined reference means now.\n */\nexport function effectiveImpactOf(control: EvaluatedRequirement, now?: string): number {\n return computeEffectiveImpact({ impact: control.impact, overrides: overrideInputs(control) }, now);\n}\n","// Compliance & threshold engine — the TypeScript peer of\n// hdf-engine/go/compliance.go. Pure functions, kept at behavioural parity with\n// the Go implementation (see test/compliance.test.ts, which runs both over the\n// same fixture). Violation message formats match the Go fmt.Sprintf output.\n\nimport type { HDFResults, EvaluatedRequirement, RequirementResult, Severity } from '@mitre/hdf-schema';\nimport { worstStatus, impactToSeverity } from '@mitre/hdf-utilities';\nimport { effectiveImpactOf } from './effective.js';\nimport type { ThresholdRule } from './rules.js';\nimport type { Match } from './query.js';\n\n/** Threshold status-key constants (SAF CLI-compatible keys). */\nexport const THRESHOLD_PASSED = 'passed';\nexport const THRESHOLD_FAILED = 'failed';\nexport const THRESHOLD_SKIPPED = 'skipped';\nexport const THRESHOLD_ERROR = 'error';\nexport const THRESHOLD_NOT_APPLICABLE = 'not_applicable';\n\n/**\n * SAF CLI's name for the notApplicable bucket. It names a severity score\n * rather than the status the bucket counts, so this tool emits\n * not_applicable, but SAF's own threshold files are a supported input — so it\n * is a permanent second spelling on input, not a deprecation.\n * Parity: safNotApplicableKey in go/compliance.go.\n */\nexport const SAF_NOT_APPLICABLE_KEY = 'no_impact';\n\n/**\n * The name the informational severity bucket had before 3.7.0 renamed it.\n * Accepted on input and echoed back in violations written with it, never\n * emitted by generate.\n */\nconst LEGACY_INFORMATIONAL_KEY = 'none';\n\nexport interface SeverityCounts {\n critical: number;\n high: number;\n medium: number;\n low: number;\n /** The schema's fifth severity; also absorbs a severity that cannot be derived or is not in the enum. */\n informational: number;\n total: number;\n}\n\nexport interface StatusCounts {\n passed: SeverityCounts;\n failed: SeverityCounts;\n skipped: SeverityCounts;\n error: SeverityCounts;\n notApplicable: SeverityCounts;\n}\n\nexport interface ControlIDMapping {\n id: string;\n status: string;\n /**\n * The counting BUCKET, not the requirement's raw severity string: always one\n * of `critical`, `high`, `medium`, `low`, `informational`, having gone through\n * severityBucket. Anything else would name a bucket the counts do not have,\n * and a bound listing the control would report a mismatch against the bucket\n * that control was counted in.\n */\n severity: string;\n /**\n * The requirement's title when it has one, carried so a breached count bound\n * can name its offenders the way a rule violation does. A reader should not\n * have to know which kind of bound produced a line to know whether it will be\n * readable. Parity: ControlIDMapping.Title in go/compliance.go.\n */\n title?: string;\n}\n\nexport interface ThresholdBound {\n min?: number;\n max?: number;\n controls?: string[];\n}\n\nexport interface ThresholdSeverity {\n critical?: ThresholdBound;\n high?: ThresholdBound;\n medium?: ThresholdBound;\n low?: ThresholdBound;\n informational?: ThresholdBound;\n /** The name `informational` replaced in 3.7.0; resolved on read, never written. */\n none?: ThresholdBound;\n total?: ThresholdBound;\n}\n\nexport interface ComplianceBound {\n min?: number;\n max?: number;\n}\n\nexport interface ThresholdConfig {\n compliance?: ComplianceBound;\n passed?: ThresholdSeverity;\n failed?: ThresholdSeverity;\n skipped?: ThresholdSeverity;\n error?: ThresholdSeverity;\n notApplicable?: ThresholdSeverity;\n /** SAF CLI's spelling of notApplicable, accepted so a SAF threshold file\n * validates unchanged. Resolved by resolveSafSection; never written. */\n noImpact?: ThresholdSeverity;\n /**\n * The additive half: a filter predicate plus a bound, for the policies the\n * fixed grid above cannot express. See rules.ts.\n */\n rules?: ThresholdRule[];\n}\n\nfunction newSeverityCounts(): SeverityCounts {\n return { critical: 0, high: 0, medium: 0, low: 0, informational: 0, total: 0 };\n}\n\nfunction newStatusCounts(): StatusCounts {\n return {\n passed: newSeverityCounts(),\n failed: newSeverityCounts(),\n skipped: newSeverityCounts(),\n error: newSeverityCounts(),\n notApplicable: newSeverityCounts(),\n };\n}\n\n/**\n * overallStatus is the canonical worst-wins roll-up of a requirement's result\n * statuses, delegated to @mitre/hdf-utilities worstStatus (error > failed >\n * passed > notApplicable > notReviewed; empty → notReviewed). No local rank\n * switch — the TS peer of the Go overallStatus dedup (supersedes hdf-libs-ixhx).\n */\nexport function overallStatus(results: RequirementResult[]): string {\n return worstStatus(results.map((r) => String(r.status)));\n}\n\n/**\n * deriveSeverity determines the severity string from impact and optional explicit\n * severity, using impactToSeverity. Both paths yield a value from the schema's\n * severity enum: an explicit informational and an impact-derived one are the same\n * thing and must not land in different buckets.\n */\nexport function deriveSeverity(impact: number, severity?: Severity | null): string {\n // Presence-based, matching Go DeriveSeverity's `if severity != nil`: an explicit\n // severity — including an empty string — is returned verbatim; only a\n // null/undefined severity derives from impact. Testing truthiness here would\n // send \"\" through the impact path and diverge from Go (bead 4908.20).\n if (severity != null) {\n return String(severity);\n }\n return impactToSeverity(impact);\n}\n\n/**\n * severityBucket folds a severity string into the bucket the threshold grid\n * counts it in. The schema's four named levels pass through; informational and\n * anything outside the enum land in informational, so a malformed severity is\n * counted rather than dropped and a document still gates.\n *\n * Exported because ControlIDMapping.severity is the bucket, not the raw string:\n * a caller assembling its own control map has to apply the same rule or its\n * listing and its counts will disagree. Parity: SeverityBucket in\n * go/compliance.go.\n */\nexport function severityBucket(severity: string): string {\n switch (severity) {\n case 'critical':\n case 'high':\n case 'medium':\n case 'low':\n return severity;\n default:\n return 'informational';\n }\n}\n\nfunction statusBucket(counts: StatusCounts, status: string): SeverityCounts {\n switch (status) {\n case 'passed':\n return counts.passed;\n case 'failed':\n return counts.failed;\n case 'error':\n return counts.error;\n case 'notApplicable':\n return counts.notApplicable;\n case 'notReviewed':\n return counts.skipped;\n default:\n return counts.skipped;\n }\n}\n\nfunction addCount(counts: StatusCounts, status: string, severity: string): void {\n const sc = statusBucket(counts, status);\n sc.total++;\n switch (severityBucket(severity)) {\n case 'critical':\n sc.critical++;\n break;\n case 'high':\n sc.high++;\n break;\n case 'medium':\n sc.medium++;\n break;\n case 'low':\n sc.low++;\n break;\n default:\n sc.informational++;\n }\n}\n\n/**\n * statusToThresholdKey's inverse, for reporting a requirement found via the\n * control map. A finding line describes the REQUIREMENT, so it names the\n * requirement's own status — which is also the only vocabulary\n * `hdf query --status` accepts, so a reader can paste the value straight into a\n * query. The threshold key is a bucket name and is refused there.\n * Parity: thresholdKeyToStatus in go/compliance.go.\n */\nfunction thresholdKeyToStatus(key: string): string {\n switch (key) {\n case THRESHOLD_PASSED:\n return 'passed';\n case THRESHOLD_FAILED:\n return 'failed';\n case THRESHOLD_SKIPPED:\n return 'notReviewed';\n case THRESHOLD_ERROR:\n return 'error';\n case THRESHOLD_NOT_APPLICABLE:\n case SAF_NOT_APPLICABLE_KEY:\n return 'notApplicable';\n default:\n return key;\n }\n}\n\nfunction statusToThresholdKey(status: string): string {\n switch (status) {\n case 'passed':\n return THRESHOLD_PASSED;\n case 'failed':\n return THRESHOLD_FAILED;\n case 'notReviewed':\n return THRESHOLD_SKIPPED;\n case 'error':\n return THRESHOLD_ERROR;\n case 'notApplicable':\n return THRESHOLD_NOT_APPLICABLE;\n default:\n return THRESHOLD_SKIPPED;\n }\n}\n\n/**\n * countControlsByStatusSeverity counts requirements by overall status and severity.\n * Reads each requirement's OWN impact and raw result statuses by design: this is the\n * no-override-awareness twin of countControlsByStatus, which is its purpose.\n */\nexport function countControlsByStatusSeverity(results: HDFResults): StatusCounts {\n const counts = newStatusCounts();\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n addCount(counts, overallStatus(req.results ?? []), deriveSeverity(req.impact, reqSeverity(req)));\n }\n }\n return counts;\n}\n\n/**\n * countControlsByStatus counts requirements by a caller-resolved status — the\n * injected-resolver twin of countControlsByStatusSeverity (which counts raw\n * result statuses with no override awareness). statusOf returns each\n * requirement's status in the schema vocabulary (passed/failed/notApplicable/\n * notReviewed/error); an empty or unrecognized value counts as skipped, and an\n * absent resolver yields all-skipped. Callers build effective-status rollups\n * (e.g. compliance with and without agent-attributed overrides) without the\n * engine binding to any one status convention. Parity: go/compliance.go.\n */\nexport function countControlsByStatus(\n results: HDFResults,\n statusOf?: (req: EvaluatedRequirement) => string,\n now?: string,\n): StatusCounts {\n const counts = newStatusCounts();\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n const status = statusOf ? statusOf(req) : '';\n // Effective impact, so a governing riskAdjustment moves the requirement\n // into the band it was re-scored into. This function already resolves\n // STATUS through the injected resolver; deriving severity from the raw\n // impact counted one post-adjudication and the other pre-adjudication.\n // As of now, so an impact override judged expired by a threshold's reference\n // time stops re-scoring here too. Parity: CountControlsByStatusAt in go.\n addCount(counts, status, deriveSeverity(effectiveImpactOf(req, now), reqSeverity(req)));\n }\n }\n return counts;\n}\n\n/**\n * agentOverrideCount counts the status overrides across a result set whose\n * applied-by identity type is \"agent\" — the detective count. Deterministic\n * from_vex/system overrides are excluded so the count is a meaningful AI-scrutiny\n * signal. Parity: go/compliance.go AgentOverrideCount.\n */\nexport function agentOverrideCount(results: HDFResults): number {\n let count = 0;\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n for (const o of req.statusOverrides ?? []) {\n if (o.appliedBy?.type === 'agent') {\n count++;\n }\n }\n }\n }\n return count;\n}\n\n/** MapControlIDs builds control ID → status/severity mappings from a result set. */\nexport function mapControlIDs(results: HDFResults): ControlIDMapping[] {\n const mappings: ControlIDMapping[] = [];\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n const status = overallStatus(req.results ?? []);\n mappings.push({\n id: req.id,\n status: statusToThresholdKey(status),\n severity: severityBucket(deriveSeverity(req.impact, reqSeverity(req))),\n title: req.title ?? '',\n });\n }\n }\n return mappings;\n}\n\n/**\n * mapControlIDsByStatus builds control ID → status/severity mappings using a\n * caller-resolved status — the injected-resolver twin of mapControlIDs (which\n * maps raw result statuses). statusOf returns each requirement's status in the\n * schema vocabulary; an empty or unrecognized value maps to skipped, and an\n * absent resolver yields all-skipped. Callers build effective-status control\n * listings (the same injection pattern as countControlsByStatus). Parity:\n * go/compliance.go MapControlIDsByStatus.\n */\nexport function mapControlIDsByStatus(\n results: HDFResults,\n statusOf?: (req: EvaluatedRequirement) => string,\n now?: string,\n): ControlIDMapping[] {\n const mappings: ControlIDMapping[] = [];\n for (const baseline of results.baselines ?? []) {\n for (const req of baseline.requirements ?? []) {\n const status = statusOf ? statusOf(req) : '';\n mappings.push({\n id: req.id,\n status: statusToThresholdKey(status),\n // Effective impact, matching countControlsByStatus, so a control\n // listing and the counts it is listed alongside cannot disagree.\n severity: severityBucket(deriveSeverity(effectiveImpactOf(req, now), reqSeverity(req))),\n title: req.title ?? '',\n });\n }\n }\n return mappings;\n}\n\nfunction reqSeverity(req: EvaluatedRequirement): Severity | null {\n return (req.severity ?? null) as Severity | null;\n}\n\n/**\n * normalizeThresholdConfig folds SAF's scalar count bound into the object form a\n * bound is otherwise written in: a bare `total: 19` means EXACTLY 19, measured in\n * SAF's own validate-threshold command, which guards the scalar path with\n * `typeof !== 'object'` and then fails on inequality.\n *\n * Go reaches this rule through ThresholdBound's YAML decoding; TypeScript does no\n * YAML decoding of its own, so a consumer that parsed a SAF file itself calls\n * this before evaluating. Both are pinned by testdata/saf-bound-shorthand-cases.json.\n * The input is not mutated.\n */\nexport function normalizeThresholdConfig(config: ThresholdConfig): ThresholdConfig {\n const bound = (value: unknown): ThresholdBound | undefined => {\n if (value === undefined || value === null) return undefined;\n if (typeof value === 'number') {\n if (!Number.isInteger(value)) {\n throw new Error(`a bound written as a bare value must be a whole number of controls, got ${value}`);\n }\n return { min: value, max: value };\n }\n // Anything that is not a mapping is refused rather than passed through: a\n // \"bound\" whose min and max read undefined applies to nothing, which is the\n // silent no-op this function exists to close. An array counts — it is\n // typeof 'object' and carries no bound. Go refuses both for the same reason\n // (a non-!!int scalar, and any node that is not a mapping).\n if (typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(\n `a bound must be a whole number of controls or a min/max mapping, got ${JSON.stringify(value)}`,\n );\n }\n // Mirror Go's unmarshaller: only min, max and controls are keys, min and\n // max are whole numbers, controls a list of strings. Passing anything else\n // through typed as a bound is how {min: \"abc\"} came to compare a count\n // against text and never fire.\n for (const [key, v] of Object.entries(value as Record<string, unknown>)) {\n if (key === 'min' || key === 'max') {\n if (!Number.isInteger(v)) {\n throw new Error(`a bound's ${key} must be a whole number of controls, got ${JSON.stringify(v)}`);\n }\n } else if (key === 'controls') {\n if (!Array.isArray(v) || !v.every((x) => typeof x === 'string')) {\n throw new Error(`a bound's controls must be a list of control ids, got ${JSON.stringify(v)}`);\n }\n } else {\n throw new Error(`field ${key} is not a known bound`);\n }\n }\n return value as ThresholdBound;\n };\n\n const section = (ts: ThresholdSeverity | undefined): ThresholdSeverity | undefined => {\n if (!ts) return ts;\n const out: ThresholdSeverity = {};\n for (const key of ['critical', 'high', 'medium', 'low', 'informational', 'none', 'total'] as const) {\n const normalized = bound((ts as Record<string, unknown>)[key]);\n if (normalized !== undefined) out[key] = normalized;\n }\n return out;\n };\n\n return {\n ...config,\n passed: section(config.passed),\n failed: section(config.failed),\n skipped: section(config.skipped),\n error: section(config.error),\n notApplicable: section(config.notApplicable),\n noImpact: section(config.noImpact),\n };\n}\n\n/**\n * A count set's five status buckets, so a bucket-wise operation is written once\n * and cannot miss one. Parity: statusBuckets in go/compliance.go.\n */\nfunction statusBuckets(counts: StatusCounts): SeverityCounts[] {\n return [counts.passed, counts.failed, counts.skipped, counts.error, counts.notApplicable];\n}\n\nfunction addSeverities(dst: SeverityCounts, src: SeverityCounts): void {\n dst.critical += src.critical;\n dst.high += src.high;\n dst.medium += src.medium;\n dst.low += src.low;\n dst.informational += src.informational;\n dst.total += src.total;\n}\n\n/**\n * addCounts sums count sets bucket by bucket and severity by severity, returning\n * a new set and leaving its arguments untouched — a caller that reports the parts\n * beside the whole is summing the very objects it still has to print. Each\n * bucket's `total` is added, never recomputed from the severity fields.\n *\n * The counting functions above measure one document at a time, so a caller that\n * composes documents — the HTML report rolling baselines into a source and\n * sources into a whole, each evaluated as of its own assessment time — needs this\n * rather than a second counting pass. Combining whole DOCUMENTS is merge's job,\n * not this function's (ADR-0016 §1). Parity: AddCounts in go/compliance.go,\n * pinned by testdata/status-counts-rollup-cases.json.\n */\nexport function addCounts(...counts: StatusCounts[]): StatusCounts {\n const out = newStatusCounts();\n const dst = statusBuckets(out);\n for (const c of counts) {\n // Skipped, not treated as a zero set: these are exported helpers, so a\n // JavaScript caller reaches them without the compiler's non-null guarantee,\n // and AddCounts in go/compliance.go skips a nil the same way.\n if (c == null) continue;\n statusBuckets(c).forEach((bucket, i) => addSeverities(dst[i]!, bucket));\n }\n return out;\n}\n\n/**\n * severityTotals projects a count set onto severity alone, summing each severity\n * across every status — so `total` is the whole set's requirement count. A\n * severity breakdown answers \"how much risk is in this document\", which is a\n * question about all of it, not about its failures. Parity: SeverityTotals in\n * go/compliance.go.\n */\nexport function severityTotals(counts: StatusCounts): SeverityCounts {\n const out = newSeverityCounts();\n if (counts == null) return out;\n for (const bucket of statusBuckets(counts)) addSeverities(out, bucket);\n return out;\n}\n\n/**\n * calculateCompliance returns the compliance percentage rounded to two decimals:\n * passed / (passed + failed + skipped + error) * 100; notApplicable excluded.\n */\nexport function calculateCompliance(counts: StatusCounts): number {\n const relevant = counts.passed.total + counts.failed.total + counts.skipped.total + counts.error.total;\n if (relevant === 0) {\n return 0;\n }\n const pct = (counts.passed.total / relevant) * 100;\n return Math.round(pct * 100) / 100;\n}\n\n/** One status category of a spec after the former severity name has been resolved. */\ninterface ResolvedSection {\n name: string;\n threshold: ThresholdSeverity | undefined;\n counts: SeverityCounts;\n wroteNone: boolean;\n}\n\n/**\n * Picks the notApplicable section from whichever of the two accepted spellings\n * the author wrote, carrying that spelling into the section's name so a\n * violation names the key they will find in their own file. A spec setting both\n * is refused rather than resolved: they name one bucket, so honouring one would\n * drop a bound the author wrote.\n * Parity: resolveSAFSection in go/compliance.go.\n */\nfunction resolveSafSection(\n config: ThresholdConfig,\n counts: StatusCounts\n): { section: ResolvedSection; refusal: string } {\n const base = { counts: counts.notApplicable, wroteNone: false };\n if (config.notApplicable !== undefined && config.noImpact !== undefined) {\n return {\n section: { name: THRESHOLD_NOT_APPLICABLE, threshold: config.notApplicable, ...base },\n refusal: `both '${SAF_NOT_APPLICABLE_KEY}' and '${THRESHOLD_NOT_APPLICABLE}' are set; they name the same bucket`,\n };\n }\n if (config.noImpact !== undefined) {\n return {\n section: { name: SAF_NOT_APPLICABLE_KEY, threshold: config.noImpact, ...base },\n refusal: '',\n };\n }\n return {\n section: { name: THRESHOLD_NOT_APPLICABLE, threshold: config.notApplicable, ...base },\n refusal: '',\n };\n}\n\n/**\n * Renders a control map's status in the spelling the spec's section used, so\n * both halves of an \"expected X but found Y\" message speak one vocabulary. Only\n * the notApplicable bucket has two spellings.\n * Parity: statusKeyFor in go/compliance.go.\n */\nfunction statusKeyFor(mapped: string, sectionKey: string): string {\n if (mapped === THRESHOLD_NOT_APPLICABLE && sectionKey === SAF_NOT_APPLICABLE_KEY) {\n return SAF_NOT_APPLICABLE_KEY;\n }\n return mapped;\n}\n\n/**\n * Folds a section's pre-3.7 `none` key into `informational`, reporting whether\n * the bound was written that way so a violation can name the key the author will\n * find in their own file. A spec setting both is refused rather than resolved:\n * 3.7.0 renamed the bucket, so the two name one thing and silently honouring one\n * would drop a bound the author wrote.\n *\n * The caller's section is COPIED, never rewritten. Folding in place made the\n * name a one-shot property of the config object: the same spec reported the\n * author's key on its first validate pass and the canonical one on every pass\n * after, which is the confusion naming the author's key exists to remove.\n *\n * Parity: resolveLegacySeverity in go/compliance.go.\n */\nfunction resolveLegacySeverity(\n name: string,\n ts: ThresholdSeverity | undefined,\n): { threshold: ThresholdSeverity | undefined; wroteNone: boolean; refusal: string } {\n if (!ts?.none) {\n return { threshold: ts, wroteNone: false, refusal: '' };\n }\n if (ts.informational) {\n return {\n threshold: ts,\n wroteNone: false,\n refusal: `${name}: both 'none' and 'informational' are set; 'informational' replaced 'none' in 3.7.0 and both name the same bucket`,\n };\n }\n const resolved: ThresholdSeverity = { ...ts, informational: ts.none };\n delete resolved.none;\n return { threshold: resolved, wroteNone: true, refusal: '' };\n}\n\n/**\n * Violation is one breached bound together with the requirements that breached\n * it. `findings` is empty in two cases, for two different reasons: a compliance\n * percentage is a property of the whole document, so it has no offending\n * requirement to name; and a controls list already names its requirement in the\n * message, so repeating it would say the same thing twice.\n *\n * Findings from a RULE are the filter's own matches and carry every field. Those\n * from a COUNT bound are rebuilt from the control map, which holds only id,\n * title, status and severity — so `impact`, `baseline`, `baselineIndex` and\n * `index` are zero there rather than the requirement's real values. The CLI\n * prints none of them; a consumer serializing `findings` should not read them as\n * data. Parity: Violation in go/rules.go.\n */\nexport interface Violation {\n message: string;\n findings: Match[];\n}\n\n/** The messages of a violation list, for a caller that wants the verdict alone. */\nexport function violationMessages(violations: Violation[]): string[] {\n return violations.map((v) => v.message);\n}\n\n/**\n * validateThresholds checks all threshold bounds against observed counts and\n * compliance, returning human-readable violation messages (empty when all pass).\n */\nexport function validateThresholds(\n config: ThresholdConfig,\n counts: StatusCounts,\n compliance: number,\n controlMap: ControlIDMapping[],\n): string[] {\n const violations = violationMessages(validateGrid(config, counts, compliance, controlMap));\n // A config carrying rules cannot be judged by the grid alone. Returning the\n // grid's verdict as though the rules were satisfied would report a passing\n // gate over policy nobody applied, so the caller is told rather than quietly\n // getting half an answer. Appended, not prepended, so the two languages order\n // violations alike. Parity: ValidateThresholds in go/compliance.go.\n if (config.rules && config.rules.length > 0) {\n violations.push(ruleRefusal(config.rules.length));\n }\n return violations;\n}\n\n/**\n * ruleRefusal is what a caller is told when a policy carries rules the path it\n * used cannot evaluate. It reaches end users, so it names the spec and what to do\n * about it rather than an internal function. Parity: ruleRefusal in go/rules.go.\n */\nexport function ruleRefusal(count: number): string {\n const noun = count === 1 ? 'rule' : 'rules';\n return (\n `this spec declares ${count} ${noun}, which this evaluation path cannot apply; ` +\n `the tool must evaluate rules against the document, not against counts alone`\n );\n}\n\n/**\n * validateGrid is the status x severity half of a policy, shared by\n * validateThresholds and evaluate. Parity: validateGrid in go/compliance.go.\n */\nexport function validateGrid(\n config: ThresholdConfig,\n counts: StatusCounts,\n compliance: number,\n controlMap: ControlIDMapping[],\n): Violation[] {\n const violations: Violation[] = [];\n\n // Normalized here rather than in each caller: a consumer that parsed a SAF\n // threshold file itself hands over a scalar bound, and a bound whose min and max\n // both read undefined applies to nothing — a gate that reports green because it\n // checked nothing. Go cannot reach that state because its YAML decoding\n // normalizes on the way in; this is where TypeScript gets the same guarantee.\n config = normalizeThresholdConfig(config);\n\n // Every construction path lands here, so the former name is resolved once\n // rather than in each caller. Resolved before the compliance bounds so a\n // refusal is reported ahead of them.\n const { section: naSection, refusal: naRefusal } = resolveSafSection(config, counts);\n if (naRefusal) {\n violations.push({ message: naRefusal, findings: [] });\n }\n\n const sections: ResolvedSection[] = [\n { name: THRESHOLD_PASSED, threshold: config.passed, counts: counts.passed, wroteNone: false },\n { name: THRESHOLD_FAILED, threshold: config.failed, counts: counts.failed, wroteNone: false },\n { name: THRESHOLD_SKIPPED, threshold: config.skipped, counts: counts.skipped, wroteNone: false },\n { name: THRESHOLD_ERROR, threshold: config.error, counts: counts.error, wroteNone: false },\n naSection,\n ];\n for (const section of sections) {\n const { threshold, wroteNone, refusal } = resolveLegacySeverity(section.name, section.threshold);\n if (refusal) {\n violations.push({ message: refusal, findings: [] });\n }\n section.threshold = threshold;\n section.wroteNone = wroteNone;\n }\n\n // A requirement id names the requirement, not one finding, so several entries\n // legitimately carry it (one CVE reported against several packages). Keeping\n // every entry is what lets a named-control assertion be judged against all of\n // them rather than whichever one was indexed last.\n const actualControls = new Map<string, ControlIDMapping[]>();\n for (const m of controlMap) {\n const existing = actualControls.get(m.id);\n if (existing) {\n existing.push(m);\n } else {\n actualControls.set(m.id, [m]);\n }\n }\n\n if (config.compliance) {\n // No findings: a compliance percentage is a property of the whole document,\n // so there is no offending requirement to name.\n if (config.compliance.min !== undefined && compliance < config.compliance.min) {\n violations.push({\n message: `compliance ${compliance.toFixed(2)}% is below minimum ${config.compliance.min.toFixed(2)}%`,\n findings: [],\n });\n }\n if (config.compliance.max !== undefined && compliance > config.compliance.max) {\n violations.push({\n message: `compliance ${compliance.toFixed(2)}% exceeds maximum ${config.compliance.max.toFixed(2)}%`,\n findings: [],\n });\n }\n }\n\n for (const section of sections) {\n violations.push(\n ...checkSeverityThreshold(\n section.name,\n section.threshold,\n section.counts,\n actualControls,\n section.wroteNone,\n controlMap,\n ),\n );\n }\n\n return violations;\n}\n\nfunction checkSeverityThreshold(\n status: string,\n threshold: ThresholdSeverity | undefined,\n actual: SeverityCounts,\n actualControls: Map<string, ControlIDMapping[]>,\n wroteNone: boolean,\n controlMap: ControlIDMapping[],\n): Violation[] {\n if (!threshold) {\n return [];\n }\n // The path names the key the author wrote; the comparison below keeps the\n // canonical bucket name, because informational is where the control was\n // actually counted. Reporting `expected no_impact/none` would name a bucket\n // that does not exist.\n const pathLabel = (label: string): string =>\n wroteNone && label === 'informational' ? LEGACY_INFORMATIONAL_KEY : label;\n\n // Both sides are normalized to the schema status, because a bucket has two\n // accepted key spellings and the section carries whichever one the author\n // wrote while the control map always records the canonical one.\n const wantStatus = thresholdKeyToStatus(status);\n\n // The requirements a count bound counted, so a breached bound can name them.\n // `total` is the whole status bucket; a severity label narrows it further.\n const inBucket = (label: string): Match[] =>\n controlMap\n .filter(\n (m) =>\n thresholdKeyToStatus(m.status) === wantStatus && (label === 'total' || m.severity === label)\n )\n .map((m) => ({\n id: m.id,\n title: m.title ?? '',\n status: thresholdKeyToStatus(m.status),\n impact: 0,\n severity: m.severity,\n baseline: '',\n baselineIndex: 0,\n index: 0,\n }));\n\n const violations: Violation[] = [];\n const check = (label: string, bound: ThresholdBound | undefined, actualCount: number): void => {\n if (!bound) {\n return;\n }\n const path = `${status}.${pathLabel(label)}`;\n if (bound.min !== undefined && actualCount < bound.min) {\n violations.push({ message: `${path}: ${actualCount} is below minimum ${bound.min}`, findings: inBucket(label) });\n }\n if (bound.max !== undefined && actualCount > bound.max) {\n violations.push({ message: `${path}: ${actualCount} exceeds maximum ${bound.max}`, findings: inBucket(label) });\n }\n for (const expectedID of bound.controls ?? []) {\n // A controls list already names its requirement in the message, so these\n // carry no findings: repeating the id underneath would say it twice.\n const matches = actualControls.get(expectedID) ?? [];\n if (matches.length === 0) {\n violations.push({ message: `${path}: expected control ${expectedID} not found in results`, findings: [] });\n continue;\n }\n // Fail-closed: every entry carrying the id must satisfy the assertion. One\n // passing finding out of three must not green a gate.\n matches.forEach((ac, i) => {\n if (thresholdKeyToStatus(ac.status) === wantStatus && ac.severity === label) {\n return;\n }\n const entry = matches.length > 1 ? ` (entry ${i + 1} of ${matches.length})` : '';\n violations.push({\n message: `${path}: control ${expectedID} expected ${status}/${label} but found ${statusKeyFor(ac.status, status)}/${ac.severity}${entry}`,\n findings: [],\n });\n });\n }\n };\n\n check('critical', threshold.critical, actual.critical);\n check('high', threshold.high, actual.high);\n check('medium', threshold.medium, actual.medium);\n check('low', threshold.low, actual.low);\n check('informational', threshold.informational, actual.informational);\n check('total', threshold.total, actual.total);\n\n return violations;\n}\n","// The closed vocabularies a filter value may name, and the aliases accepted for\n// them — the TypeScript peer of hdf-engine/go/vocabulary.go, pinned at parity by\n// testdata/filter-vocabulary-cases.json, which both suites read.\n\nimport { DISPOSITION_VALUES, POAM_VALID, POAM_NONE_VALID, validPoamFilter } from './query.js';\n\n/**\n * The closed vocabulary a status filter may name: the schema's Result_Status\n * enum. It is the EFFECTIVE status that is compared — the resolver a caller\n * injects runs the override ladder first — so these are the values a requirement\n * can present after its amendments are applied.\n */\nexport const STATUS_VALUES = ['passed', 'failed', 'notApplicable', 'notReviewed', 'error'] as const;\n\n/** The schema's Severity enum, which is also what deriveSeverity returns. */\nexport const SEVERITY_VALUES = ['critical', 'high', 'medium', 'low', 'informational'] as const;\n\n/**\n * The forms a value has legitimately arrived under, enumerated rather than\n * derived. An earlier version stripped separators to fold them together, which\n * also silently repaired typos: 'wai-ver' became 'waiver'. A closed vocabulary\n * that quietly corrects a misspelling is not closed.\n *\n * The status and disposition entries are separator variants of one name. The\n * severity entry is not: 3.7.0 renamed the bucket, and 'none' is the name it had\n * before, kept so a command line or spec written against the old vocabulary\n * selects what it always did.\n */\n/**\n * `advertise` records which forms help text should TEACH, so that is a property of\n * the entry rather than of whichever string literal a command happens to hold. A\n * separator variant is part of the CLI's display vocabulary and is taught; a\n * retired name is honoured and never taught, because advertising it would hand a\n * new user the name a release replaced. Parity: FilterAlias in go/vocabulary.go.\n */\nexport interface FilterAlias {\n form: string;\n means: string;\n advertise: boolean;\n}\n\nconst STATUS_ALIAS_LIST: FilterAlias[] = [\n { form: 'not_applicable', means: 'notApplicable', advertise: true },\n { form: 'not_reviewed', means: 'notReviewed', advertise: true },\n];\nconst SEVERITY_ALIAS_LIST: FilterAlias[] = [{ form: 'none', means: 'informational', advertise: false }];\nconst DISPOSITION_ALIAS_LIST: FilterAlias[] = [\n { form: 'false_positive', means: 'falsePositive', advertise: true },\n];\n\n/** Derived from the lists, so an alias cannot be accepted without declaring whether it is advertised. */\nfunction aliasMap(aliases: FilterAlias[]): Record<string, string> {\n return Object.fromEntries(aliases.map((a) => [a.form, a.means]));\n}\n\nconst STATUS_ALIASES = aliasMap(STATUS_ALIAS_LIST);\nconst SEVERITY_ALIASES = aliasMap(SEVERITY_ALIAS_LIST);\nconst DISPOSITION_ALIASES = aliasMap(DISPOSITION_ALIAS_LIST);\n\n/** The accepted non-canonical forms for a field, or undefined when it has no closed vocabulary. */\nexport function filterAliases(field: string): FilterAlias[] | undefined {\n switch (field) {\n case 'status':\n return STATUS_ALIAS_LIST;\n case 'severity':\n return SEVERITY_ALIAS_LIST;\n case 'disposition':\n return DISPOSITION_ALIAS_LIST;\n default:\n return undefined;\n }\n}\n\n/** The canonical vocabulary for a field, or undefined when it has no closed one. */\nexport function filterValues(field: string): readonly string[] | undefined {\n switch (field) {\n case 'status':\n return STATUS_VALUES;\n case 'severity':\n return SEVERITY_VALUES;\n case 'disposition':\n return DISPOSITION_VALUES;\n default:\n return undefined;\n }\n}\n\n/**\n * The forms a help string or tool schema should name for a field: the canonical\n * vocabulary, then the aliases marked for teaching. Every value here is accepted,\n * but not everything accepted is here — a retired name is deliberately absent.\n * Parity: AdvertisedFilterValues in go/vocabulary.go.\n */\nexport function advertisedFilterValues(field: string): string[] | undefined {\n const canonical = filterValues(field);\n if (!canonical) return undefined;\n return [...canonical, ...(filterAliases(field) ?? []).filter((a) => a.advertise).map((a) => a.form)];\n}\n\n/**\n * Folds a value to the form comparisons use. Case only: two spellings are the\n * same value because this file says so, not because enough punctuation was\n * removed to make them collide.\n */\nexport function normalizeKey(s: string): string {\n return s.trim().toLowerCase();\n}\n\nfunction canonical(\n vocabulary: readonly string[],\n aliases: Record<string, string> | null,\n value: string\n): string {\n const key = normalizeKey(value);\n if (aliases && aliases[key]) return aliases[key];\n return vocabulary.find((member) => normalizeKey(member) === key) ?? '';\n}\n\n/** Whether s names a status the filter understands, in any accepted form. */\nexport function validStatus(s: string): boolean {\n return canonical(STATUS_VALUES, STATUS_ALIASES, s) !== '';\n}\n\n/** Whether s names an override type the filter understands, in any accepted form. */\nexport function validDisposition(s: string): boolean {\n return canonical(DISPOSITION_VALUES, DISPOSITION_ALIASES, s) !== '';\n}\n\n/** Whether s names a severity the filter understands, in any accepted form. */\nexport function validSeverity(s: string): boolean {\n return canonical(SEVERITY_VALUES, SEVERITY_ALIASES, s) !== '';\n}\n\n/**\n * The canonical form of a filter value for the named field, or the value\n * unchanged when the field has no closed vocabulary or the value names no\n * member. Normalizing here rather than in one caller is what makes a threshold\n * rule and an `hdf query` invocation mean the same thing.\n */\nexport function normalizeFilterValue(field: string, value: string): string {\n switch (field) {\n case 'status':\n return canonical(STATUS_VALUES, STATUS_ALIASES, value) || value;\n case 'severity':\n return canonical(SEVERITY_VALUES, SEVERITY_ALIASES, value) || value;\n case 'disposition':\n return canonical(DISPOSITION_VALUES, DISPOSITION_ALIASES, value) || value;\n case 'poams':\n if (!validPoamFilter(value)) return value;\n return normalizeKey(value) === normalizeKey(POAM_VALID) ? POAM_VALID : POAM_NONE_VALID;\n default:\n return value;\n }\n}\n","// Glob matching — the TypeScript peer of hdf-engine/go/safematch.go. Kept at\n// behavioural parity with the Go matcher.\n\nconst MAX_PATTERN_LENGTH = 256;\n\nconst REGEX_SPECIAL = new Set(['.', '+', '^', '$', '(', ')', '[', ']', '{', '}', '|', '\\\\']);\n\n/**\n * globToRegex converts a glob pattern (with * and ? wildcards) to an anchored\n * regular expression, escaping every other regex metacharacter exactly once. A\n * single pass avoids re-escaping the backslash introduced by escaping an earlier\n * metacharacter (the doubled-backslash defect that made any dotted pattern match\n * nothing).\n */\nexport function globToRegex(glob: string): string {\n let result = '^';\n for (const ch of glob) {\n if (ch === '*') {\n result += '.*';\n } else if (ch === '?') {\n result += '.';\n } else if (REGEX_SPECIAL.has(ch)) {\n result += '\\\\' + ch;\n } else {\n result += ch;\n }\n }\n return result + '$';\n}\n\n/**\n * safeGlobMatch converts a glob pattern to a regex and matches case-insensitively.\n * Returns false for over-length or invalid patterns (fail-safe), mirroring the\n * Go matcher's length cap and error handling.\n */\nconst byteEncoder = new TextEncoder();\n\n/** byteLength returns the UTF-8 byte length, matching Go's len(string). */\nfunction byteLength(s: string): number {\n return byteEncoder.encode(s).length;\n}\n\nexport function safeGlobMatch(s: string, pattern: string): boolean {\n // Cap on UTF-8 byte length (matching Go's len(pattern)), and — like Go's\n // compileSafeRegex — re-cap the EXPANDED regex, so an over-length glob or a\n // small glob that expands past the limit is rejected identically in both\n // languages (not just capped on the raw glob's UTF-16 length).\n if (byteLength(pattern) > MAX_PATTERN_LENGTH) {\n return false;\n }\n const rx = globToRegex(pattern);\n if (byteLength(rx) > MAX_PATTERN_LENGTH) {\n return false;\n }\n let re: RegExp;\n try {\n re = new RegExp(rx, 'i');\n } catch {\n return false;\n }\n return re.test(s);\n}\n","/**\n * A predicate field's value set, and the normalizer that accepts the three\n * spellings a policy may use for it: a bare scalar for the common single-value\n * case, a list, and a `{not: [...]}` object for exclusion.\n *\n * Negation is PURE: `not` means \"does not match any of these\", and a requirement\n * whose field is ABSENT satisfies it. The alternative — requiring the field to\n * be present — silently weakens gates, because the requirement a gate most needs\n * to catch is usually the one nobody has touched. `{status: [failed],\n * disposition: {not: [waiver]}}` with `max: 0` must catch a failure nobody\n * adjudicated; under a presence-requiring reading that requirement is excluded\n * and the bound passes.\n *\n * Parity: Values in go/values.go.\n */\n/**\n * What a policy may write for a multi-value field: a scalar, a list, or a\n * {not: [...]} object. Normalized to Values before it reaches a matcher.\n */\nexport type PredicateValue = string | string[] | { not: string | string[] };\n\nexport interface Values {\n in: string[];\n not: string[];\n}\n\n// NOTE: there is deliberately no exported constructor for a Values here. One\n// existed and was a trap: {in: [...]} is the decoder's OUTPUT shape and is\n// refused as a policy form, so its result threw when passed back to filter().\n// TypeScript callers pass the policy spellings — a scalar, a list, or\n// {not: [...]} — and normalizeValues turns them into this. Go's In() is safe\n// because Go reaches the decoder by type rather than by normalizing a literal.\n\n/** Whether the field constrains anything at all. */\nexport function valuesActive(v: Values | undefined): boolean {\n return v !== undefined && (v.in.length > 0 || v.not.length > 0);\n}\n\n/**\n * Every value the field names, in either mode, for callers that validate the\n * vocabulary — a value inside `not` must be refused exactly as one outside it\n * is, or a typo there excludes nothing and the predicate matches everything.\n */\nexport function valuesAll(v: Values | undefined): string[] {\n return v === undefined ? [] : [...v.in, ...v.not];\n}\n\n/**\n * Applies the field's own per-value test. `test` reports whether the requirement\n * matches ONE named value; this combines those the way the vocabulary always has\n * — values within a field OR — and then applies the exclusion.\n */\nexport function valuesMatch(v: Values, test: (value: string) => boolean): boolean {\n if (v.in.length > 0 && !v.in.some(test)) return false;\n if (v.not.length > 0 && v.not.some(test)) return false;\n return true;\n}\n\n/**\n * Normalizes whatever a policy carried into a Values. Throws on a shape that is\n * none of the three, so a malformed predicate is refused rather than silently\n * asserting nothing. Parity: Values.UnmarshalYAML / UnmarshalJSON in\n * go/values.go, and the shared case table pins the accepted forms.\n */\nexport function normalizeValues(raw: unknown): Values {\n if (raw === undefined || raw === null) return { in: [], not: [] };\n if (typeof raw === 'string') return { in: [raw], not: [] };\n if (Array.isArray(raw)) {\n if (!raw.every((v) => typeof v === 'string')) {\n throw new Error('a predicate value is a value, a list, or {not: ...}');\n }\n return { in: raw as string[], not: [] };\n }\n if (typeof raw === 'object') {\n const keys = Object.keys(raw as Record<string, unknown>);\n const other = keys.find((k) => k !== 'not');\n if (other !== undefined) {\n throw new Error(`field \"${other}\" is not a known form; a predicate value is a value, a list, or {not: ...}`);\n }\n const inner = normalizeValues((raw as { not?: unknown }).not);\n if (inner.not.length > 0) throw new Error('not cannot be nested inside not');\n if (inner.in.length === 0) {\n throw new Error('not excludes nothing; a predicate that asserts nothing is refused');\n }\n return { in: [], not: inner.in };\n }\n throw new Error('a predicate value is a value, a list, or {not: ...}');\n}\n","// Requirements query engine — the TypeScript peer of hdf-engine/go/filter.go.\n// A pure filter(results, options) with no shared mutable state, kept at\n// behavioural parity with the Go implementation (see test/query.test.ts, which\n// runs both over the same fixture).\n\nimport type { HDFResults, EvaluatedRequirement } from '@mitre/hdf-schema';\nimport {\n governingOverrideIndex,\n parseTimestamp,\n extractCWEIDs,\n type StatusOverrideInput,\n} from '@mitre/hdf-utilities';\nimport { deriveSeverity } from './compliance.js';\nimport { effectiveImpactOf, overrideInputs } from './effective.js';\nimport { normalizeKey, normalizeFilterValue } from './vocabulary.js';\nimport { safeGlobMatch } from './safematch.js';\nimport { valuesActive, valuesMatch, normalizeValues, type Values, type PredicateValue } from './values.js';\n\n/**\n * FilterOptions configures a requirements query. Every filter input arrives here;\n * distinct filters combine with AND, repeated values within a filter with OR.\n * statusOf resolves a requirement's display status, injected so the engine stays\n * agnostic to the caller's status-string convention (undefined → empty status).\n */\nexport interface FilterOptions {\n status?: PredicateValue;\n severity?: PredicateValue;\n /**\n * Compares the EFFECTIVE impact — the governing non-expired impact override's\n * value, else the requirement's own.\n */\n impact?: string;\n /**\n * Compares the requirement's own impact, ignoring overrides. It exists because\n * impact resolves them: the governance policy \"an override may not move a\n * critical below 0.7\" needs both scores, and no other key reaches the\n * unadjusted one.\n */\n rawImpact?: string;\n /**\n * Compares the requirement's authoritative CVSS score, using the same\n * comparison grammar as impact. See cvssScoreOf for what \"authoritative\"\n * resolves to and how several CVSS entries collapse to one number.\n */\n cvss?: string;\n /**\n * Compares the EPSS exploit PROBABILITY (epss.score), not the percentile\n * rank. They share a 0-1 scale and mean very different things.\n */\n epss?: string;\n /**\n * CISA Known Exploited Vulnerabilities membership: 'true' for kev.inKev,\n * 'false' for everything else — including a requirement carrying no kev block\n * at all, which is not known-exploited either.\n */\n kev?: string;\n /**\n * Selects by CWE identifier, OR across values, matched numerically so CWE-79,\n * 'CWE 79' and cwe79 are one value. Reads the first-class cwe[] field ONLY and\n * never falls back to tags.cwe.\n */\n cwe?: PredicateValue;\n cci?: PredicateValue;\n nist?: PredicateValue;\n id?: string;\n tag?: PredicateValue;\n search?: string;\n baseline?: string;\n /**\n * Selects requirements by the labels of the baseline they sit in, as\n * `key:value`, OR across values, with the value globbable exactly as a tag\n * value is. Named for the baseline rather than `label` alone because there is\n * no requirement-level label, and because system documents carry component\n * labels that may one day want their own key.\n *\n * A label is a property of the BASELINE, so this is applied once per baseline\n * beside `baseline` rather than per requirement. A baseline carrying no labels\n * therefore matches nothing: an absent label is not a wildcard.\n * Parity: Options.BaselineLabel in go/filter.go.\n */\n baselineLabel?: PredicateValue;\n /**\n * The TYPE of the override that governs the requirement (waiver,\n * falsePositive, riskAdjustment, …), OR across values. The governing override\n * is the most recent non-expired one of ANY kind, so it may differ from the one\n * that set the status — see governingDisposition. Resolved rather than read\n * from the stored disposition field, which is an output cache.\n */\n disposition?: PredicateValue;\n /**\n * Remediation-plan validity: 'valid' for a requirement carrying a POA&M still\n * in force, 'none-valid' for one carrying none, an empty list, or only lapsed\n * ones. Absence and expiry are one concept on purpose.\n */\n poams?: string;\n /** Kind of the governing POA&M: remediation|mitigation|riskAcceptance|vendorDependency. */\n poamType?: PredicateValue;\n /** RFC3339 reference clock for expiry; undefined means now. */\n now?: string;\n limit?: number;\n count?: boolean;\n statusOf?: (control: EvaluatedRequirement) => string;\n}\n\n/**\n * A single query result row. baselineIndex and index are the match's position in\n * the result set (results.baselines[baselineIndex].requirements[index]) and are\n * the only unique identity a match has: baseline names repeat in shipped\n * converter output and requirement ids repeat within a baseline, so (baseline,\n * id) is not a key. Address the source requirement by position, never by name.\n */\nexport interface Match {\n id: string;\n title: string;\n status: string;\n impact: number;\n severity: string;\n baseline: string;\n baselineIndex: number;\n index: number;\n}\n\ntype FilterFunc = (control: EvaluatedRequirement, status: string, severity: string) => boolean;\n\n/**\n * filter returns the requirements across the result set's baselines that satisfy\n * options. Applies to requirement collections (results/baseline documents); the\n * calling adapter rejects document types that carry no requirements.\n */\nexport function filter(results: HDFResults, rawOptions: FilterOptions): Match[] {\n // Normalized ONCE here, so every caller — a decoded policy, the CLI, the MCP,\n // or a TypeScript consumer passing a plain array — reaches the matchers with\n // the same shape. Parity: Go reaches it by type, through Values' unmarshaller.\n const options = normalizeOptions(rawOptions);\n const filters = buildFilters(options);\n const matches: Match[] = [];\n\n for (const [baselineIndex, baseline] of (results.baselines ?? []).entries()) {\n if (options.baseline && !matchesGlob(baseline.name, options.baseline)) {\n continue;\n }\n if (!baselineLabelsMatch(baseline.labels, options.baselineLabel)) {\n continue;\n }\n for (const [index, control] of (baseline.requirements ?? []).entries()) {\n if (options.limit && options.limit > 0 && matches.length >= options.limit && !options.count) {\n return matches;\n }\n\n const status = options.statusOf ? options.statusOf(control) : '';\n // Explicit STIG severity wins; impact-derived only as a fallback — the\n // canonical rule shared with the compliance counts (deriveSeverity), so\n // query rows and compliance never disagree on a requirement's severity.\n // Effective impact for the same reason the impact filter uses it: a\n // governing riskAdjustment moves the requirement into the band it was\n // re-scored into, and filter is an override-aware surface.\n const impact = effectiveImpactOf(control, options.now);\n const severity = deriveSeverity(impact, control.severity ?? null);\n\n if (!applyFilters(control, status, severity, filters)) {\n continue;\n }\n\n matches.push({\n id: control.id,\n title: control.title ?? '',\n status,\n // The effective impact, for the same reason status carries the\n // effective status and a Match has no raw twin of either.\n impact,\n severity,\n baseline: baseline.name,\n baselineIndex,\n index,\n });\n }\n }\n return matches;\n}\n\n/** The value fields, normalized; every other option passes through unchanged. */\ntype NormalizedOptions = Omit<FilterOptions, (typeof VALUE_FIELDS)[number]> & {\n [K in (typeof VALUE_FIELDS)[number]]?: Values;\n};\n\nexport const VALUE_FIELDS = [\n 'status',\n 'severity',\n 'cwe',\n 'cci',\n 'nist',\n 'tag',\n 'baselineLabel',\n 'disposition',\n 'poamType',\n] as const;\n\nfunction normalizeOptions(options: FilterOptions): NormalizedOptions {\n const out: Record<string, unknown> = { ...options };\n for (const field of VALUE_FIELDS) {\n if (out[field] !== undefined) out[field] = normalizeValues(out[field]);\n }\n return out as NormalizedOptions;\n}\n\nfunction buildFilters(options: NormalizedOptions): FilterFunc[] {\n const filters: FilterFunc[] = [];\n\n // Compared through normalizeKey so the CLI's display spelling and the schema's\n // camelCase are one value: a filter copied from `hdf query` and a rule written\n // against the schema must select the same requirements.\n if (valuesActive(options.status)) {\n // BOTH sides go through the same alias map: the injected resolver may speak\n // the CLI's display vocabulary while the spec speaks the schema's.\n filters.push((_c, s) => {\n const actual = normalizeKey(normalizeFilterValue('status', s));\n return valuesMatch(options.status!, (want) => actual === normalizeKey(normalizeFilterValue('status', want)));\n });\n }\n\n // Normalized the same way, and through the alias map as well, so 'none' — the\n // name informational replaced in 3.7.0 — keeps selecting it on every surface,\n // not only in the CLI.\n if (valuesActive(options.severity)) {\n filters.push((_c, _s, severity) => {\n const actual = normalizeKey(normalizeFilterValue('severity', severity));\n return valuesMatch(options.severity!, (want) => actual === normalizeKey(normalizeFilterValue('severity', want)));\n });\n }\n\n // Disposition (OR across values). A requirement with no governing override\n // matches nothing, which is what makes \"waived\" and \"not waived\" opposites.\n if (valuesActive(options.disposition)) {\n filters.push((c) => {\n const governing = governingDisposition(c, options.now);\n // Nothing governing matches no VALUE, which is what makes an inclusive\n // predicate exclude it and a negation accept it — a failure nobody\n // adjudicated is correctly 'not waived'.\n const actual = normalizeKey(normalizeFilterValue('disposition', governing));\n return valuesMatch(\n options.disposition!,\n (want) => governing !== '' && actual === normalizeKey(normalizeFilterValue('disposition', want)),\n );\n });\n }\n\n if (valuesActive(options.poamType)) {\n filters.push((c) => {\n const kind = governingPoamType(c, options.now);\n return valuesMatch(options.poamType!, (want) => kind !== '' && normalizeKey(kind) === normalizeKey(want));\n });\n }\n\n // POA&M validity. An unrecognized value matches NOTHING rather than silently\n // degrading, matching the impact filter's posture — callers validate with\n // validPoamFilter and reject before filtering.\n if (options.poams) {\n const wantValid = poamFilterWantsValid(options.poams);\n filters.push((c) => wantValid !== undefined && hasValidPoam(c, options.now) === wantValid);\n }\n\n // Compared against EFFECTIVE impact, so a governing riskAdjustment is\n // honoured. Status has resolved overrides all along; an impact filter that\n // ignored a formal re-score was the same amendments-blindness in the field\n // nobody looked at.\n if (options.impact) {\n const [op, val] = parseImpactFilter(options.impact);\n filters.push((c) => compareImpact(effectiveImpactOf(c, options.now), op, val));\n }\n\n // The unadjusted twin, same grammar and same safe-degradation.\n if (options.rawImpact) {\n const [op, val] = parseImpactFilter(options.rawImpact);\n filters.push((c) => compareImpact(c.impact, op, val));\n }\n\n // The vulnerability numbers, through the SAME comparison parser — a second\n // grammar would be a second thing to learn and a second thing to get wrong. A\n // requirement carrying no such score matches no comparison on it, rather than\n // defaulting to zero and matching '<5' for the wrong reason.\n if (options.cvss) {\n const [op, val] = parseImpactFilter(options.cvss);\n filters.push((c) => {\n const score = cvssScoreOf(c);\n return score !== undefined && compareImpact(score, op, val);\n });\n }\n if (options.epss) {\n const [op, val] = parseImpactFilter(options.epss);\n filters.push((c) => c.epss != null && compareImpact(c.epss.score, op, val));\n }\n if (options.kev) {\n const want = parseKevFilter(options.kev);\n filters.push((c) => want !== undefined && inKev(c) === want);\n }\n if (valuesActive(options.cwe)) {\n filters.push((c) => {\n const carried = new Set((c.cwe ?? []).flatMap((raw) => extractCWEIDs(String(raw))));\n return valuesMatch(options.cwe!, (want) => extractCWEIDs(want).some((id) => carried.has(id)));\n });\n }\n\n if (valuesActive(options.cci)) {\n filters.push((c) => valuesMatch(options.cci!, (want) => tagContains(c.tags, 'cci', want.toUpperCase())));\n }\n\n if (valuesActive(options.nist)) {\n filters.push((c) => valuesMatch(options.nist!, (want) => tagMatchesGlob(c.tags, 'nist', want)));\n }\n\n if (options.id) {\n const id = options.id;\n // A wildcard opts into glob matching; without one this stays the exact,\n // case-sensitive lookup it has always been. Parity: go/filter.go. The id a user\n // knows is often not the id the document carries — converters mint prefixed ids\n // (Grype/CVE-...) — while `search` reaches title, description and code and so\n // also matches a CVE merely cross-referenced in another finding's prose. A glob\n // reads only the identifier, so it can be precise about which one it names.\n if (/[*?]/.test(id)) {\n filters.push(\n (c) =>\n tagMatchesGlob(c.tags, 'stig_id', id) ||\n tagMatchesGlob(c.tags, 'gid', id) ||\n tagMatchesGlob(c.tags, 'gtitle', id) ||\n matchesGlob(c.id, id),\n );\n } else {\n filters.push(\n (c) =>\n tagContains(c.tags, 'stig_id', id) ||\n tagContains(c.tags, 'gid', id) ||\n tagContains(c.tags, 'gtitle', id) ||\n c.id === id,\n );\n }\n }\n\n if (valuesActive(options.tag)) {\n filters.push((c) =>\n valuesMatch(options.tag!, (want) => {\n // A colonless value names no key, so it matches nothing rather than\n // disappearing and letting the whole document through. The CLI refuses\n // one before it reaches here; this is the safe floor for any caller\n // that does not.\n const idx = want.indexOf(':');\n return idx > 0 && tagMatchesGlob(c.tags, want.slice(0, idx), want.slice(idx + 1));\n }),\n );\n }\n\n if (options.search) {\n const search = options.search.toLowerCase();\n filters.push((c) => {\n if (c.id.toLowerCase().includes(search)) return true;\n if (c.title && c.title.toLowerCase().includes(search)) return true;\n for (const desc of c.descriptions ?? []) {\n if (desc.data.toLowerCase().includes(search)) return true;\n }\n return false;\n });\n }\n\n return filters;\n}\n\nfunction applyFilters(\n control: EvaluatedRequirement,\n status: string,\n severity: string,\n filters: FilterFunc[],\n): boolean {\n return filters.every((f) => f(control, status, severity));\n}\n\n// DECIMAL_FLOAT is the shared impact-filter operand grammar — a plain decimal:\n// optional sign, digits with an optional fraction (or a leading-dot fraction),\n// optional decimal exponent. It excludes the forms JS Number() accepts but that\n// make no sense as a 0.0–1.0 threshold and diverge from Go strconv.ParseFloat:\n// hex/binary/octal integers (0x1f→31, 0b101→5, 0o17→15) and Infinity. The Go\n// engine applies the identical pattern so a filter is accepted or rejected the\n// same in both languages (bead 4908.15).\nconst DECIMAL_FLOAT = /^[+-]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?$/;\n\n// parseDecimal parses a plain-decimal operand, returning null for anything\n// outside the shared grammar (including overflow to Infinity, e.g. '1e400', so\n// Go's ParseFloat ErrRange rejection is mirrored).\nfunction parseDecimal(s: string): number | null {\n if (!DECIMAL_FLOAT.test(s)) return null;\n const v = Number(s);\n return Number.isFinite(v) ? v : null;\n}\n\n// An invalid operand safe-degrades to ('=', NaN), which compareImpact treats as\n// matching NOTHING — mirroring the Go engine's `return ok && compareImpact(...)`.\n// It must never coerce to ('=', 0), which silently returns confidently-wrong\n// impact==0 rows for a typo'd or garbage filter.\nexport function parseImpactFilter(f: string): [string, number] {\n const trimmed = f.trim();\n for (const op of ['>=', '<=', '>', '<', '=']) {\n if (trimmed.startsWith(op)) {\n const v = parseDecimal(trimmed.slice(op.length).trim());\n return v === null ? ['=', NaN] : [op, v];\n }\n }\n const v = parseDecimal(trimmed);\n return v === null ? ['=', NaN] : ['=', v];\n}\n\nexport function compareImpact(impact: number, op: string, val: number): boolean {\n switch (op) {\n case '>':\n return impact > val;\n case '>=':\n return impact >= val;\n case '<':\n return impact < val;\n case '<=':\n return impact <= val;\n case '=':\n return impact === val;\n default:\n return false;\n }\n}\n\nexport function tagContains(tags: Record<string, unknown>, key: string, value: string): boolean {\n const tagVal = tags?.[key];\n if (tagVal === undefined) {\n return false;\n }\n const want = value.toLowerCase();\n if (typeof tagVal === 'string') {\n return tagVal.toLowerCase() === want;\n }\n if (Array.isArray(tagVal)) {\n return tagVal.some((item) => typeof item === 'string' && item.toLowerCase() === want);\n }\n return false;\n}\n\nexport function tagMatchesGlob(tags: Record<string, unknown>, key: string, pattern: string): boolean {\n const tagVal = tags?.[key];\n if (tagVal === undefined) {\n return false;\n }\n if (typeof tagVal === 'string') {\n return safeGlobMatch(tagVal, pattern);\n }\n if (Array.isArray(tagVal)) {\n return tagVal.some((item) => typeof item === 'string' && safeGlobMatch(item, pattern));\n }\n return false;\n}\n\n/**\n * validTag reports whether s is a tag expression at all. A value carrying no\n * colon names no key, so it can never match — and unlike the label filter, which\n * merely selected nothing, a colonless tag was DROPPED from the filter list\n * entirely, so a predicate made only of colonless values matched the whole\n * document. Refused rather than tolerated in either direction.\n * Parity: ValidTag in go/filter.go.\n */\n/**\n * validKeyValue is the one \"key:value with a non-empty key\" test behind every\n * expression the filter takes in that shape; the exported names keep the\n * vocabulary each flag advertises. Parity: validKeyValue in go/filter.go.\n */\nfunction validKeyValue(s: string): boolean {\n return s.indexOf(':') > 0;\n}\n\nexport function validTag(s: string): boolean {\n return validKeyValue(s);\n}\n\n/**\n * The KIND of the governing POA&M, or '' when the governing entry is an override\n * or nothing governs. Resolves through the same index governingDisposition uses,\n * so disposition and poamType can never name different entries.\n *\n * Reading the GOVERNING plan rather than any carried plan is the whole point: a\n * requirement carrying a lapsed remediation under a live mitigation is governed\n * by the mitigation, and matching it on 'remediation' would let a dead plan\n * answer for a live one.\n * Parity: governingPoamType in go/filter.go.\n */\nfunction governingPoamType(control: EvaluatedRequirement, now?: string): string {\n const overrides = control.statusOverrides ?? [];\n const entries = [...overrideInputs(control), ...poamInputs(control)];\n const index = governingOverrideIndex(entries, () => true, now);\n if (index < overrides.length) return '';\n return (control.poams ?? [])[index - overrides.length]?.type ?? '';\n}\n\n/**\n * validBaselineLabel reports whether s is a label expression at all. A value\n * carrying no colon names no key, so it can never match any document — the same\n * forever-green gate a misspelled status value produces, which is why it is\n * refused rather than allowed to select nothing.\n * Parity: ValidBaselineLabel in go/filter.go.\n */\nexport function validBaselineLabel(s: string): boolean {\n return validKeyValue(s);\n}\n\n/**\n * baselineLabelsMatch reports whether a baseline satisfies any of the\n * `key:value` label predicates. No predicates means every baseline qualifies;\n * otherwise one must match, so several values OR the way every other multi-value\n * filter does.\n *\n * A predicate without a colon is refused at the boundary by validBaselineLabel\n * rather than handled here, because selecting nothing and being ignored produce\n * the SAME false green under a max bound: the gate passes while the caller\n * believes a filter was applied. Reaching this function it selects nothing,\n * which is the safe half of that pair.\n * Parity: baselineLabelsMatch in go/filter.go.\n */\nexport function baselineLabelsMatch(\n labels: Record<string, string> | undefined,\n predicates: Values | undefined,\n): boolean {\n if (!valuesActive(predicates)) return true;\n return valuesMatch(predicates!, (p) => {\n const colon = p.indexOf(':');\n return colon > 0 && labelMatchesGlob(labels, p.slice(0, colon), p.slice(colon + 1));\n });\n}\n\n/**\n * labelMatchesGlob reports whether a label KEY is present and its value matches\n * the pattern. Deliberately not tagMatchesGlob: a tag value may be a list, which\n * is why that one goes through the tag helpers, while a label is exactly one\n * string by schema (`additionalProperties: {type: string}`). An absent key\n * matches nothing, including against `*` — the predicate asks about a label the\n * baseline does not carry, and there is nothing to match.\n * Parity: labelMatchesGlob in go/filter.go.\n */\nexport function labelMatchesGlob(\n labels: Record<string, string> | undefined,\n key: string,\n pattern: string,\n): boolean {\n const value = labels?.[key];\n if (value === undefined) return false;\n return safeGlobMatch(value, pattern);\n}\n\n/** matchesGlob reports whether s matches the glob pattern (case-insensitive). */\nexport function matchesGlob(s: string, pattern: string): boolean {\n return safeGlobMatch(s, pattern);\n}\n\n/**\n * The closed vocabulary the disposition filter accepts: the schema's\n * Override_Type enum. A value outside it can only ever match nothing, which\n * would report a clean run over a filter the caller believed was applied.\n * Parity: DispositionValues in go/filter.go, pinned by the shared case table.\n * Membership is not pinned to the schema: an eighth override type would be\n * silently unfilterable in both languages until someone adds it here.\n */\nexport const DISPOSITION_VALUES = [\n 'waiver',\n 'attestation',\n 'poam',\n 'inherited',\n 'falsePositive',\n 'riskAdjustment',\n 'operationalRequirement',\n] as const;\n\n/**\n * The closed vocabulary the poamType filter accepts: the schema's POA&M type\n * enum. Deliberately NOT merged into DISPOSITION_VALUES — disposition answers\n * which Override_Type governs, and a plan's kind is not an override type.\n * Parity: PoamTypeValues in go/filter.go, pinned by the shared case table.\n */\nexport const POAM_TYPE_VALUES = ['remediation', 'mitigation', 'riskAcceptance', 'vendorDependency'] as const;\n\n/**\n * Reports whether s names a POA&M kind. A value outside the vocabulary can only\n * ever match nothing, so callers refuse it rather than letting it read as\n * \"asked and found none\".\n * Parity: ValidPoamType in go/filter.go.\n */\nexport function validPoamType(s: string): boolean {\n return POAM_TYPE_VALUES.some((v) => normalizeKey(v) === normalizeKey(s));\n}\n\n/**\n * Reports whether s names an override type. Callers validate with this and\n * reject, rather than letting a typo match nothing and pass — the same contract\n * validPoamFilter provides for the other amendment filter.\n */\n// Re-exported from vocabulary.ts, where all four validators share one canonical()\n// rather than this one inferring \"is an alias\" from \"the normalizer changed it\".\nexport { validDisposition } from './vocabulary.js';\n\n/**\n * The two values the poams filter accepts. 'none-valid' covers a requirement\n * with no POA&M, with an empty list, and with only lapsed ones: a plan that has\n * expired is not a plan, and splitting the two cases would create a value whose\n * only use is to be chosen by mistake.\n */\nexport const POAM_VALID = 'valid';\nexport const POAM_NONE_VALID = 'none-valid';\n\n/**\n * Reports whether s is a POA&M validity value the filter understands. Callers\n * validate with this and reject, rather than letting an unrecognized value match\n * nothing and pass.\n */\nexport function validPoamFilter(s: string): boolean {\n return poamFilterWantsValid(s) !== undefined;\n}\n\nfunction poamFilterWantsValid(s: string): boolean | undefined {\n switch (s.trim().toLowerCase()) {\n case POAM_VALID:\n return true;\n case POAM_NONE_VALID:\n return false;\n default:\n return undefined;\n }\n}\n\n/**\n * The type of the override that governs the requirement, or '' when none does:\n * the most recently applied non-expired override, whatever it carries. That is\n * the schema's own definition, and the rule hdf-diff has always used to compute\n * the effective checksum.\n *\n * Eligibility is deliberately unfiltered here, unlike the status and impact\n * ladders. Requiring a status — as this did — meant an override carrying only an\n * impact governed nothing, so `--disposition riskAdjustment` could not match the\n * shape a riskAdjustment normally has. The cost is that disposition may name a\n * different override than the one that decided the status, which is what\n * per-field eligibility means rather than a contradiction.\n */\nfunction governingDisposition(control: EvaluatedRequirement, now?: string): string {\n // Overrides and POA&Ms are ONE ordered set, not two tiers: the schema defines\n // disposition as 'the most recent non-expired override or POAM governing this\n // requirement'. Both carry appliedAt and expiresAt with the same meaning, so\n // the existing resolver decides between them without inventing a comparison.\n // Parity: governingDisposition in go/filter.go.\n const overrides = control.statusOverrides ?? [];\n const entries = [...overrideInputs(control), ...poamInputs(control)];\n\n const index = governingOverrideIndex(entries, () => true, now);\n if (index < 0) return '';\n if (index < overrides.length) return overrides[index]?.type ?? '';\n // A POA&M's own kind — remediation, mitigation, riskAcceptance,\n // vendorDependency — is not a member of Override_Type, which is what\n // disposition is typed as, so every governing POA&M reports the flat 'poam'.\n return 'poam';\n}\n\n/**\n * Projects POA&Ms onto the shape the override resolver compares, carrying no\n * status or impact because a POA&M changes neither: it tracks the work being\n * done about a failure rather than adjudicating it.\n * Parity: poamInputs in go/filter.go.\n */\nfunction poamInputs(control: EvaluatedRequirement): StatusOverrideInput[] {\n return (control.poams ?? []).map((p) => ({\n appliedAt: new Date(p.appliedAt).toISOString(),\n expiresAt: new Date(p.expiresAt).toISOString(),\n }));\n}\n\n/**\n * Whether the requirement carries a POA&M still in force. expiresAt is required\n * by the schema, so a POA&M always has a deadline to judge; one exactly at the\n * reference instant has passed, matching how an override's expiry is judged.\n */\n// Note the inverted zero: hdfutil treats an override with no expiresAt as never\n// expiring, while a POA&M without a deadline is treated as already lapsed. The\n// schema requires poams[].expiresAt so it should not arise, but the two\n// same-shaped fields mean opposite things when empty.\nfunction hasValidPoam(control: EvaluatedRequirement, now?: string): boolean {\n // parseTimestamp returns null on an unparseable value; falling back to the\n // wall clock there is wrong in the other direction, so an unusable reference\n // is treated as no reference and the caller's own validation catches it.\n const parsed = now ? parseTimestamp(now) : null;\n const ref = parsed ? parsed.getTime() : Date.now();\n // A poam-typed statusOverride IS a filed plan, and it is the only form the\n // toolchain actually produces: `hdf amend apply` writes statusOverrides[], no\n // importer emits poams[], and no committed fixture carries one. Reading only\n // poams[] made this predicate dead — \"every failure has a current plan\" could\n // never pass however many POA&Ms were filed.\n //\n // \"Carries\" is not the question disposition answers: disposition names the\n // GOVERNING adjudication, so a newer override outranks an older plan without\n // cancelling it and the two can disagree. Parity: go/filter.go hasValidPoam.\n const overridePlan = (control.statusOverrides ?? []).some(\n (o) => o.type === 'poam' && new Date(o.expiresAt).getTime() > ref\n );\n return overridePlan || (control.poams ?? []).some((poam) => new Date(poam.expiresAt).getTime() > ref);\n}\n\n/**\n * The requirement's authoritative CVSS score, or undefined when it carries none.\n *\n * Two decisions live here. An entry's score is its computedScore when the\n * producer supplied one, else its baseScore: the schema calls computedScore \"the\n * score consumers should treat as authoritative for risk decisions when\n * present\", and converters populate it: nessus-to-hdf writes a requirement-level\n * computedScore when it has the metrics to recompute one, and hdf-to-csv already\n * resolves computedScore-else-baseScore for its own column, so a gate reading\n * baseScore alone would disagree with both. It does NOT reach\n * `hdf enrich --recompute-cvss`, which writes its recomputed score into a\n * riskAdjustment OVERRIDE's cvss block rather than the requirement's own cvss[].\n * And a\n * requirement may carry one entry per CVE, resolving to the HIGHEST of them: a\n * finding matching several CVEs is as dangerous as its worst.\n *\n * Parity: cvssScoreOf in go/filter.go.\n */\nexport function cvssScoreOf(control: EvaluatedRequirement): number | undefined {\n let best: number | undefined;\n for (const entry of control.cvss ?? []) {\n const score = entry.computedScore ?? entry.baseScore;\n if (typeof score === 'number' && (best === undefined || score > best)) best = score;\n }\n return best;\n}\n\n/**\n * CISA Known Exploited Vulnerabilities membership. An absent kev block reads as\n * false: a requirement nobody checked against the catalog is not\n * known-exploited, and treating absence as unknown would leave 'kev: false'\n * unable to express \"everything CISA does not list\".\n */\nfunction inKev(control: EvaluatedRequirement): boolean {\n return control.kev?.inKev === true;\n}\n\n/** Accepts only 'true' and 'false'; anything else yields undefined. */\nfunction parseKevFilter(s: string): boolean | undefined {\n switch (s.trim().toLowerCase()) {\n case 'true':\n return true;\n case 'false':\n return false;\n default:\n return undefined;\n }\n}\n\n/**\n * Whether a kev filter value is one this engine understands, for callers to\n * reject up front rather than matching nothing.\n */\nexport function validKevFilter(s: string): boolean {\n return parseKevFilter(s) !== undefined;\n}\n","// Threshold rules — the TypeScript peer of hdf-engine/go/rules.go. A rule is a\n// filter predicate plus a bound on how many requirements may match it, for the\n// policies the fixed status × severity grid cannot express. Kept at behavioural\n// parity with the Go implementation by the shared case table both suites read\n// (testdata/threshold-rule-cases.json).\n\nimport type { HDFResults, EvaluatedRequirement } from '@mitre/hdf-schema';\nimport { filter, type FilterOptions } from './query.js';\nimport type { Violation } from './compliance.js';\nimport { normalizeValues, type PredicateValue } from './values.js';\nimport {\n validateGrid,\n type ThresholdConfig,\n type StatusCounts,\n type ControlIDMapping,\n} from './compliance.js';\n\n/**\n * The predicate surface, in one place. Go maps these onto the filter explicitly\n * while TypeScript spreads them, so a field known to one language and not the\n * other is silently inert on one side; the shared case table pins this list, and\n * the assertion below stops the interface drifting away from it.\n */\nexport const PREDICATE_FIELDS = [\n 'status',\n 'severity',\n 'impact',\n 'rawImpact',\n 'cvss',\n 'epss',\n 'kev',\n 'cwe',\n 'cci',\n 'nist',\n 'id',\n 'tag',\n 'search',\n 'baseline',\n 'baselineLabel',\n 'disposition',\n 'poamType',\n 'poams',\n] as const;\n\n/**\n * The vocabulary a rule may name. It is deliberately the filter engine's own\n * vocabulary rather than a second one: a rule and an `hdf query` invocation then\n * mean the same thing. Values within a field OR; fields AND.\n */\nexport interface RulePredicate {\n status?: PredicateValue;\n severity?: PredicateValue;\n impact?: string;\n rawImpact?: string;\n cvss?: string;\n epss?: string;\n kev?: string;\n cwe?: PredicateValue;\n cci?: PredicateValue;\n nist?: PredicateValue;\n id?: string;\n tag?: PredicateValue;\n search?: string;\n baseline?: string;\n /**\n * Selects by the labels of the baseline a requirement sits in, which is what\n * makes 'nothing fails in anything labelled environment=production'\n * expressible as a policy rather than only as a query.\n */\n baselineLabel?: PredicateValue;\n disposition?: PredicateValue;\n /**\n * The KIND of the governing POA&M, which disposition collapses to the flat\n * 'poam' because it is typed Override_Type and a plan's kind is not one.\n */\n poamType?: PredicateValue;\n poams?: string;\n}\n\n/**\n * A policy the grid cannot express. Two decisions, recorded because a policy\n * author will otherwise assume one of them: a rule bounds a COUNT and not a\n * percentage — the grid's compliance min/max remains the only percentage bound,\n * and extending rules to percentages is deferred rather than excluded — and a\n * rule evaluates over the WHOLE document, not per baseline. A policy that wants\n * one baseline says so with the baseline predicate.\n *\n * `name` is optional and exists for the\n * violation message; a rule without one is identified by its predicate, which is\n * the only other handle a reader has.\n */\nexport interface ThresholdRule {\n name?: string;\n where: RulePredicate;\n min?: number;\n max?: number;\n}\n\n/**\n * What rule evaluation needs beyond the document: the reference clock for\n * expiry, and the status resolver. statusOf is injected rather than assumed so a\n * rule and the grid's counts cannot disagree about what 'failed' means on the\n * same document.\n */\nexport interface RuleOptions {\n now?: string;\n statusOf?: (control: EvaluatedRequirement) => string;\n}\n\n/**\n * Maps a predicate onto the engine filter. Every field is a pass-through: the\n * point of reusing the vocabulary is that there is nothing to translate, and a\n * new filter field becomes a rule field by adding it here.\n */\nfunction filterOptions(where: RulePredicate, options: RuleOptions): FilterOptions {\n return {\n ...where,\n now: options.now,\n // count so a limit can never truncate the population a bound is judged\n // against — a rule counts matches, it does not list them.\n count: true,\n statusOf: options.statusOf,\n };\n}\n\n/**\n * Renders a predicate for a violation message, fields sorted so the same rule\n * always reads the same way. Values within a field join with '|', which is what\n * they mean. Parity: describe() in go/rules.go.\n */\nfunction describe(where: RulePredicate): string {\n const parts: string[] = [];\n for (const [key, value] of Object.entries(where)) {\n if (value === undefined || value === null || value === '') continue;\n if (typeof value === 'string') {\n // A scalar is the one-element list, and reads as one.\n parts.push(`${key}: ${value}`);\n continue;\n }\n if (Array.isArray(value)) {\n if (value.length > 0) parts.push(`${key}: ${value.join('|')}`);\n continue;\n }\n // A negated field renders as \"not X|Y\" so an unnamed rule's identity says\n // which way round its predicate ran — without this it rendered\n // \"[object Object]\". Parity: add() in go/rules.go.\n const v = normalizeValues(value);\n if (v.in.length > 0) parts.push(`${key}: ${v.in.join('|')}`);\n if (v.not.length > 0) parts.push(`${key}: not ${v.not.join('|')}`);\n }\n parts.sort();\n return `{${parts.join(', ')}}`;\n}\n\nfunction label(rule: ThresholdRule): string {\n return rule.name && rule.name !== '' ? rule.name : `rule ${describe(rule.where)}`;\n}\n\n/**\n * Applies every rule to the document and returns one violation per breached\n * bound. Evaluation is filter → count → compare, calling the engine's own filter\n * rather than a second matcher.\n */\nexport function evaluateRules(\n config: ThresholdConfig,\n results: HDFResults,\n options: RuleOptions = {}\n): Violation[] {\n const violations: Violation[] = [];\n for (const rule of config.rules ?? []) {\n // The matches, not just their count: naming which requirements broke a gate\n // is the difference between a red check a reader can act on and one that\n // sends them to an artifact and a script. This filter already ran.\n const matches = filter(results, filterOptions(rule.where, options));\n const matched = matches.length;\n if (rule.max !== undefined && matched > rule.max) {\n violations.push({ message: `${label(rule)}: ${matched} matched, maximum ${rule.max}`, findings: matches });\n }\n if (rule.min !== undefined && matched < rule.min) {\n // A minimum is breached by what is ABSENT, so the matches are the\n // requirements that DID qualify — fewer than required. Naming them still\n // says what the gate found rather than what it wanted.\n violations.push({ message: `${label(rule)}: ${matched} matched, minimum ${rule.min}`, findings: matches });\n }\n }\n return violations;\n}\n\n/**\n * Everything an evaluation needs. A shape rather than a parameter list because\n * rules made the list long enough that a caller could transpose two arguments of\n * the same type without the compiler noticing. Parity: ThresholdInput in\n * go/rules.go.\n */\nexport interface ThresholdInput {\n results: HDFResults;\n counts: StatusCounts;\n compliance: number;\n controlMap: ControlIDMapping[];\n now?: string;\n statusOf?: (control: EvaluatedRequirement) => string;\n}\n\n/**\n * Applies a whole policy — the grid and the rules — and returns every violation.\n * This is the entry point a surface should call: validateThresholds evaluates the\n * grid alone and refuses a config carrying rules, so a caller cannot\n * half-implement a policy without being told. Parity: Evaluate in go/rules.go.\n */\nexport function evaluate(config: ThresholdConfig, input: ThresholdInput): Violation[] {\n const violations = validateGrid(config, input.counts, input.compliance, input.controlMap);\n return violations.concat(\n evaluateRules(config, input.results, { now: input.now, statusOf: input.statusOf })\n );\n}\n\n// Compile-time guard: a field added to RulePredicate and not to PREDICATE_FIELDS\n// would reach the TypeScript filter through the spread and never reach Go, which\n// is the drift the shared field list exists to prevent. This fails the build\n// rather than waiting for a test nobody wrote.\ntype UnlistedPredicateField = Exclude<keyof RulePredicate, (typeof PREDICATE_FIELDS)[number]>;\nconst _everyPredicateFieldIsListed: UnlistedPredicateField extends never ? true : never = true;\nvoid _everyPredicateFieldIsListed;\n","// Document loader engine core — the TypeScript peer of hdf-engine/go/loader.go,\n// kept at behavioural parity (see loader.test.ts + the Go parity test, which\n// run both over the same fixtures). Pure and schema-typed: size-guard first,\n// wire-format + document-type detection, then the canonical parse for the\n// results/baseline types. No cache, no degraded envelope — those are MCP\n// concerns layered on top in hdf-cli/internal/mcp/loader.\n\nimport type { HDFResults, HDFBaseline } from '@mitre/hdf-schema';\nimport { validateInputSize } from '@mitre/hdf-utilities';\nimport { parseResults, parseBaseline } from '@mitre/hdf-parsers';\nimport { detect, type HdfDocType } from './detect.js';\n\n/** Wire encoding of loader input (parity with Go InputFormat). */\nexport type InputFormat = 'json' | 'ndjson';\n\nexport interface LoadResult {\n format: InputFormat;\n docType: HdfDocType;\n results?: HDFResults;\n baseline?: HDFBaseline;\n /** Non-empty when detected as results/baseline but the parse/validate failed. */\n parseError?: string;\n valid: boolean;\n}\n\n/**\n * load is the schema-typed loader core. In order: validateInputSize (FIRST,\n * before any parse; maxSize <= 0 uses the default), wire-format detection\n * (JSON vs NDJSON), document-type detection (detect), then the canonical\n * hdf-parsers parse for the results and baseline types. Other types are\n * detected but not parsed here.\n */\nexport function load(input: string | Uint8Array, maxSize = 0): LoadResult {\n validateInputSize(input, maxSize); // first op — throws on oversize\n\n const text = typeof input === 'string' ? input : new TextDecoder().decode(input);\n const result: LoadResult = {\n format: detectFormat(text),\n docType: detect(text),\n valid: false,\n };\n\n if (result.docType === 'results') {\n const r = parseResults(text);\n if (r.success && r.data) {\n result.results = r.data;\n result.valid = true;\n } else {\n result.parseError = r.error;\n }\n } else if (result.docType === 'baseline') {\n const r = parseBaseline(text);\n if (r.success && r.data) {\n result.baseline = r.data;\n result.valid = true;\n } else {\n result.parseError = r.error;\n }\n }\n\n return result;\n}\n\n/**\n * detectFormat classifies input as a single JSON document or newline-delimited\n * JSON, consistent with the Go core: NDJSON is two or more non-blank lines that\n * each independently parse as a complete JSON value. A pretty-printed single\n * object stays 'json' (its first line is not itself a complete JSON value).\n */\nexport function detectFormat(text: string): InputFormat {\n const lines = text.split('\\n').filter((l) => l.trim() !== '');\n const [first, second] = lines;\n if (first === undefined || second === undefined) {\n return 'json';\n }\n if (isCompleteJSON(first) && isCompleteJSON(second)) {\n return 'ndjson';\n }\n return 'json';\n}\n\n// isCompleteJSON reports whether s is a single complete JSON value with no\n// trailing content — the per-line test the NDJSON classifier applies. JSON.parse\n// already rejects trailing garbage, so a successful parse is sufficient.\nfunction isCompleteJSON(s: string): boolean {\n try {\n JSON.parse(s);\n return true;\n } catch {\n return false;\n }\n}\n","// Evidence-verify engine — the TypeScript peer of hdf-engine/go/evidence.go.\n// Pure, filesystem-agnostic core of `hdf evidence info --verify` (ADR-0007 §11):\n// content-checksum classification and plan/results completeness. All filesystem\n// IO and path confinement stay in the caller, injected as a FetchFn. Kept at\n// behavioural parity with the Go implementation (see test/evidence.test.ts,\n// which runs both over the same fixtures).\n\nimport { blake3 } from '@noble/hashes/blake3.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport { generateHash, type HashAlgorithm } from '@mitre/hdf-utilities';\nimport { agentOverrideCount } from './compliance.js';\nimport type { HDFResults } from '@mitre/hdf-schema';\n\n/** Classifies a single content entry's checksum verification. 'unsupported' is a\n * recorded algorithm this build cannot compute — deliberately NOT 'error', since the\n * bytes may be intact and the package valid. Every consumer switching on this type\n * must handle it; leaving it to a default reports an unverified entry as verified. */\nexport type ChecksumStatus = 'match' | 'mismatch' | 'skipped' | 'error' | 'unsupported';\n\n/** One content entry of an evidence package: a referenced document and its\n * recorded checksum ('' when the entry carries none). */\nexport interface EvidenceContent {\n uri: string;\n type: string;\n checksum: string;\n /** The algorithm the package recorded, '' when it stated none. Optional so an\n * omitted field behaves exactly like Go's zero-valued string: absent means\n * sha256 at verification time. The sha256 default belongs to verification, not\n * to the parse, so an unstated algorithm is not invented here. */\n checksumAlgorithm?: string;\n /** Distinguishes an entry carrying no checksum object from one carrying a\n * checksum whose value is empty. `checksum` alone conflates them, and the\n * difference matters: a recorded-but-blank value is unverifiable, whereas an\n * absent checksum is simply not a claim. Optional so an omitted field behaves\n * like Go's zero-valued bool. */\n checksumRecorded?: boolean;\n /** Set for an `externalEvidence[]` entry and absent for a `contents[]` one;\n * `type` is the reverse. The schema gives the two arrays different fields — a\n * content entry records a Content_Type, an external entry records a native\n * Native_Format — so they are kept apart rather than collapsed into `type`,\n * which would put 'raw-log' in a field whose vocabulary is the seven document\n * types. Optional so an omitted field behaves like Go's zero-valued string. */\n format?: string;\n}\n\n/** The verification outcome for one content entry. */\nexport interface ChecksumResult {\n uri: string;\n type: string;\n /** Mirrors `EvidenceContent.format`: set for an `externalEvidence[]` entry,\n * absent for a `contents[]` one, so a caller can report what an artifact is\n * without reading `type`'s Content_Type vocabulary onto it. */\n format?: string;\n /** The algorithm this entry's checksum is recorded under, with an unstated one\n * reported as the sha256 it defaults to. Absent for a skipped entry — one with no\n * checksum VALUE to verify, whether it carries no checksum at all or one whose\n * value is blank (Checksum.value has no minLength, so a blank value is\n * schema-valid and may still name an algorithm). Nothing was hashed in either\n * case, and naming an algorithm would imply a computation that never ran. */\n algorithm?: string;\n status: ChecksumStatus;\n expected?: string;\n actual?: string;\n error?: string;\n}\n\n/** Reports which planned baselines are covered by results. */\nexport interface CompletenessResult {\n planned: string[];\n covered: string[];\n missing: string[];\n complete: boolean;\n}\n\n/** Resolves a content URI to its bytes. The caller owns path confinement\n * (HDF_MCP_ROOT for the MCP, the package directory for the CLI). Throws when the\n * uri cannot be read. */\nexport type FetchFn = (uri: string) => Uint8Array;\n\ntype RawObject = Record<string, unknown>;\n\n/** Go decodes into a typed struct, so a JSON `null` document leaves zero values\n * while a wrong-typed one is a decode error. These three helpers give the TS\n * peer the same split instead of asserting a shape onto untrusted input. */\nfunction parseDocument(text: string, what: string): RawObject {\n const doc: unknown = JSON.parse(text);\n if (doc === null) return {};\n if (typeof doc !== 'object' || Array.isArray(doc)) {\n throw new Error(`parse ${what}: cannot unmarshal ${describe(doc)} into an object`);\n }\n return doc as RawObject;\n}\n\nfunction objectArray(value: unknown, what: string, field: string): RawObject[] {\n if (value === undefined || value === null) return [];\n if (!Array.isArray(value)) {\n throw new Error(`parse ${what}: cannot unmarshal ${describe(value)} into ${field}`);\n }\n return value.map((entry: unknown) => {\n if (entry === null) return {};\n if (typeof entry !== 'object' || Array.isArray(entry)) {\n throw new Error(`parse ${what}: cannot unmarshal ${describe(entry)} into a ${field} entry`);\n }\n return entry as RawObject;\n });\n}\n\nfunction str(value: unknown): string {\n return typeof value === 'string' ? value : '';\n}\n\nfunction describe(value: unknown): string {\n return Array.isArray(value) ? 'array' : value === null ? 'null' : typeof value;\n}\n\n/** Extracts the planRef and content entries from an evidence-package document. */\nexport function parseEvidencePackage(pkg: string): { planRef: string; contents: EvidenceContent[] } {\n const doc = parseDocument(pkg, 'evidence package');\n const contents: EvidenceContent[] = objectArray(doc.contents, 'evidence package', 'contents').map((c) => {\n const checksum = c.checksum;\n const isObject = typeof checksum === 'object' && checksum !== null;\n return {\n uri: str(c.uri),\n type: str(c.type),\n checksum: isObject ? str((checksum as RawObject).value) : '',\n checksumAlgorithm: isObject ? str((checksum as RawObject).algorithm) : '',\n checksumRecorded: isObject,\n };\n });\n return { planRef: str(doc.planRef), contents };\n}\n\n/** Returns the `externalEvidence[]` entries as the same shape `contents[]` parses\n * to, so ONE verification pass covers both arrays. It exists because verify\n * examined `contents[]` only, and a wrong checksum in the other array passed at\n * exit 0 while bundle refused the same package — the two commands disagreeing\n * about one document.\n *\n * Additive on purpose: `verifyChecksums` is reused unchanged on what this returns,\n * so the hashing has one implementation rather than one per array. */\nexport function parseExternalEvidence(pkg: string): EvidenceContent[] {\n const doc = parseDocument(pkg, 'evidence package');\n return objectArray(doc.externalEvidence, 'evidence package', 'externalEvidence').map((e) => {\n const checksum = e.checksum;\n const isObject = typeof checksum === 'object' && checksum !== null;\n return {\n uri: str(e.uri),\n type: '',\n format: str(e.format),\n checksum: isObject ? str((checksum as RawObject).value) : '',\n checksumAlgorithm: isObject ? str((checksum as RawObject).algorithm) : '',\n checksumRecorded: isObject,\n };\n });\n}\n\n/** Verifies each content entry against fetch(uri) using the algorithm the entry\n * recorded, preserving entry order. No checksum → skipped; an algorithm this\n * build cannot compute → unsupported, never mismatch (that would say their evidence\n * changed when it did not) and never error, since the bytes may be intact; a fetch throw → error;\n * hash mismatch → mismatch (carrying expected+actual).\n *\n * Asynchronous because the SHA family is hashed through Web Crypto, which is what lets\n * this package bundle for the browser. */\nexport async function verifyChecksums(contents: EvidenceContent[], fetch: FetchFn): Promise<ChecksumResult[]> {\n const results: ChecksumResult[] = [];\n // One entry at a time, so only one fetched document is held in memory.\n for (const c of contents) {\n results.push(await verifyChecksum(c, fetch));\n }\n return results;\n}\n\nasync function verifyChecksum(c: EvidenceContent, fetch: FetchFn): Promise<ChecksumResult> {\n const r: ChecksumResult = { uri: c.uri, type: c.type, status: 'skipped' };\n if (c.format !== undefined && c.format !== '') {\n r.format = c.format;\n }\n if (c.checksum === '') {\n return r;\n }\n r.algorithm = effectiveAlgorithm(c.checksumAlgorithm);\n // The algorithm is checked before any IO: whether this build can compute it\n // is a property of the package, not of the filesystem.\n if (!supportedAlgorithm(c.checksumAlgorithm)) {\n return { ...r, status: 'unsupported', error: unsupportedAlgorithmMessage(c.checksumAlgorithm) };\n }\n let data: Uint8Array;\n try {\n data = fetch(c.uri);\n } catch (e) {\n return { ...r, status: 'error', error: e instanceof Error ? e.message : String(e) };\n }\n const actual = await checksumHex(c.checksumAlgorithm, data);\n if (actual === c.checksum) {\n return { ...r, status: 'match' };\n }\n return { ...r, status: 'mismatch', expected: c.checksum, actual };\n}\n\n/** Extracts assessment baselineRefs from a plan document, deduped in first-seen\n * order. */\nexport function plannedBaselineRefs(plan: string): string[] {\n const doc = parseDocument(plan, 'plan');\n const refs = objectArray(doc.assessments, 'plan', 'assessments')\n .map((a) => str(a.baselineRef))\n .filter((s) => s !== '');\n return dedupe(refs);\n}\n\n/** Extracts baseline names from a results document, deduped in first-seen order. */\nexport function coveredBaselineNames(results: string): string[] {\n const doc = parseDocument(results, 'results');\n const names = objectArray(doc.baselines, 'results', 'baselines')\n .map((b) => str(b.name))\n .filter((s) => s !== '');\n return dedupe(names);\n}\n\n/** Concatenates the covered baseline names of every hdf-results document the\n * package references, in entry order. An entry that cannot be fetched or parsed\n * is skipped: checksum verification is what reports a read failure, and a\n * partial coverage list is what the completeness diff needs. */\nexport function coveredBaselinesInPackage(contents: EvidenceContent[], fetch: FetchFn): string[] {\n const covered: string[] = [];\n forEachResultsDocument(contents, fetch, (text) => {\n try {\n covered.push(...coveredBaselineNames(text));\n } catch {\n return;\n }\n });\n return covered;\n}\n\n/** Sums the agent-attributed override count across every hdf-results document\n * the package references. Unreadable or unparseable entries are skipped. */\nexport function agentOverridesInPackage(contents: EvidenceContent[], fetch: FetchFn): number {\n let total = 0;\n forEachResultsDocument(contents, fetch, (text) => {\n try {\n total += agentOverrideCount(JSON.parse(text) as HDFResults);\n } catch {\n return;\n }\n });\n return total;\n}\n\n/** Fetches each referenced hdf-results document in entry order, skipping\n * entries that carry no uri or cannot be read. */\nfunction forEachResultsDocument(\n contents: EvidenceContent[],\n fetch: FetchFn,\n visit: (text: string) => void\n): void {\n for (const c of contents) {\n if (c.type !== 'hdf-results' || c.uri === '') {\n continue;\n }\n let data: Uint8Array;\n try {\n data = fetch(c.uri);\n } catch {\n continue;\n }\n visit(new TextDecoder().decode(data));\n }\n}\n\n/** Diffs planned baseline refs against covered baseline names. A planned ref is\n * covered when some results baseline shares its name. Missing is sorted so the\n * outcome is deterministic across languages and runs. */\nexport function completeness(planned: string[], covered: string[]): CompletenessResult {\n const coveredSet = new Set(covered);\n const missing = planned.filter((p) => !coveredSet.has(p)).sort();\n return { planned, covered, missing, complete: missing.length === 0 };\n}\n\n/** The algorithms this build can verify — every value Hash_Algorithm admits. An\n * algorithm outside the enum is refused by name rather than silently treated as\n * something else. Kept identical to Go's ChecksumHex. */\nconst SUPPORTED_ALGORITHMS = ['sha256', 'sha384', 'sha512', 'blake3'] as const;\n\n/** Names the algorithm an entry's checksum is verified under: an unstated\n * algorithm means sha256, so reporting '' would understate it. */\nfunction effectiveAlgorithm(recorded: string | undefined): string {\n return !recorded ? 'sha256' : recorded;\n}\n\nfunction supportedAlgorithm(algorithm: string | undefined): boolean {\n return !algorithm || (SUPPORTED_ALGORITHMS as readonly string[]).includes(algorithm);\n}\n\n/** Formats the algorithm list exactly as Go's ChecksumHex does, so the two languages\n * emit the SAME user-visible refusal rather than two spellings of it. */\nfunction algorithmList(): string {\n const all = SUPPORTED_ALGORITHMS as readonly string[];\n return `${all.slice(0, -1).join(', ')} and ${all[all.length - 1]}`;\n}\n\nfunction unsupportedAlgorithmMessage(algorithm: string | undefined): string {\n return `unsupported checksum algorithm \"${algorithm}\": this build computes ${algorithmList()}`;\n}\n\n/** Hashes data with the named Hash_Algorithm, hex-encoded. An empty algorithm\n * means sha256, so a package that records only a value keeps its meaning. Rejects\n * an algorithm this build cannot compute.\n *\n * The SHA family goes through the shared Web Crypto helper rather than node:crypto,\n * which is what lets this package bundle for the browser; blake3 has no Web Crypto\n * equivalent and keeps its own implementation. */\nexport async function checksumHex(algorithm: string | undefined, data: Uint8Array): Promise<string> {\n if (!supportedAlgorithm(algorithm)) {\n throw new Error(unsupportedAlgorithmMessage(algorithm));\n }\n if (algorithm === 'blake3') {\n // The 32-byte default-length digest is what the BLAKE3 reference vectors direct\n // implementations to compare.\n return bytesToHex(blake3(data));\n }\n return generateHash(data, { algorithm: (!algorithm ? 'sha256' : algorithm) as HashAlgorithm });\n}\n\n/**\n * Turns a recorded evidence reference into the path it names.\n *\n * A reference is a uri-reference — the schema says so on both `contents[].uri` and\n * `externalEvidence[].uri` — so its percent-escapes are part of the encoding, not part of\n * the name. The DECODED form is what the reference means. Before this, every consumer\n * treated the value as opaque bytes, so the legal spelling of a filename containing a\n * space failed while the illegal spelling worked: a producer following the declared\n * format wrote a package this toolchain could not read.\n *\n * ORDERING MATTERS AND THE CALLER OWNS IT. Decoding can CREATE a parent traversal —\n * `%2e%2e/x` becomes `../x` and `a%2Fb` gains a separator — so the decoded form, never the\n * raw one, is what a caller must put through its containment check.\n *\n * A value whose percent is not a valid escape cannot be decoded, and that throws rather\n * than being guessed at: falling back to the raw bytes would make resolution depend on\n * whether a filename happens to contain a `%`.\n *\n * Present here even though no TypeScript consumer resolves a reference to a filesystem\n * today — what a reference MEANS is language-independent, and a consumer that starts\n * resolving must not be free to disagree with Go. Pinned across both by\n * `testdata/reference-decode-vectors.json`.\n */\nexport function decodeReference(uri: string): string {\n if (uri === '') return '';\n // decodeURIComponent throws URIError on a malformed escape, which is the reporting\n // this contract wants; Go's url.PathUnescape returns an error for the same inputs.\n try {\n return decodeURIComponent(uri);\n } catch {\n throw new Error(`reference ${JSON.stringify(uri)} is not a valid uri-reference`);\n }\n}\n\nfunction dedupe(input: string[]): string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n for (const s of input) {\n if (!seen.has(s)) {\n seen.add(s);\n out.push(s);\n }\n }\n return out;\n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GAAG,EAAE,8BAA8B;CACjF;AACF;AAEA,SAAS,OAAO,OAA2B;CACzC,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,MAAgB,CAAC;CACvB,KAAK,MAAM,KAAK,OACd,IAAI,CAAC,KAAK,IAAI,CAAC,GAAG;EAChB,KAAK,IAAI,CAAC;EACV,IAAI,KAAK,CAAC;CACZ;CAEF,OAAO;AACT"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mitre/hdf-engine",
|
|
3
|
-
"version": "3.8.0-next.
|
|
3
|
+
"version": "3.8.0-next.42665732325.1",
|
|
4
4
|
"description": "Shared schema-typed read-side engines for HDF documents — detection, query/filtering, and compliance rollups",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -25,14 +25,14 @@
|
|
|
25
25
|
"author": "MITRE Corporation",
|
|
26
26
|
"license": "Apache-2.0",
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@mitre/hdf-parsers": "3.8.0-next.
|
|
29
|
-
"@mitre/hdf-schema": "3.8.0-next.
|
|
30
|
-
"@mitre/hdf-utilities": "3.8.0-next.
|
|
28
|
+
"@mitre/hdf-parsers": "3.8.0-next.42665732325.1",
|
|
29
|
+
"@mitre/hdf-schema": "3.8.0-next.42665732325.1",
|
|
30
|
+
"@mitre/hdf-utilities": "3.8.0-next.42665732325.1",
|
|
31
31
|
"@noble/hashes": "2.4.0"
|
|
32
32
|
},
|
|
33
33
|
"devDependencies": {
|
|
34
|
-
"@mitre/hdf-fixtures": "^3.8.0-next.
|
|
35
|
-
"@mitre/hdf-validators": "^3.8.0-next.
|
|
34
|
+
"@mitre/hdf-fixtures": "^3.8.0-next.42665732325.1",
|
|
35
|
+
"@mitre/hdf-validators": "^3.8.0-next.42665732325.1"
|
|
36
36
|
},
|
|
37
37
|
"engines": {
|
|
38
38
|
"node": ">=24.0.0"
|