@mitre/hdf-diff 3.4.4 → 3.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,14 +1,6 @@
1
+ import { computeEffectiveStatus as computeEffectiveStatus$1, formatTimestamp, governingOverrideIndex, parseCvssVector, parseTimestamp, sha256 } from "@mitre/hdf-utilities";
1
2
  import { validateComparison as validateComparison$1 } from "@mitre/hdf-validators";
2
- import { parseCvssVector } from "@mitre/hdf-utilities";
3
3
  //#region src/status.ts
4
- /** Status severity ranking — higher index = worse */
5
- const STATUS_SEVERITY = [
6
- "notApplicable",
7
- "notReviewed",
8
- "passed",
9
- "failed",
10
- "error"
11
- ];
12
4
  /** Statuses that count as "passing" for fixed/regressed classification */
13
5
  const PASSING_STATUSES = /* @__PURE__ */ new Set(["passed"]);
14
6
  /** Statuses that count as "failing" for fixed/regressed classification */
@@ -18,36 +10,29 @@ const FAILING_STATUSES = /* @__PURE__ */ new Set([
18
10
  "notReviewed"
19
11
  ]);
20
12
  /**
21
- * Determine the effective status of a requirement from its results and overrides.
13
+ * Determine the effective status of a requirement from its results and
14
+ * overrides, delegating to the canonical shared implementation in
15
+ * `@mitre/hdf-utilities` (see status-determination.md):
22
16
  *
23
- * Priority:
24
17
  * 1. impact === 0 → notApplicable (regardless of results)
25
- * 2. effectiveStatus field set (and no statusOverrides) → use it
26
- * 3. Non-expired statusOverrides → use first non-expired
18
+ * 2. the governing (most recent non-expired) status override's status
19
+ * 3. effectiveStatus field set (and no statusOverrides) → use it
27
20
  * 4. Aggregate results using worst-wins
28
21
  * 5. Empty results → notReviewed
29
22
  */
30
23
  function computeEffectiveStatus(requirement, referenceTimestamp) {
31
- if (requirement["impact"] === 0) return "notApplicable";
32
- const overrides = requirement["statusOverrides"];
33
- if (overrides && overrides.length > 0) {
34
- const refTime = referenceTimestamp ? new Date(referenceTimestamp).getTime() : Date.now();
35
- for (const override of overrides) if (new Date(override.expiresAt).getTime() > refTime && override.status) return override.status;
36
- }
37
- const effectiveStatus = requirement["effectiveStatus"];
38
- if (effectiveStatus && (!overrides || overrides.length === 0)) return effectiveStatus;
39
- const results = requirement["results"];
40
- if (!results || results.length === 0) return "notReviewed";
41
- let worstIndex = -1;
42
- let worstStatus = "notReviewed";
43
- for (const result of results) {
44
- const idx = STATUS_SEVERITY.indexOf(result.status);
45
- if (idx > worstIndex) {
46
- worstIndex = idx;
47
- worstStatus = result.status;
48
- }
49
- }
50
- return worstStatus;
24
+ const results = requirement["results"] ?? [];
25
+ const overrides = requirement["statusOverrides"] ?? [];
26
+ return computeEffectiveStatus$1({
27
+ impact: requirement["impact"] ?? NaN,
28
+ effectiveStatus: requirement["effectiveStatus"],
29
+ resultStatuses: results.map((r) => r.status),
30
+ overrides: overrides.map((o) => ({
31
+ status: o.status,
32
+ appliedAt: o.appliedAt,
33
+ expiresAt: o.expiresAt
34
+ }))
35
+ }, referenceTimestamp);
51
36
  }
