@mitre/hdf-engine 3.6.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,55 @@
1
+ # License
2
+
3
+ Copyright © 2025 The MITRE Corporation.
4
+
5
+ Approved for Public Release; Distribution Unlimited. Case Number 18-3678.
6
+
7
+ Licensed under the Apache License, Version 2.0 (the "License"); you may
8
+ not use this file except in compliance with the License. You may obtain a
9
+ copy of the License at
10
+
11
+ http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ Unless required by applicable law or agreed to in writing, software
14
+ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15
+ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16
+ License for the specific language governing permissions and limitations
17
+ under the License.
18
+
19
+ ## Redistribution Terms
20
+
21
+ Redistribution and use in source and binary forms, with or without
22
+ modification, are permitted provided that the following conditions are
23
+ met:
24
+
25
+ - Redistributions of source code must retain the above copyright/digital
26
+ rights legend, this list of conditions and the following Notice.
27
+ - Redistributions in binary form must reproduce the above
28
+ copyright/digital rights legend, this list of conditions and the
29
+ following Notice in the documentation and/or other materials provided
30
+ with the distribution.
31
+ - Neither the name of The MITRE Corporation nor the names of its contributors
32
+ may be used to endorse or promote products derived from this software
33
+ without specific prior written permission.
34
+
35
+ ## Notice
36
+
37
+ The MITRE Corporation grants permission to reproduce, distribute, modify, and
38
+ otherwise use this software to the extent permitted by the licensed terms
39
+ provided in the LICENSE file included with this project.
40
+
41
+ This software was produced by The MITRE Corporation for the U.S. Government
42
+ under contract. As such the U.S. Government has certain use and data
43
+ rights in this software. No use other than those granted to the U.S.
44
+ Government, or to those acting on behalf of the U.S. Government, under
45
+ these contract arrangements is authorized without the express written
46
+ permission of The MITRE Corporation.
47
+
48
+ Some files in this codebase were generated by generative AI, under the
49
+ direction and review of The MITRE Corporation employees, for the purpose of
50
+ development efficiency. All AI-generated code functionality was validated
51
+ by standard quality and assurance testing.
52
+
53
+ For further information, please contact The MITRE Corporation,
54
+ Contracts Management Office, 7515 Colshire Drive, McLean, VA 22102-7539,
55
+ (703) 983-6000.
package/README.md ADDED
@@ -0,0 +1,7 @@
1
+ # @mitre/hdf-engine
2
+
3
+ Shared, schema-typed read-side engines for Heimdall Data Format (HDF) documents — document-type **detection**, requirement **query/filtering**, and **compliance** rollups (with more read-side engines to follow).
4
+
5
+ It sits above `@mitre/hdf-schema` (types) and `@mitre/hdf-utilities` (schema-free primitives) and is consumed as a library by both the `hdf` CLI and the HDF MCP server — neither owns the engines. It is a sibling to `@mitre/hdf-diff` (which owns diff / change-events / amend); see `dev-docs/adr-0007-hdf-mcp-server.md`.
6
+
7
+ Dual-language: TypeScript (`@mitre/hdf-engine`) and Go (`github.com/mitre/hdf-libs/hdf-engine/go/v3`), kept at parity.
@@ -0,0 +1,232 @@
1
+ import { EvaluatedRequirement, HDFBaseline, HDFResults, RequirementResult, Severity } from "@mitre/hdf-schema";
2
+ //#region src/detect.d.ts
3
+ /** The eight HDF document type strings, matching validators.Type* in Go. */
4
+ type HdfDocType = 'results' | 'baseline' | 'system' | 'plan' | 'amendments' | 'evidence-package' | 'comparison' | 'requirement-change-event' | '';
5
+ /**
6
+ * Detect fingerprints an HDF document by its root keys and returns the schema
7
+ * type string, or '' when the input is not a JSON object or matches no known
8
+ * HDF document type.
9
+ */
10
+ declare function detect(input: string): HdfDocType;
11
+ //#endregion
12
+ //#region src/query.d.ts
13
+ /**
14
+ * FilterOptions configures a requirements query. Every filter input arrives here;
15
+ * distinct filters combine with AND, repeated values within a filter with OR.
16
+ * statusOf resolves a requirement's display status, injected so the engine stays
17
+ * agnostic to the caller's status-string convention (undefined → empty status).
18
+ */
19
+ interface FilterOptions {
20
+ status?: string[];
21
+ severity?: string[];
22
+ impact?: string;
23
+ cci?: string[];
24
+ nist?: string[];
25
+ id?: string;
26
+ tag?: string[];
27
+ search?: string;
28
+ baseline?: string;
29
+ limit?: number;
30
+ count?: boolean;
31
+ statusOf?: (control: EvaluatedRequirement) => string;
32
+ }
33
+ /** A single query result row. */
34
+ interface Match {
35
+ id: string;
36
+ title: string;
37
+ status: string;
38
+ impact: number;
39
+ severity: string;
40
+ baseline: string;
41
+ }
42
+ /**
43
+ * filter returns the requirements across the result set's baselines that satisfy
44
+ * options. Applies to requirement collections (results/baseline documents); the
45
+ * calling adapter rejects document types that carry no requirements.
46
+ */
47
+ declare function filter(results: HDFResults, options: FilterOptions): Match[];
48
+ //#endregion
49
+ //#region src/loader.d.ts
50
+ /** Wire encoding of loader input (parity with Go InputFormat). */
51
+ type InputFormat = 'json' | 'ndjson';
52
+ interface LoadResult {
53
+ format: InputFormat;
54
+ docType: HdfDocType;
55
+ results?: HDFResults;
56
+ baseline?: HDFBaseline;
57
+ /** Non-empty when detected as results/baseline but the parse/validate failed. */
58
+ parseError?: string;
59
+ valid: boolean;
60
+ }
61
+ /**
62
+ * load is the schema-typed loader core. In order: validateInputSize (FIRST,
63
+ * before any parse; maxSize <= 0 uses the default), wire-format detection
64
+ * (JSON vs NDJSON), document-type detection (detect), then the canonical
65
+ * hdf-parsers parse for the results and baseline types. Other types are
66
+ * detected but not parsed here.
67
+ */
68
+ declare function load(input: string | Uint8Array, maxSize?: number): LoadResult;
69
+ /**
70
+ * detectFormat classifies input as a single JSON document or newline-delimited
71
+ * JSON, consistent with the Go core: NDJSON is two or more non-blank lines that
72
+ * each independently parse as a complete JSON value. A pretty-printed single
73
+ * object stays 'json' (its first line is not itself a complete JSON value).
74
+ */
75
+ declare function detectFormat(text: string): InputFormat;
76
+ //#endregion
77
+ //#region src/evidence.d.ts
78
+ /** Classifies a single content entry's checksum verification. */
79
+ type ChecksumStatus = 'match' | 'mismatch' | 'skipped' | 'error';
80
+ /** One content entry of an evidence package: a referenced document and its
81
+ * recorded checksum ('' when the entry carries none). */
82
+ interface EvidenceContent {
83
+ uri: string;
84
+ type: string;
85
+ checksum: string;
86
+ }
87
+ /** The verification outcome for one content entry. */
88
+ interface ChecksumResult {
89
+ uri: string;
90
+ type: string;
91
+ status: ChecksumStatus;
92
+ expected?: string;
93
+ actual?: string;
94
+ error?: string;
95
+ }
96
+ /** Reports which planned baselines are covered by results. */
97
+ interface CompletenessResult {
98
+ planned: string[];
99
+ covered: string[];
100
+ missing: string[];
101
+ complete: boolean;
102
+ }
103
+ /** Resolves a content URI to its bytes. The caller owns path confinement
104
+ * (HDF_MCP_ROOT for the MCP, the package directory for the CLI). Throws when the
105
+ * uri cannot be read. */
106
+ type FetchFn = (uri: string) => Uint8Array;
107
+ /** Extracts the planRef and content entries from an evidence-package document. */
108
+ declare function parseEvidencePackage(pkg: string): {
109
+ planRef: string;
110
+ contents: EvidenceContent[];
111
+ };
112
+ /** Verifies each content entry's sha256 against fetch(uri), preserving entry
113
+ * order. No checksum → skipped; a fetch throw → error; hash mismatch → mismatch
114
+ * (carrying expected+actual). */
115
+ declare function verifyChecksums(contents: EvidenceContent[], fetch: FetchFn): ChecksumResult[];
116
+ /** Extracts assessment baselineRefs from a plan document, deduped in first-seen
117
+ * order. */
118
+ declare function plannedBaselineRefs(plan: string): string[];
119
+ /** Extracts baseline names from a results document, deduped in first-seen order. */
120
+ declare function coveredBaselineNames(results: string): string[];
121
+ /** Diffs planned baseline refs against covered baseline names. A planned ref is
122
+ * covered when some results baseline shares its name. Missing is sorted so the
123
+ * outcome is deterministic across languages and runs. */
124
+ declare function completeness(planned: string[], covered: string[]): CompletenessResult;
125
+ //#endregion
126
+ //#region src/compliance.d.ts
127
+ interface SeverityCounts {
128
+ critical: number;
129
+ high: number;
130
+ medium: number;
131
+ low: number;
132
+ none: number;
133
+ total: number;
134
+ }
135
+ interface StatusCounts {
136
+ passed: SeverityCounts;
137
+ failed: SeverityCounts;
138
+ skipped: SeverityCounts;
139
+ error: SeverityCounts;
140
+ noImpact: SeverityCounts;
141
+ }
142
+ interface ControlIDMapping {
143
+ id: string;
144
+ status: string;
145
+ severity: string;
146
+ }
147
+ interface ThresholdBound {
148
+ min?: number;
149
+ max?: number;
150
+ controls?: string[];
151
+ }
152
+ interface ThresholdSeverity {
153
+ critical?: ThresholdBound;
154
+ high?: ThresholdBound;
155
+ medium?: ThresholdBound;
156
+ low?: ThresholdBound;
157
+ none?: ThresholdBound;
158
+ total?: ThresholdBound;
159
+ }
160
+ interface ComplianceBound {
161
+ min?: number;
162
+ max?: number;
163
+ }
164
+ interface ThresholdConfig {
165
+ compliance?: ComplianceBound;
166
+ passed?: ThresholdSeverity;
167
+ failed?: ThresholdSeverity;
168
+ skipped?: ThresholdSeverity;
169
+ error?: ThresholdSeverity;
170
+ noImpact?: ThresholdSeverity;
171
+ }
172
+ /**
173
+ * overallStatus is the canonical worst-wins roll-up of a requirement's result
174
+ * statuses, delegated to @mitre/hdf-utilities worstStatus (error > failed >
175
+ * passed > notApplicable > notReviewed; empty → notReviewed). No local rank
176
+ * switch — the TS peer of the Go overallStatus dedup (supersedes hdf-libs-ixhx).
177
+ */
178
+ declare function overallStatus(results: RequirementResult[]): string;
179
+ /**
180
+ * deriveSeverity determines the severity string from impact and optional explicit
181
+ * severity, using impactToSeverity. Maps "informational" to "none".
182
+ */
183
+ declare function deriveSeverity(impact: number, severity?: Severity | null): string;
184
+ /** CountControlsByStatusSeverity counts requirements by overall status and severity. */
185
+ declare function countControlsByStatusSeverity(results: HDFResults): StatusCounts;
186
+ /**
187
+ * countControlsByStatus counts requirements by a caller-resolved status — the
188
+ * injected-resolver twin of countControlsByStatusSeverity (which counts raw
189
+ * result statuses with no override awareness). statusOf returns each
190
+ * requirement's status in the schema vocabulary (passed/failed/notApplicable/
191
+ * notReviewed/error); an empty or unrecognized value counts as skipped, and an
192
+ * absent resolver yields all-skipped. Callers build effective-status rollups
193
+ * (e.g. compliance with and without agent-attributed overrides) without the
194
+ * engine binding to any one status convention. Parity: go/compliance.go.
195
+ */
196
+ declare function countControlsByStatus(results: HDFResults, statusOf?: (req: EvaluatedRequirement) => string): StatusCounts;
197
+ /**
198
+ * agentOverrideCount counts the status overrides across a result set whose
199
+ * applied-by identity type is "agent" — the detective count. Deterministic
200
+ * from_vex/system overrides are excluded so the count is a meaningful AI-scrutiny
201
+ * signal. Parity: go/compliance.go AgentOverrideCount.
202
+ */
203
+ declare function agentOverrideCount(results: HDFResults): number;
204
+ /** MapControlIDs builds control ID → status/severity mappings from a result set. */
205
+ declare function mapControlIDs(results: HDFResults): ControlIDMapping[];
206
+ /**
207
+ * mapControlIDsByStatus builds control ID → status/severity mappings using a
208
+ * caller-resolved status — the injected-resolver twin of mapControlIDs (which
209
+ * maps raw result statuses). statusOf returns each requirement's status in the
210
+ * schema vocabulary; an empty or unrecognized value maps to skipped, and an
211
+ * absent resolver yields all-skipped. Callers build effective-status control
212
+ * listings (the same injection pattern as countControlsByStatus). Parity:
213
+ * go/compliance.go MapControlIDsByStatus.
214
+ */
215
+ declare function mapControlIDsByStatus(results: HDFResults, statusOf?: (req: EvaluatedRequirement) => string): ControlIDMapping[];
216
+ /**
217
+ * calculateCompliance returns the compliance percentage rounded to two decimals:
218
+ * passed / (passed + failed + skipped + error) * 100; notApplicable excluded.
219
+ */
220
+ declare function calculateCompliance(counts: StatusCounts): number;
221
+ /**
222
+ * validateThresholds checks all threshold bounds against observed counts and
223
+ * compliance, returning human-readable violation messages (empty when all pass).
224
+ */
225
+ declare function validateThresholds(config: ThresholdConfig, counts: StatusCounts, compliance: number, controlMap: ControlIDMapping[]): string[];
226
+ //#endregion
227
+ //#region src/index.d.ts
228
+ /** Library version, kept on the workspace lockstep. */
229
+ declare const engineVersion = "3.5.0";
230
+ //#endregion
231
+ export { type ChecksumResult, type ChecksumStatus, type CompletenessResult, type ComplianceBound, type ControlIDMapping, type EvidenceContent, type FetchFn, type FilterOptions, type HdfDocType, type InputFormat, type LoadResult, type Match, type SeverityCounts, type StatusCounts, type ThresholdBound, type ThresholdConfig, type ThresholdSeverity, agentOverrideCount, calculateCompliance, completeness, countControlsByStatus, countControlsByStatusSeverity, coveredBaselineNames, deriveSeverity, detect, detectFormat, engineVersion, filter, load, mapControlIDs, mapControlIDsByStatus, overallStatus, parseEvidencePackage, plannedBaselineRefs, validateThresholds, verifyChecksums };
232
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/detect.ts","../src/query.ts","../src/loader.ts","../src/evidence.ts","../src/compliance.ts","../src/index.ts"],"mappings":";;;KAOY;;;;;;iBAgBI,OAAO,gBAAgB;;;;;;;;;UCRtB;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,YAAY,SAAS;;;UAIN;EACf;EACA;EACA;EACA;EACA;EACA;;;;;;;iBAUc,OAAO,SAAS,YAAY,SAAS,gBAAgB;;;;KClCzD;UAEK;EACf,QAAQ;EACR,SAAS;EACT,UAAU;EACV,WAAW;;EAEX;EACA;;;;;;;;;iBAUc,KAAK,gBAAgB,YAAY,mBAAc;;;;;;;iBAqC/C,aAAa,eAAe;;;;KC3DhC;;;UAIK;EACf;EACA;EACA;;;UAIe;EACf;EACA;EACA,QAAQ;EACR;EACA;EACA;;;UAIe;EACf;EACA;EACA;EACA;;;;;KAMU,WAAW,gBAAgB;;iBASvB,qBAAqB;EAAgB;EAAiB,UAAU;;;;;iBAahE,gBAAgB,UAAU,mBAAmB,OAAO,UAAU;;;iBAsB9D,oBAAoB;;iBAOpB,qBAAqB;;;;iBASrB,aAAa,mBAAmB,oBAAoB;;;UCtFnD;EACf;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf,QAAQ;EACR,QAAQ;EACR,SAAS;EACT,OAAO;EACP,UAAU;;UAGK;EACf;EACA;EACA;;UAGe;EACf;EACA;EACA;;UAGe;EACf,WAAW;EACX,OAAO;EACP,SAAS;EACT,MAAM;EACN,OAAO;EACP,QAAQ;;UAGO;EACf;EACA;;UAGe;EACf,aAAa;EACb,SAAS;EACT,SAAS;EACT,UAAU;EACV,QAAQ;EACR,WAAW;;;;;;;;iBAuBG,cAAc,SAAS;;;;;iBAQvB,eAAe,gBAAgB,WAAW;;iBAoE1C,8BAA8B,SAAS,aAAa;;;;;;;;;;;iBAoBpD,sBACd,SAAS,YACT,YAAY,KAAK,kCAChB;;;;;;;iBAiBa,mBAAmB,SAAS;;iBAe5B,cAAc,SAAS,aAAa;;;;;;;;;;iBAwBpC,sBACd,SAAS,YACT,YAAY,KAAK,kCAChB;;;;;iBAuBa,oBAAoB,QAAQ;;;;;iBAa5B,mBACd,QAAQ,iBACR,QAAQ,cACR,oBACA,YAAY;;;;cCxRD"}
package/dist/index.js ADDED
@@ -0,0 +1,560 @@
1
+ import { impactToSeverity, validateInputSize, worstStatus } from "@mitre/hdf-utilities";
2
+ import { parseBaseline, parseResults } from "@mitre/hdf-parsers";
3
+ import { createHash } from "node:crypto";
4
+ //#region src/detect.ts
5
+ /**
6
+ * Detect fingerprints an HDF document by its root keys and returns the schema
7
+ * type string, or '' when the input is not a JSON object or matches no known
8
+ * HDF document type.
9
+ */
10
+ function detect(input) {
11
+ let parsed;
12
+ try {
13
+ parsed = JSON.parse(input);
14
+ } catch {
15
+ return "";
16
+ }
17
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return "";
18
+ const doc = parsed;
19
+ const has = (...keys) => keys.every((k) => Object.prototype.hasOwnProperty.call(doc, k));
20
+ if (has("requirementId", "state", "before", "after")) return "requirement-change-event";
21
+ if (has("contents")) return "evidence-package";
22
+ if (has("overrides")) return "amendments";
23
+ if (has("assessments")) return "plan";
24
+ if (has("comparisonMode")) return "comparison";
25
+ if (has("baselines")) return "results";
26
+ if (has("components")) return "system";
27
+ if (has("requirements")) return "baseline";
28
+ return "";
29
+ }
30
+ //#endregion
31
+ //#region src/compliance.ts
32
+ /** Threshold status-key constants (SAF CLI-compatible keys). */
33
+ const THRESHOLD_PASSED = "passed";
34
+ const THRESHOLD_FAILED = "failed";
35
+ const THRESHOLD_SKIPPED = "skipped";
36
+ const THRESHOLD_ERROR = "error";
37
+ const THRESHOLD_NO_IMPACT = "no_impact";
38
+ function newSeverityCounts() {
39
+ return {
40
+ critical: 0,
41
+ high: 0,
42
+ medium: 0,
43
+ low: 0,
44
+ none: 0,
45
+ total: 0
46
+ };
47
+ }
48
+ function newStatusCounts() {
49
+ return {
50
+ passed: newSeverityCounts(),
51
+ failed: newSeverityCounts(),
52
+ skipped: newSeverityCounts(),
53
+ error: newSeverityCounts(),
54
+ noImpact: newSeverityCounts()
55
+ };
56
+ }
57
+ /**
58
+ * overallStatus is the canonical worst-wins roll-up of a requirement's result
59
+ * statuses, delegated to @mitre/hdf-utilities worstStatus (error > failed >
60
+ * passed > notApplicable > notReviewed; empty → notReviewed). No local rank
61
+ * switch — the TS peer of the Go overallStatus dedup (supersedes hdf-libs-ixhx).
62
+ */
63
+ function overallStatus(results) {
64
+ return worstStatus(results.map((r) => String(r.status)));
65
+ }
66
+ /**
67
+ * deriveSeverity determines the severity string from impact and optional explicit
68
+ * severity, using impactToSeverity. Maps "informational" to "none".
69
+ */
70
+ function deriveSeverity(impact, severity) {
71
+ if (severity != null) return String(severity);
72
+ const sev = impactToSeverity(impact);
73
+ return sev === "informational" ? "none" : sev;
74
+ }
75
+ function statusBucket(counts, status) {
76
+ switch (status) {
77
+ case "passed": return counts.passed;
78
+ case "failed": return counts.failed;
79
+ case "error": return counts.error;
80
+ case "notApplicable": return counts.noImpact;
81
+ case "notReviewed": return counts.skipped;
82
+ default: return counts.skipped;
83
+ }
84
+ }
85
+ function addCount(counts, status, severity) {
86
+ const sc = statusBucket(counts, status);
87
+ sc.total++;
88
+ switch (severity) {
89
+ case "critical":
90
+ sc.critical++;
91
+ break;
92
+ case "high":
93
+ sc.high++;
94
+ break;
95
+ case "medium":
96
+ sc.medium++;
97
+ break;
98
+ case "low":
99
+ sc.low++;
100
+ break;
101
+ default: sc.none++;
102
+ }
103
+ }
104
+ function statusToThresholdKey(status) {
105
+ switch (status) {
106
+ case "passed": return THRESHOLD_PASSED;
107
+ case "failed": return THRESHOLD_FAILED;
108
+ case "notReviewed": return THRESHOLD_SKIPPED;
109
+ case "error": return THRESHOLD_ERROR;
110
+ case "notApplicable": return THRESHOLD_NO_IMPACT;
111
+ default: return THRESHOLD_SKIPPED;
112
+ }
113
+ }
114
+ /** CountControlsByStatusSeverity counts requirements by overall status and severity. */
115
+ function countControlsByStatusSeverity(results) {
116
+ const counts = newStatusCounts();
117
+ for (const baseline of results.baselines ?? []) for (const req of baseline.requirements ?? []) addCount(counts, overallStatus(req.results ?? []), deriveSeverity(req.impact, reqSeverity(req)));
118
+ return counts;
119
+ }
120
+ /**
121
+ * countControlsByStatus counts requirements by a caller-resolved status — the
122
+ * injected-resolver twin of countControlsByStatusSeverity (which counts raw
123
+ * result statuses with no override awareness). statusOf returns each
124
+ * requirement's status in the schema vocabulary (passed/failed/notApplicable/
125
+ * notReviewed/error); an empty or unrecognized value counts as skipped, and an
126
+ * absent resolver yields all-skipped. Callers build effective-status rollups
127
+ * (e.g. compliance with and without agent-attributed overrides) without the
128
+ * engine binding to any one status convention. Parity: go/compliance.go.
129
+ */
130
+ function countControlsByStatus(results, statusOf) {
131
+ const counts = newStatusCounts();
132
+ for (const baseline of results.baselines ?? []) for (const req of baseline.requirements ?? []) addCount(counts, statusOf ? statusOf(req) : "", deriveSeverity(req.impact, reqSeverity(req)));
133
+ return counts;
134
+ }
135
+ /**
136
+ * agentOverrideCount counts the status overrides across a result set whose
137
+ * applied-by identity type is "agent" — the detective count. Deterministic
138
+ * from_vex/system overrides are excluded so the count is a meaningful AI-scrutiny
139
+ * signal. Parity: go/compliance.go AgentOverrideCount.
140
+ */
141
+ function agentOverrideCount(results) {
142
+ let count = 0;
143
+ for (const baseline of results.baselines ?? []) for (const req of baseline.requirements ?? []) for (const o of req.statusOverrides ?? []) if (o.appliedBy?.type === "agent") count++;
144
+ return count;
145
+ }
146
+ /** MapControlIDs builds control ID → status/severity mappings from a result set. */
147
+ function mapControlIDs(results) {
148
+ const mappings = [];
149
+ for (const baseline of results.baselines ?? []) for (const req of baseline.requirements ?? []) {
150
+ const status = overallStatus(req.results ?? []);
151
+ mappings.push({
152
+ id: req.id,
153
+ status: statusToThresholdKey(status),
154
+ severity: deriveSeverity(req.impact, reqSeverity(req))
155
+ });
156
+ }
157
+ return mappings;
158
+ }
159
+ /**
160
+ * mapControlIDsByStatus builds control ID → status/severity mappings using a
161
+ * caller-resolved status — the injected-resolver twin of mapControlIDs (which
162
+ * maps raw result statuses). statusOf returns each requirement's status in the
163
+ * schema vocabulary; an empty or unrecognized value maps to skipped, and an
164
+ * absent resolver yields all-skipped. Callers build effective-status control
165
+ * listings (the same injection pattern as countControlsByStatus). Parity:
166
+ * go/compliance.go MapControlIDsByStatus.
167
+ */
168
+ function mapControlIDsByStatus(results, statusOf) {
169
+ const mappings = [];
170
+ for (const baseline of results.baselines ?? []) for (const req of baseline.requirements ?? []) {
171
+ const status = statusOf ? statusOf(req) : "";
172
+ mappings.push({
173
+ id: req.id,
174
+ status: statusToThresholdKey(status),
175
+ severity: deriveSeverity(req.impact, reqSeverity(req))
176
+ });
177
+ }
178
+ return mappings;
179
+ }
180
+ function reqSeverity(req) {
181
+ return req.severity ?? null;
182
+ }
183
+ /**
184
+ * calculateCompliance returns the compliance percentage rounded to two decimals:
185
+ * passed / (passed + failed + skipped + error) * 100; notApplicable excluded.
186
+ */
187
+ function calculateCompliance(counts) {
188
+ const relevant = counts.passed.total + counts.failed.total + counts.skipped.total + counts.error.total;
189
+ if (relevant === 0) return 0;
190
+ const pct = counts.passed.total / relevant * 100;
191
+ return Math.round(pct * 100) / 100;
192
+ }
193
+ /**
194
+ * validateThresholds checks all threshold bounds against observed counts and
195
+ * compliance, returning human-readable violation messages (empty when all pass).
196
+ */
197
+ function validateThresholds(config, counts, compliance, controlMap) {
198
+ const violations = [];
199
+ const actualControls = /* @__PURE__ */ new Map();
200
+ for (const m of controlMap) actualControls.set(m.id, m);
201
+ if (config.compliance) {
202
+ if (config.compliance.min !== void 0 && compliance < config.compliance.min) violations.push(`compliance ${compliance.toFixed(2)}% is below minimum ${config.compliance.min.toFixed(2)}%`);
203
+ if (config.compliance.max !== void 0 && compliance > config.compliance.max) violations.push(`compliance ${compliance.toFixed(2)}% exceeds maximum ${config.compliance.max.toFixed(2)}%`);
204
+ }
205
+ violations.push(...checkSeverityThreshold(THRESHOLD_PASSED, config.passed, counts.passed, actualControls));
206
+ violations.push(...checkSeverityThreshold(THRESHOLD_FAILED, config.failed, counts.failed, actualControls));
207
+ violations.push(...checkSeverityThreshold(THRESHOLD_SKIPPED, config.skipped, counts.skipped, actualControls));
208
+ violations.push(...checkSeverityThreshold(THRESHOLD_ERROR, config.error, counts.error, actualControls));
209
+ violations.push(...checkSeverityThreshold(THRESHOLD_NO_IMPACT, config.noImpact, counts.noImpact, actualControls));
210
+ return violations;
211
+ }
212
+ function checkSeverityThreshold(status, threshold, actual, actualControls) {
213
+ if (!threshold) return [];
214
+ const violations = [];
215
+ const check = (label, bound, actualCount) => {
216
+ if (!bound) return;
217
+ const path = `${status}.${label}`;
218
+ if (bound.min !== void 0 && actualCount < bound.min) violations.push(`${path}: ${actualCount} is below minimum ${bound.min}`);
219
+ if (bound.max !== void 0 && actualCount > bound.max) violations.push(`${path}: ${actualCount} exceeds maximum ${bound.max}`);
220
+ for (const expectedID of bound.controls ?? []) {
221
+ const ac = actualControls.get(expectedID);
222
+ if (!ac) violations.push(`${path}: expected control ${expectedID} not found in results`);
223
+ else if (ac.status !== status || ac.severity !== label) violations.push(`${path}: control ${expectedID} expected ${status}/${label} but found ${ac.status}/${ac.severity}`);
224
+ }
225
+ };
226
+ check("critical", threshold.critical, actual.critical);
227
+ check("high", threshold.high, actual.high);
228
+ check("medium", threshold.medium, actual.medium);
229
+ check("low", threshold.low, actual.low);
230
+ check("none", threshold.none, actual.none);
231
+ check("total", threshold.total, actual.total);
232
+ return violations;
233
+ }
234
+ //#endregion
235
+ //#region src/safematch.ts
236
+ const MAX_PATTERN_LENGTH = 256;
237
+ const REGEX_SPECIAL = /* @__PURE__ */ new Set([
238
+ ".",
239
+ "+",
240
+ "^",
241
+ "$",
242
+ "(",
243
+ ")",
244
+ "[",
245
+ "]",
246
+ "{",
247
+ "}",
248
+ "|",
249
+ "\\"
250
+ ]);
251
+ /**
252
+ * globToRegex converts a glob pattern (with * and ? wildcards) to an anchored
253
+ * regular expression, escaping every other regex metacharacter exactly once. A
254
+ * single pass avoids re-escaping the backslash introduced by escaping an earlier
255
+ * metacharacter (the doubled-backslash defect that made any dotted pattern match
256
+ * nothing).
257
+ */
258
+ function globToRegex(glob) {
259
+ let result = "^";
260
+ for (const ch of glob) if (ch === "*") result += ".*";
261
+ else if (ch === "?") result += ".";
262
+ else if (REGEX_SPECIAL.has(ch)) result += "\\" + ch;
263
+ else result += ch;
264
+ return result + "$";
265
+ }
266
+ /**
267
+ * safeGlobMatch converts a glob pattern to a regex and matches case-insensitively.
268
+ * Returns false for over-length or invalid patterns (fail-safe), mirroring the
269
+ * Go matcher's length cap and error handling.
270
+ */
271
+ const byteEncoder = new TextEncoder();
272
+ /** byteLength returns the UTF-8 byte length, matching Go's len(string). */
273
+ function byteLength(s) {
274
+ return byteEncoder.encode(s).length;
275
+ }
276
+ function safeGlobMatch(s, pattern) {
277
+ if (byteLength(pattern) > MAX_PATTERN_LENGTH) return false;
278
+ const rx = globToRegex(pattern);
279
+ if (byteLength(rx) > MAX_PATTERN_LENGTH) return false;
280
+ let re;
281
+ try {
282
+ re = new RegExp(rx, "i");
283
+ } catch {
284
+ return false;
285
+ }
286
+ return re.test(s);
287
+ }
288
+ //#endregion
289
+ //#region src/query.ts
290
+ /**
291
+ * filter returns the requirements across the result set's baselines that satisfy
292
+ * options. Applies to requirement collections (results/baseline documents); the
293
+ * calling adapter rejects document types that carry no requirements.
294
+ */
295
+ function filter(results, options) {
296
+ const filters = buildFilters(options);
297
+ const matches = [];
298
+ for (const baseline of results.baselines ?? []) {
299
+ if (options.baseline && !matchesGlob(baseline.name, options.baseline)) continue;
300
+ for (const control of baseline.requirements ?? []) {
301
+ if (options.limit && options.limit > 0 && matches.length >= options.limit && !options.count) return matches;
302
+ const status = options.statusOf ? options.statusOf(control) : "";
303
+ const severity = deriveSeverity(control.impact, control.severity ?? null);
304
+ if (!applyFilters(control, status, severity, filters)) continue;
305
+ matches.push({
306
+ id: control.id,
307
+ title: control.title ?? "",
308
+ status,
309
+ impact: control.impact,
310
+ severity,
311
+ baseline: baseline.name
312
+ });
313
+ }
314
+ }
315
+ return matches;
316
+ }
317
+ function buildFilters(options) {
318
+ const filters = [];
319
+ if (options.status && options.status.length > 0) {
320
+ const statuses = options.status.map((s) => s.toLowerCase());
321
+ filters.push((_c, s) => statuses.includes(s.toLowerCase()));
322
+ }
323
+ if (options.severity && options.severity.length > 0) {
324
+ const severities = options.severity.map((s) => s.toLowerCase());
325
+ filters.push((_c, _s, severity) => severities.includes(severity));
326
+ }
327
+ if (options.impact) {
328
+ const [op, val] = parseImpactFilter(options.impact);
329
+ filters.push((c) => compareImpact(c.impact, op, val));
330
+ }
331
+ if (options.cci && options.cci.length > 0) {
332
+ const ccis = options.cci.map((c) => c.toUpperCase());
333
+ filters.push((c) => ccis.some((cci) => tagContains(c.tags, "cci", cci)));
334
+ }
335
+ if (options.nist && options.nist.length > 0) {
336
+ const nist = options.nist;
337
+ filters.push((c) => nist.some((n) => tagMatchesGlob(c.tags, "nist", n)));
338
+ }
339
+ if (options.id) {
340
+ const id = options.id;
341
+ filters.push((c) => tagContains(c.tags, "stig_id", id) || tagContains(c.tags, "gid", id) || tagContains(c.tags, "gtitle", id) || c.id === id);
342
+ }
343
+ if (options.tag && options.tag.length > 0) {
344
+ const tagFilters = [];
345
+ for (const t of options.tag) {
346
+ const idx = t.indexOf(":");
347
+ if (idx >= 0) tagFilters.push({
348
+ key: t.slice(0, idx),
349
+ value: t.slice(idx + 1)
350
+ });
351
+ }
352
+ if (tagFilters.length > 0) filters.push((c) => tagFilters.some((tf) => tagMatchesGlob(c.tags, tf.key, tf.value)));
353
+ }
354
+ if (options.search) {
355
+ const search = options.search.toLowerCase();
356
+ filters.push((c) => {
357
+ if (c.id.toLowerCase().includes(search)) return true;
358
+ if (c.title && c.title.toLowerCase().includes(search)) return true;
359
+ for (const desc of c.descriptions ?? []) if (desc.data.toLowerCase().includes(search)) return true;
360
+ return false;
361
+ });
362
+ }
363
+ return filters;
364
+ }
365
+ function applyFilters(control, status, severity, filters) {
366
+ return filters.every((f) => f(control, status, severity));
367
+ }
368
+ const DECIMAL_FLOAT = /^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/;
369
+ function parseDecimal(s) {
370
+ if (!DECIMAL_FLOAT.test(s)) return null;
371
+ const v = Number(s);
372
+ return Number.isFinite(v) ? v : null;
373
+ }
374
+ function parseImpactFilter(f) {
375
+ const trimmed = f.trim();
376
+ for (const op of [
377
+ ">=",
378
+ "<=",
379
+ ">",
380
+ "<",
381
+ "="
382
+ ]) if (trimmed.startsWith(op)) {
383
+ const v = parseDecimal(trimmed.slice(op.length).trim());
384
+ return v === null ? ["=", NaN] : [op, v];
385
+ }
386
+ const v = parseDecimal(trimmed);
387
+ return v === null ? ["=", NaN] : ["=", v];
388
+ }
389
+ function compareImpact(impact, op, val) {
390
+ switch (op) {
391
+ case ">": return impact > val;
392
+ case ">=": return impact >= val;
393
+ case "<": return impact < val;
394
+ case "<=": return impact <= val;
395
+ case "=": return impact === val;
396
+ default: return false;
397
+ }
398
+ }
399
+ function tagContains(tags, key, value) {
400
+ const tagVal = tags?.[key];
401
+ if (tagVal === void 0) return false;
402
+ const want = value.toLowerCase();
403
+ if (typeof tagVal === "string") return tagVal.toLowerCase() === want;
404
+ if (Array.isArray(tagVal)) return tagVal.some((item) => typeof item === "string" && item.toLowerCase() === want);
405
+ return false;
406
+ }
407
+ function tagMatchesGlob(tags, key, pattern) {
408
+ const tagVal = tags?.[key];
409
+ if (tagVal === void 0) return false;
410
+ if (typeof tagVal === "string") return safeGlobMatch(tagVal, pattern);
411
+ if (Array.isArray(tagVal)) return tagVal.some((item) => typeof item === "string" && safeGlobMatch(item, pattern));
412
+ return false;
413
+ }
414
+ /** matchesGlob reports whether s matches the glob pattern (case-insensitive). */
415
+ function matchesGlob(s, pattern) {
416
+ return safeGlobMatch(s, pattern);
417
+ }
418
+ //#endregion
419
+ //#region src/loader.ts
420
+ /**
421
+ * load is the schema-typed loader core. In order: validateInputSize (FIRST,
422
+ * before any parse; maxSize <= 0 uses the default), wire-format detection
423
+ * (JSON vs NDJSON), document-type detection (detect), then the canonical
424
+ * hdf-parsers parse for the results and baseline types. Other types are
425
+ * detected but not parsed here.
426
+ */
427
+ function load(input, maxSize = 0) {
428
+ validateInputSize(input, maxSize);
429
+ const text = typeof input === "string" ? input : new TextDecoder().decode(input);
430
+ const result = {
431
+ format: detectFormat(text),
432
+ docType: detect(text),
433
+ valid: false
434
+ };
435
+ if (result.docType === "results") {
436
+ const r = parseResults(text);
437
+ if (r.success && r.data) {
438
+ result.results = r.data;
439
+ result.valid = true;
440
+ } else result.parseError = r.error;
441
+ } else if (result.docType === "baseline") {
442
+ const r = parseBaseline(text);
443
+ if (r.success && r.data) {
444
+ result.baseline = r.data;
445
+ result.valid = true;
446
+ } else result.parseError = r.error;
447
+ }
448
+ return result;
449
+ }
450
+ /**
451
+ * detectFormat classifies input as a single JSON document or newline-delimited
452
+ * JSON, consistent with the Go core: NDJSON is two or more non-blank lines that
453
+ * each independently parse as a complete JSON value. A pretty-printed single
454
+ * object stays 'json' (its first line is not itself a complete JSON value).
455
+ */
456
+ function detectFormat(text) {
457
+ const [first, second] = text.split("\n").filter((l) => l.trim() !== "");
458
+ if (first === void 0 || second === void 0) return "json";
459
+ if (isCompleteJSON(first) && isCompleteJSON(second)) return "ndjson";
460
+ return "json";
461
+ }
462
+ function isCompleteJSON(s) {
463
+ try {
464
+ JSON.parse(s);
465
+ return true;
466
+ } catch {
467
+ return false;
468
+ }
469
+ }
470
+ //#endregion
471
+ //#region src/evidence.ts
472
+ /** Extracts the planRef and content entries from an evidence-package document. */
473
+ function parseEvidencePackage(pkg) {
474
+ const doc = JSON.parse(pkg);
475
+ const contents = (doc.contents ?? []).map((c) => ({
476
+ uri: c.uri ?? "",
477
+ type: c.type ?? "",
478
+ checksum: c.checksum?.value ?? ""
479
+ }));
480
+ return {
481
+ planRef: doc.planRef ?? "",
482
+ contents
483
+ };
484
+ }
485
+ /** Verifies each content entry's sha256 against fetch(uri), preserving entry
486
+ * order. No checksum → skipped; a fetch throw → error; hash mismatch → mismatch
487
+ * (carrying expected+actual). */
488
+ function verifyChecksums(contents, fetch) {
489
+ return contents.map((c) => {
490
+ const r = {
491
+ uri: c.uri,
492
+ type: c.type,
493
+ status: "skipped"
494
+ };
495
+ if (c.checksum === "") return r;
496
+ let data;
497
+ try {
498
+ data = fetch(c.uri);
499
+ } catch (e) {
500
+ return {
501
+ ...r,
502
+ status: "error",
503
+ error: e instanceof Error ? e.message : String(e)
504
+ };
505
+ }
506
+ const actual = sha256Hex(data);
507
+ if (actual === c.checksum) return {
508
+ ...r,
509
+ status: "match"
510
+ };
511
+ return {
512
+ ...r,
513
+ status: "mismatch",
514
+ expected: c.checksum,
515
+ actual
516
+ };
517
+ });
518
+ }
519
+ /** Extracts assessment baselineRefs from a plan document, deduped in first-seen
520
+ * order. */
521
+ function plannedBaselineRefs(plan) {
522
+ return dedupe((JSON.parse(plan).assessments ?? []).map((a) => a.baselineRef ?? "").filter((s) => s !== ""));
523
+ }
524
+ /** Extracts baseline names from a results document, deduped in first-seen order. */
525
+ function coveredBaselineNames(results) {
526
+ return dedupe((JSON.parse(results).baselines ?? []).map((b) => b.name ?? "").filter((s) => s !== ""));
527
+ }
528
+ /** Diffs planned baseline refs against covered baseline names. A planned ref is
529
+ * covered when some results baseline shares its name. Missing is sorted so the
530
+ * outcome is deterministic across languages and runs. */
531
+ function completeness(planned, covered) {
532
+ const coveredSet = new Set(covered);
533
+ const missing = planned.filter((p) => !coveredSet.has(p)).sort();
534
+ return {
535
+ planned,
536
+ covered,
537
+ missing,
538
+ complete: missing.length === 0
539
+ };
540
+ }
541
+ function sha256Hex(data) {
542
+ return createHash("sha256").update(data).digest("hex");
543
+ }
544
+ function dedupe(input) {
545
+ const seen = /* @__PURE__ */ new Set();
546
+ const out = [];
547
+ for (const s of input) if (!seen.has(s)) {
548
+ seen.add(s);
549
+ out.push(s);
550
+ }
551
+ return out;
552
+ }
553
+ //#endregion
554
+ //#region src/index.ts
555
+ /** Library version, kept on the workspace lockstep. */
556
+ const engineVersion = "3.5.0";
557
+ //#endregion
558
+ export { agentOverrideCount, calculateCompliance, completeness, countControlsByStatus, countControlsByStatusSeverity, coveredBaselineNames, deriveSeverity, detect, detectFormat, engineVersion, filter, load, mapControlIDs, mapControlIDsByStatus, overallStatus, parseEvidencePackage, plannedBaselineRefs, validateThresholds, verifyChecksums };
559
+
560
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/detect.ts","../src/compliance.ts","../src/safematch.ts","../src/query.ts","../src/loader.ts","../src/evidence.ts","../src/index.ts"],"sourcesContent":["// 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","// 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';\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_NO_IMPACT = 'no_impact';\n\nexport interface SeverityCounts {\n critical: number;\n high: number;\n medium: number;\n low: number;\n none: number;\n total: number;\n}\n\nexport interface StatusCounts {\n passed: SeverityCounts;\n failed: SeverityCounts;\n skipped: SeverityCounts;\n error: SeverityCounts;\n noImpact: SeverityCounts;\n}\n\nexport interface ControlIDMapping {\n id: string;\n status: string;\n severity: 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 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 noImpact?: ThresholdSeverity;\n}\n\nfunction newSeverityCounts(): SeverityCounts {\n return { critical: 0, high: 0, medium: 0, low: 0, none: 0, total: 0 };\n}\n\nfunction newStatusCounts(): StatusCounts {\n return {\n passed: newSeverityCounts(),\n failed: newSeverityCounts(),\n skipped: newSeverityCounts(),\n error: newSeverityCounts(),\n noImpact: 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. Maps \"informational\" to \"none\".\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 const sev = impactToSeverity(impact);\n return sev === 'informational' ? 'none' : sev;\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.noImpact;\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 (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.none++;\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_NO_IMPACT;\n default:\n return THRESHOLD_SKIPPED;\n }\n}\n\n/** CountControlsByStatusSeverity counts requirements by overall status and severity. */\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): 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 addCount(counts, status, deriveSeverity(req.impact, 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: deriveSeverity(req.impact, reqSeverity(req)),\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): 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 severity: deriveSeverity(req.impact, reqSeverity(req)),\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 * 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/**\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: string[] = [];\n\n const actualControls = new Map<string, ControlIDMapping>();\n for (const m of controlMap) {\n actualControls.set(m.id, m);\n }\n\n if (config.compliance) {\n if (config.compliance.min !== undefined && compliance < config.compliance.min) {\n violations.push(`compliance ${compliance.toFixed(2)}% is below minimum ${config.compliance.min.toFixed(2)}%`);\n }\n if (config.compliance.max !== undefined && compliance > config.compliance.max) {\n violations.push(`compliance ${compliance.toFixed(2)}% exceeds maximum ${config.compliance.max.toFixed(2)}%`);\n }\n }\n\n violations.push(...checkSeverityThreshold(THRESHOLD_PASSED, config.passed, counts.passed, actualControls));\n violations.push(...checkSeverityThreshold(THRESHOLD_FAILED, config.failed, counts.failed, actualControls));\n violations.push(...checkSeverityThreshold(THRESHOLD_SKIPPED, config.skipped, counts.skipped, actualControls));\n violations.push(...checkSeverityThreshold(THRESHOLD_ERROR, config.error, counts.error, actualControls));\n violations.push(...checkSeverityThreshold(THRESHOLD_NO_IMPACT, config.noImpact, counts.noImpact, actualControls));\n\n return violations;\n}\n\nfunction checkSeverityThreshold(\n status: string,\n threshold: ThresholdSeverity | undefined,\n actual: SeverityCounts,\n actualControls: Map<string, ControlIDMapping>,\n): string[] {\n if (!threshold) {\n return [];\n }\n const violations: string[] = [];\n const check = (label: string, bound: ThresholdBound | undefined, actualCount: number): void => {\n if (!bound) {\n return;\n }\n const path = `${status}.${label}`;\n if (bound.min !== undefined && actualCount < bound.min) {\n violations.push(`${path}: ${actualCount} is below minimum ${bound.min}`);\n }\n if (bound.max !== undefined && actualCount > bound.max) {\n violations.push(`${path}: ${actualCount} exceeds maximum ${bound.max}`);\n }\n for (const expectedID of bound.controls ?? []) {\n const ac = actualControls.get(expectedID);\n if (!ac) {\n violations.push(`${path}: expected control ${expectedID} not found in results`);\n } else if (ac.status !== status || ac.severity !== label) {\n violations.push(\n `${path}: control ${expectedID} expected ${status}/${label} but found ${ac.status}/${ac.severity}`,\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('none', threshold.none, actual.none);\n check('total', threshold.total, actual.total);\n\n return violations;\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","// 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 { deriveSeverity } from './compliance.js';\nimport { safeGlobMatch } from './safematch.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?: string[];\n severity?: string[];\n impact?: string;\n cci?: string[];\n nist?: string[];\n id?: string;\n tag?: string[];\n search?: string;\n baseline?: string;\n limit?: number;\n count?: boolean;\n statusOf?: (control: EvaluatedRequirement) => string;\n}\n\n/** A single query result row. */\nexport interface Match {\n id: string;\n title: string;\n status: string;\n impact: number;\n severity: string;\n baseline: string;\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, options: FilterOptions): Match[] {\n const filters = buildFilters(options);\n const matches: Match[] = [];\n\n for (const baseline of results.baselines ?? []) {\n if (options.baseline && !matchesGlob(baseline.name, options.baseline)) {\n continue;\n }\n for (const control of baseline.requirements ?? []) {\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 const severity = deriveSeverity(control.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 impact: control.impact,\n severity,\n baseline: baseline.name,\n });\n }\n }\n return matches;\n}\n\nfunction buildFilters(options: FilterOptions): FilterFunc[] {\n const filters: FilterFunc[] = [];\n\n if (options.status && options.status.length > 0) {\n const statuses = options.status.map((s) => s.toLowerCase());\n filters.push((_c, s) => statuses.includes(s.toLowerCase()));\n }\n\n if (options.severity && options.severity.length > 0) {\n const severities = options.severity.map((s) => s.toLowerCase());\n filters.push((_c, _s, severity) => severities.includes(severity));\n }\n\n if (options.impact) {\n const [op, val] = parseImpactFilter(options.impact);\n filters.push((c) => compareImpact(c.impact, op, val));\n }\n\n if (options.cci && options.cci.length > 0) {\n const ccis = options.cci.map((c) => c.toUpperCase());\n filters.push((c) => ccis.some((cci) => tagContains(c.tags, 'cci', cci)));\n }\n\n if (options.nist && options.nist.length > 0) {\n const nist = options.nist;\n filters.push((c) => nist.some((n) => tagMatchesGlob(c.tags, 'nist', n)));\n }\n\n if (options.id) {\n const id = options.id;\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 if (options.tag && options.tag.length > 0) {\n const tagFilters: { key: string; value: string }[] = [];\n for (const t of options.tag) {\n const idx = t.indexOf(':');\n if (idx >= 0) {\n tagFilters.push({ key: t.slice(0, idx), value: t.slice(idx + 1) });\n }\n }\n if (tagFilters.length > 0) {\n filters.push((c) => tagFilters.some((tf) => tagMatchesGlob(c.tags, tf.key, tf.value)));\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/** 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","// 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 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 { createHash } from 'node:crypto';\n\n/** Classifies a single content entry's checksum verification. */\nexport type ChecksumStatus = 'match' | 'mismatch' | 'skipped' | 'error';\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}\n\n/** The verification outcome for one content entry. */\nexport interface ChecksumResult {\n uri: string;\n type: 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\ninterface RawContent {\n uri?: string;\n type?: string;\n checksum?: { value?: string };\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 = JSON.parse(pkg) as { planRef?: string; contents?: RawContent[] };\n const contents: EvidenceContent[] = (doc.contents ?? []).map((c) => ({\n uri: c.uri ?? '',\n type: c.type ?? '',\n checksum: c.checksum?.value ?? '',\n }));\n return { planRef: doc.planRef ?? '', contents };\n}\n\n/** Verifies each content entry's sha256 against fetch(uri), preserving entry\n * order. No checksum → skipped; a fetch throw → error; hash mismatch → mismatch\n * (carrying expected+actual). */\nexport function verifyChecksums(contents: EvidenceContent[], fetch: FetchFn): ChecksumResult[] {\n return contents.map((c) => {\n const r: ChecksumResult = { uri: c.uri, type: c.type, status: 'skipped' };\n if (c.checksum === '') {\n return r;\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 = sha256Hex(data);\n if (actual === c.checksum) {\n return { ...r, status: 'match' };\n }\n return { ...r, status: 'mismatch', expected: c.checksum, actual };\n });\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 = JSON.parse(plan) as { assessments?: Array<{ baselineRef?: string }> };\n const refs = (doc.assessments ?? []).map((a) => a.baselineRef ?? '').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 = JSON.parse(results) as { baselines?: Array<{ name?: string }> };\n const names = (doc.baselines ?? []).map((b) => b.name ?? '').filter((s) => s !== '');\n return dedupe(names);\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\nfunction sha256Hex(data: Uint8Array): string {\n return createHash('sha256').update(data).digest('hex');\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","// @mitre/hdf-engine — shared, schema-typed read-side engines for HDF documents\n// (detect, query, compliance, and future read-side engines). Consumed as a\n// library by the CLI and the MCP; sibling to @mitre/hdf-diff. See ADR-0007.\n\n/** Library version, kept on the workspace lockstep. */\nexport const engineVersion = '3.5.0';\n\n// Detection engine (peer of hdf-engine/go/detect.go).\nexport { detect, type HdfDocType } from './detect.js';\n\n// Query engine (peer of hdf-engine/go/filter.go).\nexport { filter, type FilterOptions, type Match } from './query.js';\n\n// Document loader core (peer of hdf-engine/go/loader.go).\nexport { load, detectFormat, type InputFormat, type LoadResult } from './loader.js';\n\n// Evidence-verify engine (peer of hdf-engine/go/evidence.go).\nexport {\n parseEvidencePackage,\n verifyChecksums,\n plannedBaselineRefs,\n coveredBaselineNames,\n completeness,\n type ChecksumStatus,\n type EvidenceContent,\n type ChecksumResult,\n type CompletenessResult,\n type FetchFn,\n} from './evidence.js';\n\n// Compliance & threshold engine (peer of hdf-engine/go/compliance.go).\nexport {\n countControlsByStatusSeverity,\n countControlsByStatus,\n agentOverrideCount,\n mapControlIDs,\n mapControlIDsByStatus,\n calculateCompliance,\n validateThresholds,\n overallStatus,\n deriveSeverity,\n type StatusCounts,\n type SeverityCounts,\n type ControlIDMapping,\n type ThresholdConfig,\n type ThresholdSeverity,\n type ThresholdBound,\n type ComplianceBound,\n} from './compliance.js';\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AAE,GAAG;GAAG,QAAQ;GAAY,UAAU,EAAE;GAAU;EAAO;CAClE,CAAC;AACH;;;AAIA,SAAgB,oBAAoB,MAAwB;CAG1D,OAAO,QAFK,KAAK,MAAM,IACP,CAAC,CAAC,eAAe,CAAC,EAAA,CAAG,KAAK,MAAM,EAAE,eAAe,EAAE,CAAC,CAAC,QAAQ,MAAM,MAAM,EACxE,CAAC;AACpB;;AAGA,SAAgB,qBAAqB,SAA2B;CAG9D,OAAO,QAFK,KAAK,MAAM,OACN,CAAC,CAAC,aAAa,CAAC,EAAA,CAAG,KAAK,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC,QAAQ,MAAM,MAAM,EAC/D,CAAC;AACrB;;;;AAKA,SAAgB,aAAa,SAAmB,SAAuC;CACrF,MAAM,aAAa,IAAI,IAAI,OAAO;CAClC,MAAM,UAAU,QAAQ,QAAQ,MAAM,CAAC,WAAW,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK;CAC/D,OAAO;EAAE;EAAS;EAAS;EAAS,UAAU,QAAQ,WAAW;CAAE;AACrE;AAEA,SAAS,UAAU,MAA0B;CAC3C,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,OAAO,KAAK;AACvD;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;;;;ACpHA,MAAa,gBAAgB"}
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@mitre/hdf-engine",
3
+ "version": "3.6.0-rc.1",
4
+ "description": "Shared schema-typed read-side engines for HDF documents — detection, query/filtering, and compliance rollups",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "type": "module",
9
+ "main": "./dist/index.js",
10
+ "types": "./dist/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js"
15
+ }
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "https://github.com/mitre/hdf-libs.git",
23
+ "directory": "hdf-engine"
24
+ },
25
+ "author": "MITRE Corporation",
26
+ "license": "Apache-2.0",
27
+ "dependencies": {
28
+ "@mitre/hdf-utilities": "^3.5.1",
29
+ "@mitre/hdf-parsers": "^3.5.1",
30
+ "@mitre/hdf-schema": "^3.5.1"
31
+ },
32
+ "devDependencies": {
33
+ "@mitre/hdf-validators": "^3.5.1"
34
+ },
35
+ "engines": {
36
+ "node": ">=22.0.0"
37
+ },
38
+ "keywords": [
39
+ "hdf",
40
+ "heimdall",
41
+ "engine",
42
+ "query",
43
+ "compliance",
44
+ "security",
45
+ "compliance"
46
+ ],
47
+ "scripts": {
48
+ "build": "tsdown",
49
+ "clean": "rimraf dist",
50
+ "test": "pnpm run test:ts",
51
+ "test:ts": "vitest run",
52
+ "test:go": "cd go && go test ./...",
53
+ "test:watch": "vitest",
54
+ "test:coverage": "vitest run --coverage",
55
+ "type-check": "tsc --noEmit",
56
+ "lint": "eslint src test",
57
+ "lint:fix": "eslint src test --fix"
58
+ }
59
+ }