52
37
  /**
53
38
  * Classify why the status changed between two requirements.
@@ -65,11 +50,11 @@ function classifyChangeReasons(oldReq, newReq, oldTimestamp, newTimestamp) {
65
50
  if (newOverrides.length > oldOverrides.length) reasons.push("overrideAdded");
66
51
  else if (newOverrides.length < oldOverrides.length) reasons.push("overrideRemoved");
67
52
  if (oldTimestamp && newTimestamp && oldOverrides.length > 0) {
68
- const oldTime = new Date(oldTimestamp).getTime();
69
- const newTime = new Date(newTimestamp).getTime();
70
- for (const override of oldOverrides) {
71
- const expiresAt = new Date(override.expiresAt).getTime();
72
- if (expiresAt > oldTime && expiresAt <= newTime) {
53
+ const oldTime = parseTimestamp(oldTimestamp)?.getTime();
54
+ const newTime = parseTimestamp(newTimestamp)?.getTime();
55
+ if (oldTime !== void 0 && newTime !== void 0) for (const override of oldOverrides) {
56
+ const expiresAt = parseTimestamp(override.expiresAt)?.getTime();
57
+ if (expiresAt !== void 0 && expiresAt > oldTime && expiresAt <= newTime) {
73
58
  reasons.push("overrideExpired");
74
59
  break;
75
60
  }
@@ -154,6 +139,15 @@ function computeSummary(requirements) {
154
139
  //#endregion
155
140
  //#region src/normalize.ts
156
141
  /**
142
+ * Normalize InSpec exec-json v1 format to HDF v2 structure for diffing.
143
+ *
144
+ * V1 uses: profiles[].controls[].results[].code_desc, source_location, start_time
145
+ * V2 uses: baselines[].requirements[].results[].codeDesc, sourceLocation, startTime
146
+ *
147
+ * This module detects v1 documents and converts them in-memory to v2 shape
148
+ * so the diff engine only needs to handle one format.
149
+ */
150
+ /**
157
151
  * Detect whether a document is v1 (InSpec exec-json) format.
158
152
  * V1 has `profiles` at the top level; v2 has `baselines`.
159
153
  */
@@ -230,8 +224,8 @@ function normalizeResultStatus(v1Status) {
230
224
  */
231
225
  function normalizeTimestamp(timestamp) {
232
226
  if (timestamp.includes("T")) return timestamp;
233
- const parsed = new Date(timestamp);
234
- if (!isNaN(parsed.getTime())) return parsed.toISOString();
227
+ const parsed = parseTimestamp(timestamp);
228
+ if (parsed) return parsed.toISOString();
235
229
  return timestamp;
236
230
  }
237
231
  function normalizeResult(result) {
@@ -1210,6 +1204,13 @@ const DEFAULT_TRACKED_FIELDS = [
1210
1204
  "tags"
1211
1205
  ];
1212
1206
  /**
1207
+ * Round a fuzzy-match confidence (0-1 similarity) to 4 decimal places to strip
1208
+ * IEEE-754 noise from the serialized matchConfidence value.
1209
+ */
1210
+ function roundConfidence(x) {
1211
+ return Math.round(x * 1e4) / 1e4;
1212
+ }
1213
+ /**
1213
1214
  * Extract a dataSource label from a document, if available.
1214
1215
  * Looks for `dataSource.name` in the raw (pre-normalized) document.
1215
1216
  */
@@ -1456,7 +1457,7 @@ function comparePair(oldNormalized, newNormalized, oldTimestamp, newTimestamp, t
1456
1457
  before: oldReq,
1457
1458
  after: newReq,
1458
1459
  matchStrategy: pair.strategy,
1459
- matchConfidence: pair.confidence
1460
+ matchConfidence: roundConfidence(pair.confidence)
1460
1461
  });
1461
1462
  }
1462
1463
  for (const req of matchResult.unmatchedOld) {
@@ -1951,7 +1952,7 @@ function diffBaselines(oldBaseline, newBaseline, options) {
1951
1952
  before: oldReq,
1952
1953
  after: newReq,
1953
1954
  matchStrategy: pair.strategy,
1954
- matchConfidence: pair.confidence
1955
+ matchConfidence: roundConfidence(pair.confidence)
1955
1956
  });
1956
1957
  }
1957
1958
  for (const req of matchResult.unmatchedOld) {
@@ -2259,6 +2260,496 @@ function computeComponentFieldChanges(oldObj, newObj, trackedFields) {
2259
2260
  return changes;
2260
2261
  }
2261
2262
  //#endregion
2263
+ //#region src/effective-checksum.ts
2264
+ /** Maps overrides onto the shared neutral selection shape (applied/expiry
2265
+ * window only; eligibility is passed separately). */
2266
+ function overrideWindows(overrides) {
2267
+ return overrides.map((o) => ({
2268
+ appliedAt: o.appliedAt,
2269
+ expiresAt: o.expiresAt
2270
+ }));
2271
+ }
2272
+ /**
2273
+ * Determine the effective impact of a requirement: the most recently applied
2274
+ * non-expired override carrying an impact value wins (the schema's definition
2275
+ * of effectiveImpact, selected by the shared governing helper); with no
2276
+ * overrides, a stored effectiveImpact field is honored; otherwise the base
2277
+ * impact. (Go parity: ComputeEffectiveImpact in hdf-diff/go/effective_checksum.go.)
2278
+ */
2279
+ function computeEffectiveImpact(requirement, referenceTimestamp) {
2280
+ const baseImpact = requirement["impact"] ?? 0;
2281
+ const overrides = requirement["statusOverrides"];
2282
+ if (overrides && overrides.length > 0) {
2283
+ const i = governingOverrideIndex(overrideWindows(overrides), (idx) => overrides[idx]?.impact !== void 0, referenceTimestamp);
2284
+ if (i >= 0) return overrides[i].impact.value;
2285
+ return baseImpact;
2286
+ }
2287
+ const effectiveImpact = requirement["effectiveImpact"];
2288
+ if (effectiveImpact !== void 0) return effectiveImpact;
2289
+ return baseImpact;
2290
+ }
2291
+ /**
2292
+ * Return the Override_Type of the governing (most recently applied
2293
+ * non-expired) override, a stored disposition field when no overrides are
2294
+ * present, or null. (Go parity: ComputeDisposition.)
2295
+ */
2296
+ function computeDisposition(requirement, referenceTimestamp) {
2297
+ const overrides = requirement["statusOverrides"];
2298
+ if (overrides && overrides.length > 0) {
2299
+ const i = governingOverrideIndex(overrideWindows(overrides), () => true, referenceTimestamp);
2300
+ if (i >= 0) return overrides[i]?.type ?? null;
2301
+ return null;
2302
+ }
2303
+ return requirement["disposition"] ?? null;
2304
+ }
2305
+ /**
2306
+ * Hash the resolved effective posture of a requirement: sha256 over the
2307
+ * canonical JSON {"status":<resolved>,"impact":<resolved>,"disposition":<type|null>}.
2308
+ * Flips exactly when the operative status, impact, or disposition changes;
2309
+ * stable under all other document churn. Byte-identical with the Go
2310
+ * implementation (ComputeEffectiveChecksum) — the key order of the canonical
2311
+ * object is part of the contract. Pass the document timestamp as
2312
+ * referenceTimestamp for determinism. A missing or unparseable reference
2313
+ * falls back to the wall clock inside the shared governing-override helper,
2314
+ * so callers that need reproducible output must always supply a valid
2315
+ * timestamp.
2316
+ */
2317
+ async function computeEffectiveChecksum(requirement, referenceTimestamp) {
2318
+ return {
2319
+ algorithm: "sha256",
2320
+ value: await sha256(JSON.stringify({
2321
+ status: computeEffectiveStatus(requirement, referenceTimestamp),
2322
+ impact: computeEffectiveImpact(requirement, referenceTimestamp),
2323
+ disposition: computeDisposition(requirement, referenceTimestamp)
2324
+ }))
2325
+ };
2326
+ }
2327
+ //#endregion
2328
+ //#region src/change-event.ts
2329
+ /** Batch ChangeReason → event-vocabulary mapping; unmapped reasons are batch-only. */
2330
+ const EVENT_REASON_FOR = {
2331
+ resultChanged: "resultChanged",
2332
+ overrideAdded: "overrideAdded",
2333
+ overrideExpired: "overrideExpired",
2334
+ overrideRemoved: "overrideRemoved",
2335
+ impactChanged: "impactChanged",
2336
+ effectiveImpactChanged: "impactChanged"
2337
+ };
2338
+ function classifyEventReasons(prev, newReq, prevReq, inputs) {
2339
+ const reasons = [];
2340
+ const add = (r) => {
2341
+ if (r && !reasons.includes(r)) reasons.push(r);
2342
+ };
2343
+ if (prevReq) {
2344
+ const prevRef = inputs.prevReferenceTimestamp ?? inputs.referenceTimestamp;
2345
+ for (const r of classifyChangeReasons(prevReq, newReq, prevRef, inputs.referenceTimestamp)) add(EVENT_REASON_FOR[r]);
2346
+ return reasons;
2347
+ }
2348
+ if (computeEffectiveImpact(newReq, inputs.referenceTimestamp) !== prev.effectiveImpact) add("impactChanged");
2349
+ return reasons;
2350
+ }
2351
+ /**
2352
+ * The pure detection kernel (ADR-0005): compare a requirement's resolved
2353
+ * posture against the stored last-value state and emit a
2354
+ * Requirement_Change_Event when it moved, or null when it did not.
2355
+ *
2356
+ * - prev null → state "new" (chain start: null before/priorChecksum)
2357
+ * - newReq null → state "absent" (after null, thin before preserved)
2358
+ * - checksum match → null (no event; the steady-state majority)
2359
+ * - otherwise → fixed/regressed/updated per the effective-status
2360
+ * transition, with the full after requirement as payload
2361
+ *
2362
+ * prevReq (optional) is the full prior requirement when the caller's
2363
+ * materialized state has it; it enables complete changeReasons
2364
+ * classification via the batch classifier, filtered to the event
2365
+ * vocabulary. Without it, only reasons provable from the thin state
2366
+ * (impactChanged) are emitted. Byte-parity with the Go kernel
2367
+ * (ChangeEventFromPrevious) is pinned by shared test vectors.
2368
+ */
2369
+ async function changeEventFromPrevious(prev, newReq, prevReq, inputs) {
2370
+ if (!prev && !newReq) return null;
2371
+ const envelope = {
2372
+ eventId: inputs.eventId,
2373
+ source: inputs.source,
2374
+ sequence: inputs.sequence,
2375
+ systemRef: inputs.systemRef,
2376
+ componentId: inputs.componentId,
2377
+ requirementId: inputs.requirementId,
2378
+ timestamp: inputs.timestamp,
2379
+ ...inputs.schemaRef !== void 0 ? { schemaRef: inputs.schemaRef } : {}
2380
+ };
2381
+ if (!prev) return {
2382
+ ...envelope,
2383
+ priorChecksum: null,
2384
+ state: "new",
2385
+ before: null,
2386
+ after: newReq
2387
+ };
2388
+ const before = {
2389
+ effectiveStatus: prev.effectiveStatus,
2390
+ effectiveImpact: prev.effectiveImpact
2391
+ };
2392
+ if (!newReq) return {
2393
+ ...envelope,
2394
+ priorChecksum: { ...prev.checksum },
2395
+ state: "absent",
2396
+ before,
2397
+ after: null
2398
+ };
2399
+ if ((await computeEffectiveChecksum(newReq, inputs.referenceTimestamp)).value === prev.checksum.value) return null;
2400
+ const newStatus = computeEffectiveStatus(newReq, inputs.referenceTimestamp);
2401
+ const transition = classifyDiffStatus(prev.effectiveStatus, newStatus);
2402
+ const state = transition === "fixed" || transition === "regressed" ? transition : "updated";
2403
+ const changeReasons = classifyEventReasons(prev, newReq, prevReq, inputs);
2404
+ return {
2405
+ ...envelope,
2406
+ priorChecksum: { ...prev.checksum },
2407
+ state,
2408
+ ...changeReasons.length > 0 ? { changeReasons } : {},
2409
+ before,
2410
+ after: newReq
2411
+ };
2412
+ }
2413
+ //#endregion
2414
+ //#region src/event-stream-common.ts
2415
+ /** Extract the priorChecksum hex from an event ('' when null/absent). */
2416
+ function eventPriorValue(ev) {
2417
+ return ev["priorChecksum"]?.value ?? "";
2418
+ }
2419
+ /** Effective checksum of a requirement ('' when absent). */
2420
+ async function requirementChecksum(req, referenceTimestamp) {
2421
+ if (!req) return "";
2422
+ return (await computeEffectiveChecksum(req, referenceTimestamp)).value;
2423
+ }
2424
+ /**
2425
+ * Drop duplicate (source, eventId) deliveries — the fold contract's
2426
+ * idempotency key (ADR-0005 §4). Go parity: dedupEvents.
2427
+ */
2428
+ function dedupEvents(events) {
2429
+ const seen = /* @__PURE__ */ new Set();
2430
+ const deduped = [];
2431
+ for (const ev of events) {
2432
+ if (!ev) continue;
2433
+ const key = `${String(ev["source"])}|${String(ev["eventId"])}`;
2434
+ if (seen.has(key)) continue;
2435
+ seen.add(key);
2436
+ deduped.push(ev);
2437
+ }
2438
+ return deduped;
2439
+ }
2440
+ /**
2441
+ * Group events per entity key, each chain ordered by sequence (eventId
2442
+ * tie-break), keys sorted for deterministic iteration. Go parity:
2443
+ * groupEventChains.
2444
+ */
2445
+ function groupEventChains(events) {
2446
+ const byKey = /* @__PURE__ */ new Map();
2447
+ for (const ev of events) {
2448
+ const id = ev["requirementId"];
2449
+ const chain = byKey.get(id) ?? [];
2450
+ chain.push(ev);
2451
+ byKey.set(id, chain);
2452
+ }
2453
+ const keys = [...byKey.keys()].sort();
2454
+ for (const [, chain] of byKey) chain.sort((a, b) => {
2455
+ const seqA = a["sequence"];
2456
+ const seqB = b["sequence"];
2457
+ if (seqA !== seqB) return seqA - seqB;
2458
+ return String(a["eventId"]).localeCompare(String(b["eventId"]));
2459
+ });
2460
+ return {
2461
+ byKey,
2462
+ keys
2463
+ };
2464
+ }
2465
+ /**
2466
+ * Walk a per-key chain's priorChecksum links from the seed posture forward,
2467
+ * reporting anomalies through keyWarn. Best-effort: expiry anchored to each
2468
+ * event's occurrence time. Unanchored chains (key not in seed, first event
2469
+ * not new) are left to the caller's application outcome. Go parity:
2470
+ * verifyEventChain.
2471
+ */
2472
+ async function verifyEventChain(chain, seedReq, inSeed, keyWarn) {
2473
+ const first = chain[0];
2474
+ if (!first) return;
2475
+ if (!inSeed && first["state"] !== "new") return;
2476
+ let expected = "";
2477
+ if (seedReq) expected = await requirementChecksum(seedReq, first["timestamp"]);
2478
+ for (const ev of chain) {
2479
+ const prior = eventPriorValue(ev);
2480
+ if (ev["state"] === "new") {
2481
+ if (inSeed) keyWarn("newOnExisting", "state new for a key already present in the seed");
2482
+ else if (prior !== "") keyWarn("chainGap", "new-state event carries a non-null priorChecksum");
2483
+ } else if (prior !== expected) keyWarn("chainGap", `priorChecksum "${prior}" does not match expected chain state "${expected}"`);
2484
+ expected = await requirementChecksum(ev["after"], ev["timestamp"]);
2485
+ }
2486
+ }
2487
+ //#endregion
2488
+ //#region src/apply-events.ts
2489
+ function findRequirement(doc, id) {
2490
+ const baselines = doc["baselines"] ?? [];
2491
+ for (const baseline of baselines) {
2492
+ const requirements = baseline["requirements"] ?? [];
2493
+ const index = requirements.findIndex((r) => r["id"] === id);
2494
+ if (index >= 0) return {
2495
+ baseline,
2496
+ requirements,
2497
+ index
2498
+ };
2499
+ }
2500
+ return null;
2501
+ }
2502
+ /**
2503
+ * Reassemble the current posture from a seed hdf-results document plus a
2504
+ * batch of requirement-change events (ADR-0005 §§4-7): keyed last-value-wins
2505
+ * by sequence, idempotent via (source, eventId) dedup, tombstone-aware
2506
+ * (absent removes), total over the event-state enum. Delivery order and
2507
+ * duplicates never change the output. The result carries the caller's
2508
+ * generator and a derivation block (seed pinned by content, watermark,
2509
+ * count, asOf) so it can never masquerade as scan evidence. Chain gaps and
2510
+ * anomalies surface as warnings, never as refusal. Go parity:
2511
+ * ApplyChangeEvents.
2512
+ */
2513
+ async function applyChangeEvents(seedJson, events, inputs) {
2514
+ const doc = JSON.parse(seedJson);
2515
+ const seedChecksum = await sha256(seedJson);
2516
+ const docTimestamp = doc["timestamp"] ?? "";
2517
+ const { byKey, keys } = groupEventChains(dedupEvents(events));
2518
+ const warnings = [];
2519
+ let maxSequence = 0;
2520
+ let maxOccurredMs = Number.NEGATIVE_INFINITY;
2521
+ let asOfFromEvents = "";
2522
+ let eventsApplied = 0;
2523
+ const insertions = [];
2524
+ for (const id of keys) {
2525
+ const chain = byKey.get(id) ?? [];
2526
+ const first = chain[0];
2527
+ const winner = chain[chain.length - 1];
2528
+ if (!first || !winner) continue;
2529
+ const inSeed = findRequirement(doc, id) !== null;
2530
+ let keyWarned = false;
2531
+ const keyWarn = (kind, message) => {
2532
+ if (!keyWarned) {
2533
+ keyWarned = true;
2534
+ warnings.push({
2535
+ requirementId: id,
2536
+ kind,
2537
+ message
2538
+ });
2539
+ }
2540
+ };
2541
+ const located = findRequirement(doc, id);
2542
+ await verifyEventChain(chain, located ? located.requirements[located.index] ?? null : null, inSeed, keyWarn);
2543
+ const verifyLinks = inSeed || first["state"] === "new";
2544
+ const winnerSeq = winner["sequence"];
2545
+ if (winnerSeq > maxSequence) maxSequence = winnerSeq;
2546
+ const occurred = parseTimestamp(winner["timestamp"]);
2547
+ if (occurred !== null && occurred.getTime() > maxOccurredMs) {
2548
+ maxOccurredMs = occurred.getTime();
2549
+ asOfFromEvents = formatTimestamp(occurred);
2550
+ }
2551
+ if (winner["state"] === "absent") {
2552
+ const hit = findRequirement(doc, id);
2553
+ if (hit) {
2554
+ hit.requirements.splice(hit.index, 1);
2555
+ eventsApplied++;
2556
+ } else keyWarn("absentUnknown", "absent event for a key not present in the document");
2557
+ continue;
2558
+ }
2559
+ if (!verifyLinks) keyWarn("chainGap", "non-new chain for a key the seed does not carry");
2560
+ const payload = winner["after"];
2561
+ if (!payload) {
2562
+ keyWarn("chainGap", "winning event carries no applicable after payload");
2563
+ continue;
2564
+ }
2565
+ const hit = findRequirement(doc, id);
2566
+ if (hit) {
2567
+ hit.requirements[hit.index] = structuredClone(payload);
2568
+ eventsApplied++;
2569
+ } else insertions.push({
2570
+ sequence: winnerSeq,
2571
+ id,
2572
+ payload: structuredClone(payload)
2573
+ });
2574
+ }
2575
+ insertions.sort((a, b) => a.sequence !== b.sequence ? a.sequence - b.sequence : a.id.localeCompare(b.id));
2576
+ if (insertions.length > 0) {
2577
+ const baselines = doc["baselines"] ?? [];
2578
+ const firstBaseline = baselines[0];
2579
+ const firstInsertion = insertions[0];
2580
+ if (!firstBaseline || !firstInsertion) throw new Error("seed document has no baselines to insert new requirements into");
2581
+ if (baselines.length > 1) warnings.push({
2582
+ requirementId: firstInsertion.id,
2583
+ kind: "multiBaseline",
2584
+ message: "seed has multiple baselines; new requirements appended to the first"
2585
+ });
2586
+ const requirements = firstBaseline["requirements"] ?? [];
2587
+ for (const ins of insertions) {
2588
+ requirements.push(ins.payload);
2589
+ eventsApplied++;
2590
+ }
2591
+ firstBaseline["requirements"] = requirements;
2592
+ }
2593
+ const asOf = asOfFromEvents !== "" ? asOfFromEvents : docTimestamp;
2594
+ if (asOf === "") throw new Error("cannot derive asOf: no events supplied and the seed document has no timestamp");
2595
+ doc["generator"] = {
2596
+ name: inputs.generator.name,
2597
+ version: inputs.generator.version
2598
+ };
2599
+ doc["timestamp"] = asOf;
2600
+ doc["derivation"] = {
2601
+ seed: {
2602
+ uri: inputs.seedUri,
2603
+ checksum: {
2604
+ algorithm: "sha256",
2605
+ value: seedChecksum
2606
+ }
2607
+ },
2608
+ source: inputs.source,
2609
+ throughSequence: maxSequence,
2610
+ eventsApplied,
2611
+ asOf
2612
+ };
2613
+ return {
2614
+ results: doc,
2615
+ warnings
2616
+ };
2617
+ }
2618
+ //#endregion
2619
+ //#region src/fold-events.ts
2620
+ function findSeedRequirement(doc, id) {
2621
+ const baselines = doc["baselines"] ?? [];
2622
+ for (const baseline of baselines) {
2623
+ const hit = (baseline["requirements"] ?? []).find((r) => r["id"] === id);
2624
+ if (hit) return hit;
2625
+ }
2626
+ return null;
2627
+ }
2628
+ /**
2629
+ * Materialize a change-event batch into a full systemDrift hdf-comparison
2630
+ * against the seed document (ADR-0005 §5): each winning event lifts into the
2631
+ * Requirement_Diff shape the batch engine produces — before from the seed,
2632
+ * after from the event payload, field changes derived by the batch engine's
2633
+ * own computeFieldChanges — under the same fold contract as
2634
+ * applyChangeEvents (dedup, last-value-wins by sequence, tombstone-aware,
2635
+ * warnings never abort). Deterministic: the comparison timestamp is the
2636
+ * latest event occurrence, and seed-side override expiry anchors to the
2637
+ * seed's own timestamp (falling back to the event occurrence when the seed
2638
+ * has none) — never wall clock. Go parity: FoldChangeEventsIntoComparison.
2639
+ */
2640
+ async function foldChangeEventsIntoComparison(seedJson, events) {
2641
+ const doc = JSON.parse(seedJson);
2642
+ const docTimestamp = doc["timestamp"] ?? "";
2643
+ const { byKey, keys } = groupEventChains(dedupEvents(events));
2644
+ const warnings = [];
2645
+ const diffs = [];
2646
+ let maxOccurredMs = Number.NEGATIVE_INFINITY;
2647
+ let asOfFromEvents = "";
2648
+ let systemRef = "";
2649
+ for (const id of keys) {
2650
+ const chain = byKey.get(id) ?? [];
2651
+ const winner = chain[chain.length - 1];
2652
+ if (!winner) continue;
2653
+ if (systemRef === "") systemRef = winner["systemRef"] ?? "";
2654
+ let keyWarned = false;
2655
+ const keyWarn = (kind, message) => {
2656
+ if (!keyWarned) {
2657
+ keyWarned = true;
2658
+ warnings.push({
2659
+ requirementId: id,
2660
+ kind,
2661
+ message
2662
+ });
2663
+ }
2664
+ };
2665
+ const seedReq = findSeedRequirement(doc, id);
2666
+ await verifyEventChain(chain, seedReq, seedReq !== null, keyWarn);
2667
+ const occurred = parseTimestamp(winner["timestamp"]);
2668
+ if (occurred !== null && occurred.getTime() > maxOccurredMs) {
2669
+ maxOccurredMs = occurred.getTime();
2670
+ asOfFromEvents = formatTimestamp(occurred);
2671
+ }
2672
+ const newTs = occurred !== null ? formatTimestamp(occurred) : winner["timestamp"];
2673
+ const seedRef = docTimestamp !== "" ? docTimestamp : newTs;
2674
+ if (winner["state"] === "absent") {
2675
+ if (!seedReq) {
2676
+ keyWarn("absentUnknown", "absent event for a key not present in the seed");
2677
+ continue;
2678
+ }
2679
+ diffs.push({
2680
+ id,
2681
+ title: seedReq["title"],
2682
+ state: "absent",
2683
+ oldEffectiveStatus: computeEffectiveStatus(seedReq, seedRef),
2684
+ changeReasons: [],
2685
+ oldImpact: seedReq["impact"],
2686
+ fieldChanges: [],
2687
+ before: seedReq,
2688
+ after: null
2689
+ });
2690
+ continue;
2691
+ }
2692
+ const after = winner["after"];
2693
+ if (!after) {
2694
+ keyWarn("chainGap", "winning event carries no applicable after payload");
2695
+ continue;
2696
+ }
2697
+ const newStatus = computeEffectiveStatus(after, newTs);
2698
+ if (!seedReq) {
2699
+ if (winner["state"] !== "new") keyWarn("chainGap", "non-new chain for a key the seed does not carry; lifted as new");
2700
+ diffs.push({
2701
+ id,
2702
+ title: after["title"],
2703
+ state: "new",
2704
+ newEffectiveStatus: newStatus,
2705
+ changeReasons: [],
2706
+ newImpact: after["impact"],
2707
+ fieldChanges: [],
2708
+ before: null,
2709
+ after
2710
+ });
2711
+ continue;
2712
+ }
2713
+ diffs.push({
2714
+ id,
2715
+ title: after["title"] ?? seedReq["title"],
2716
+ state: winner["state"],
2717
+ oldEffectiveStatus: computeEffectiveStatus(seedReq, seedRef),
2718
+ newEffectiveStatus: newStatus,
2719
+ changeReasons: winner["changeReasons"] ?? [],
2720
+ oldImpact: seedReq["impact"],
2721
+ newImpact: after["impact"],
2722
+ fieldChanges: computeFieldChanges(seedReq, after, DEFAULT_TRACKED_FIELDS),
2723
+ before: seedReq,
2724
+ after
2725
+ });
2726
+ }
2727
+ diffs.sort((a, b) => a.id.localeCompare(b.id));
2728
+ const asOf = asOfFromEvents !== "" ? asOfFromEvents : docTimestamp;
2729
+ if (asOf === "") throw new Error("cannot derive a comparison timestamp: no events supplied and the seed document has no timestamp");
2730
+ return {
2731
+ comparison: {
2732
+ formatVersion: "1.0.0",
2733
+ comparisonMode: "systemDrift",
2734
+ timestamp: asOf,
2735
+ ...systemRef !== "" ? { systemRef } : {},
2736
+ sources: [{
2737
+ role: "old",
2738
+ label: "Old evaluation"
2739
+ }, {
2740
+ role: "new",
2741
+ label: "New evaluation"
2742
+ }],
2743
+ matching: { primaryStrategy: "exactId" },
2744
+ summary: computeSummary(diffs),
2745
+ baselineDiffs: [],
2746
+ requirementDiffs: diffs,
2747
+ drift: extractDrift(diffs)
2748
+ },
2749
+ warnings
2750
+ };
2751
+ }
2752
+ //#endregion
2262
2753
  //#region src/exit-codes.ts
2263
2754
  /** GNU diff compatible exit codes (--exit-code mode) */
2264
2755
  const EXIT_IDENTICAL = 0;
@@ -2875,6 +3366,6 @@ function buildPackageMap(packages) {
2875
3366
  return map;
2876
3367
  }
2877
3368
  //#endregion
2878
- export { EXIT_DETAILED_BASELINE_CHANGED, EXIT_DETAILED_DRIFT_ONLY, EXIT_DETAILED_ERROR, EXIT_DETAILED_FIXES_ONLY, EXIT_DETAILED_IDENTICAL, EXIT_DETAILED_MIXED, EXIT_DETAILED_REGRESSIONS_ONLY, EXIT_DIFFERENCES, EXIT_ERROR, EXIT_IDENTICAL, classifyChangeReasons, classifyDiffStatus, computeDetailedExitCode, computeEffectiveStatus, computeExitCode, computeSummary, createCciMatchStrategy, createExactIdStrategy, createFuzzyTitleStrategy, createMappedIdStrategy, createSrgCciTiebreakStrategy, createSrgDeterministicStrategy, createVendorFuzzyTitleStrategy, diffBaselines, diffHdf, diffSboms, diffSystems, isV1Format, jaccardSimilarity, levenshteinDistance, matchRequirements, normalizeToV2, normalizedLevenshtein, render, renderCsv, renderJson, renderMarkdown, renderTerminal, tokenize, validateComparison };
3369
+ export { EXIT_DETAILED_BASELINE_CHANGED, EXIT_DETAILED_DRIFT_ONLY, EXIT_DETAILED_ERROR, EXIT_DETAILED_FIXES_ONLY, EXIT_DETAILED_IDENTICAL, EXIT_DETAILED_MIXED, EXIT_DETAILED_REGRESSIONS_ONLY, EXIT_DIFFERENCES, EXIT_ERROR, EXIT_IDENTICAL, applyChangeEvents, changeEventFromPrevious, classifyChangeReasons, classifyDiffStatus, computeDetailedExitCode, computeDisposition, computeEffectiveChecksum, computeEffectiveImpact, computeEffectiveStatus, computeExitCode, computeSummary, createCciMatchStrategy, createExactIdStrategy, createFuzzyTitleStrategy, createMappedIdStrategy, createSrgCciTiebreakStrategy, createSrgDeterministicStrategy, createVendorFuzzyTitleStrategy, diffBaselines, diffHdf, diffSboms, diffSystems, foldChangeEventsIntoComparison, isV1Format, jaccardSimilarity, levenshteinDistance, matchRequirements, normalizeToV2, normalizedLevenshtein, render, renderCsv, renderJson, renderMarkdown, renderTerminal, tokenize, validateComparison };
2879
3370
 
2880
3371
  //# sourceMappingURL=index.js.map