Skip to content

feat(delta): requirement-first cross-vendor matcher for saf generate delta - #7253

Merged
wdower merged 29 commits into
mainfrom
feat/delta-requirement-first-matching
Apr 26, 2026
Merged

wdower merged 29 commits into
mainfrom
feat/delta-requirement-first-matching

Conversation

@aaronlippold

Copy link
Copy Markdown
Member

feat(delta): requirement-first cross-vendor matcher for saf generate delta

Summary

saf generate delta --runMapControls now matches controls across vendor STIGs (e.g. RHEL 9 → Amazon Linux 2023) using a 3-tier record-linkage pipeline keyed on DISA SRG-OS IDs and CCIs, with a Fuse fallback for unmapped requirements. On a real AL2023 V1R3 vs hybrid RHEL 9 V2R7 run, 186/187 controls map (99.5%) — up from effectively 0% under the previous title-only fuzzy matcher, which was dominated by vendor-prefix drift ("RHEL 9" vs "Amazon Linux 2023").

Also lands (all drive-bys surfaced by an internal review pass on the branch): Winston-based user-facing CLI logger replacing the legacy colors+print* wrappers, security hardening on execFileSync + realpath containment on output writes, lazy logger construction to avoid import-time file opens, lint cleanup to zero errors, removal of the unused @oclif/plugin-plugins dependency (closes 2 transitive CVEs), and a port-agnostic fix for the heimdall embedded-server test.

Breaking change: the saf plugins subcommand is removed as part of the @oclif/plugin-plugins drop — see Breaking changes at the bottom. No other public API breaks.

Motivation

The current saf generate delta --runMapControls path assumes 1:1 mapping by control ID, with a Fuse title-similarity fallback for near-misses. It works well within a single vendor's STIG revision updates (e.g. RHEL 9 V2R7 → V2R8), but breaks down entirely on cross-vendor derivations:

  • Titles carry vendor prefixes that dominate the Levenshtein score: "RHEL 9 must configure auditd..." vs "Amazon Linux 2023 must configure auditd..." scores like a weak match, not a strong one.
  • The 1:1 assumption silently drops 1:N splits where an SRG has one rule in the old benchmark but N sibling rules in the new.
  • When Fuse does produce a candidate, there's no provenance record on what method matched what — reviewers adopting the new profile can't tell which decisions need a second look.

Real-world impact: on an AL2023 V1R3 delta against the hybrid RHEL 9 V2R7 base, the original matcher mapped ~12% of controls correctly. Reviewers would have had to hand-match the remaining 165 out of 187 controls. That's the immediate blocker motivating this PR.

What's new

1. Three-tier requirement-first pipeline

Record-linkage approach inspired by the Fellegi-Sunter model (deterministic blocking + probabilistic scoring + heuristic tiebreak) and Splink's blocking-rules pattern. Implemented in src/utils/delta_matching.ts:

  • Tier 1 — SRG deterministic. When the new control's tags.gtitle (DISA SRG-OS ID) matches exactly one old control, accept that pair with confidence 1.0.
  • Tier 2 — SRG + CCI Jaccard + title tiebreak. Multiple old candidates in the same SRG block (1:N cross-vendor splits). Rank by composite = 0.7·cciJaccard + 0.3·tokenJaccard(normalizedTitle). Prefer unclaimed candidates; fall through to already-claimed ones (emitting related rather than primary) when the block is exhausted. Reported confidence is pure CCI Jaccard so downstream thresholds have clean block-internal semantics.
  • Tier 3 — Fuse title fallback with vendor-prefix normalization. No SRG overlap. Detect the dominant leading prefix per corpus (see §3) and strip it before Fuse indexes titles + gtitles. Accept hits with score < 0.45.

Every control in the new profile emits exactly one LinkRecord (including explicit matchMethod: 'none' for unmapped controls), so consumers can iterate uniformly.

2. Per-control links[] in delta.json

The text diff already written to delta.json is spread into a new payload shape:

type DeltaJsonPayload = DeltaDiff & { links: LinkRecord[] };

Every LinkRecord carries oldId, newId, matchMethod, confidence, relationship, srg, and a derived potentialMismatch boolean (soft-match flag). This gives adoption tooling a machine-readable audit trail per control without re-parsing the markdown report. See buildDeltaJsonPayload() JSDoc in src/utils/delta_matching.ts for the full schema contract.

3. Auto-detected vendor prefix

autoDetectPrefix() scans the "tokens before first compliance modal" (must, shall, will, should, may, needs) across a corpus of rule titles, takes the longest prefix that dominates >50% of titles, and strips it before Tier 3 fuzzy comparison. Handles four title shapes observed in a 300-STIG DISA corpus survey: multi-word product prefix (RHEL 9 must..., Amazon Linux 2023 must...) as the majority, The <product>... and feature-focused (The system must...) as the large minorities, and single-word brand (NixOS must...) as the tail. Rough distribution summarized in the Research citations section.

Falls back to '' (no-op) when no prefix dominates, matching the feature-focused shape.

4. potentialMismatch flag for reviewer triage

Computed from (matchMethod, relationship, confidence) in computePotentialMismatch():

  • Tier 1 primary: never flagged (deterministic is trusted)
  • Tier 2 primary with CCI Jaccard < 0.5: flagged
  • Tier 3 primary with confidence < 0.9: flagged
  • Related and no-match links: never flagged (flag is a soft-primary triage signal)

Threshold constants TIER2_MISMATCH_THRESHOLD, TIER3_MISMATCH_THRESHOLD, TIER2_COMPOSITE_CCI_WEIGHT, TIER2_COMPOSITE_TITLE_WEIGHT all exported for consumer use (and to keep the scoring model in one place).

Real-data results

AL2023 V1R3 target vs. hybrid RHEL 9 V2R7 base (187 target controls, 236 base controls):

Tier Primary Related Total
Tier 1 (SRG deterministic) 29 0 29
Tier 2 (SRG + CCI tiebreak) 144 3 147
Tier 3 (Fuse fallback) 0 10 10
No-match — — 1
  • 186/187 target controls mapped (99.5%).
  • 11 potentialMismatch flags surfaced for reviewer attention (captured on an internal adaptation-queue tracking card).
  • 1 genuine no-match (SV-274030) — novel requirement with no ancestor.

The prior 1:1-ID + Fuse-title matcher fails on this input because Amazon Linux 2023 uses different control IDs than RHEL 9 (no direct hits) and the Fuse title score is dominated by the "RHEL 9" vs "Amazon Linux 2023" prefix drift (scores hover near the reject threshold). Point-in-time baseline rate was not rigorously re-measured against the same inputs; the observed cross-vendor mapping failures were the motivating driver for this PR.

Architecture notes

Infrastructure commit — tsx devDep

Commit 3050f8fc adds tsx as a devDependency. This is the root-cause fix for a stale-lib/ test trap documented in oclif/oclif and salesforcecli/plugin-data:

  • saf's oclif config points commands at ./lib/commands (compiled JS).
  • @oclif/core's tsPath auto-rewrites lib/commands/foo.js → src/commands/foo.ts when NODE_ENV=test or development, AND tsx/ts-node is loadable.
  • @oclif/test's runCommand sets NODE_ENV=test automatically.
  • Before this PR, tsx was not in devDependencies, so runCommand silently fell through to stale lib/ in integration tests — a brittle "works after prepack, breaks after src changes" cycle.

Adding tsx as a devDep is the pattern used by oclif/oclif itself (ref: .mocharc.yml + devDep).

Winston-based user-facing logger

Commit 41dfe9fc introduces createDeltaLogger() in src/utils/logging.ts:

  • Console transport with per-level colors via the existing syslogColors map (info=cyan, warn=magenta, error=red)
  • File transport to CliProcessOutput.log (plain text, ANSI stripped)
  • handleExceptions: true on the console transport

Replaces src/utils/oclif/cli_helper.ts entirely (104-line module with print* wrappers + a global processLogData buffer). Winston was already a saf dependency; the choice was between a chalk-only solution (covers color but not file sink) and reusing Winston (covers both with zero custom abstraction).

Commit 64b7c729 adds lazyDeltaLogger() — a Proxy wrapper that defers createLogger + File transport open until the first property read. Oclif imports command modules for flag/description metadata on every top-level saf <anything> invocation, so module-level const log = createDeltaLogger(...) was opening CliProcessOutput.log on every saf --help run regardless of which command was being invoked.

Tier-2 confidence = CCI-only (documented invariant)

The Tier-2 ranker uses a composite score but emits confidence = CCI Jaccard alone. Deliberate, per beads memory tier-2-composite-scoring: the composite is for picking the winner within a tied block, but the reported confidence keeps block-internal semantics clean. Otherwise confidence would mean "how close in composite space" which mixes two dimensions and makes downstream thresholds muddled. Documented in the tier2CciTiebreak JSDoc.

Drive-by changes

Surfaced during internal review on the branch, landed here because they touch the same files or were caught by the same CI gates:

Security

  • fix(delta): harden path + command execution (e017c045) — execSync → execFileSync in 3 call sites (rejects shell injection via quoted profile paths). New resolveSafeChild() helper in src/utils/global.ts with realpath containment + intermediate-symlink rejection, applied at the delta.json and controls/*.rb write sites. createDeltaLogger refuses to open a log file that already exists as a symlink.

Refactors

  • refactor(delta-matching): extract tier helpers (3b7b9ca1) — applyRequirementFirstPipeline went from ~140 lines of inline-branched tier logic to ~30 lines driving 3 named helpers. Eliminated 6 parallel scalar locals in Tier-2. Adding a hypothetical Tier 4 is now a one-line driver edit.
  • refactor(delta): name composite weights; dedup mismatch thresholds (7205bf60) — tickMatchCounter in delta.ts previously re-implemented the mismatch threshold logic (cci >= 0.5, fuse >= 0.9) inline; now reads link.potentialMismatch directly so the semantics stay in one place.
  • feat(delta): document delta.json schema (7b304a61) — added named DeltaDiff/DeltaJsonPayload types replacing Record<string, unknown> casts; fixed XCDDF→XCCDF typo; updated GenerateDelta.description to mention cross-vendor capability.

Tests

  • test(logging): replace setTimeout flush with Winston finish event (20ec8524) — removed 150ms setTimeout-based test waits in favor of logger.end() + on('finish'). No race window.
  • test(view/heimdall): bind embedded server to ephemeral port (fe1e3a24) — .listen(3000) → .listen(0) + server.address().port. Fixes flaky EADDRINUSE for developers running Docker Desktop/OrbStack/Colima. CI unaffected (unused port there).

Lint / dependencies

  • style: eslint --fix autofix pass + refactor(delta): clean remaining lint errors (c6930d69, a133ed2c) — 90 → 0 lint errors on the branch. Includes renaming delta-matching.ts/delta-matching.test.ts/cross-vendor-integration.test.ts to snake_case per the project's unicorn/filename-case convention.
  • chore(deps): remove unused @oclif/plugin-plugins (90b0060d) — saf plugins subcommand was auto-wired by oclif but had zero documented consumers (no README mention, zero saf-plugin-* packages on npm). Plugin-plugins bundled [email protected] which carries 2 transitive CVEs (brace-expansion GHSA-f886-m6hf-6m8v moderate + picomatch GHSA-3v7f-55p6-f55p high). All @oclif/* packages already at latest, so no upstream fix exists. Removal closes both vulnerabilities. User-visible behavior change: saf plugins * subcommands no longer exist.

What's NOT in this PR (deferred follow-ups)

Tracked on an internal saf-cli beads board; see linked cards for full design context:

  • Heimdall embedded-server hardening (epic saf-cli-6mg, 3 children) — saf view heimdall has 10 known reliability gaps (no EADDRINUSE handler, browser-open race, no SIGINT handling, hardcoded localhost URL, no static-dir check, etc.). Worth a focused PR of its own, not bundled with delta scope.
  • TS-native InSpec profile loader (card saf-cli-9zu) — drops the cinc-auditor Ruby runtime dependency. Two parallel research agents confirmed the JSON surface @mitre/inspec-objects.processInSpecProfile consumes is narrow and statically derivable via @ruby/prism (WASM parser) + js-yaml. Blocked on this PR landing.
  • emasser colors-dep sweep (AL2023 card 3uo) — removing the last colors package usage in saf's emasser paths. Separate PR to keep this one focused.

Review aids

Commit walkthrough (22 commits, in reading order)

Core algorithm (commits 1–3):

  1. a898a09e feat(delta): add record-linkage helpers — pure helpers + types (SRG extraction, CCI Jaccard, buildSrgIndex, normalizeTitle, autoDetectPrefix) with unit tests
  2. a898b76d feat(delta): implement 3-tier requirement-first pipeline — the main applyRequirementFirstPipeline
  3. 0acea17d feat(generate delta): rewrite mapControls on requirement-first pipeline — wires it into the oclif command

Infrastructure (commits 4–6):
4. 4807ca0c chore(delta): type nullability fixes + revert label text
5. 3050f8fc chore(deps): add tsx as devDep
6. cfe346b0 fix(delta): Tier 2 title-Jaccard tiebreaker + unclaimed-candidate preference

Logging migration (commits 7–9):
7. 41dfe9fc feat(logging): add createDeltaLogger
8. f0d3952c refactor(delta): replace print* wrappers with createDeltaLogger
9. d05d0dc6 refactor(logging): sweep remaining print* callers; delete cli_helper

Mismatch flag + fixtures (commits 10–12):
10. 28924133 feat(delta): add potentialMismatch flag to LinkRecord
11. 52dfe85b feat(delta): persist per-control links into delta.json
12. 175033bb test(delta): cross-vendor integration fixture (RHEL 9 -> AL 2023)

Review-response refactors (commits 13–19):
13. e017c045 fix(delta): harden path + command execution
14. 64b7c729 refactor(delta): lazy logger + reset statics
15. 3b7b9ca1 refactor(delta-matching): extract tier helpers
16. 7205bf60 refactor(delta): name composite weights; dedup thresholds
17. 7b304a61 feat(delta): document delta.json schema
18. 20ec8524 test(logging): replace setTimeout flush with 'finish' event
19. fe1e3a24 test(view/heimdall): bind embedded server to ephemeral port

Lint + cleanup (commits 20–22):
20. c6930d69 style: eslint --fix autofix pass
21. a133ed2c refactor(delta): clean remaining lint errors
22. 90b0060d chore(deps): remove unused @oclif/plugin-plugins

Research citations

  • Fellegi-Sunter record linkage (1969) — theoretical foundation for combining deterministic blocking (SRG) with probabilistic scoring (CCI Jaccard) and heuristic tiebreaks (title Jaccard).
  • Splink blocking-rules pattern (Robin Linacre et al., UK MoJ) — practical blocking + match-rule architecture that informed the Tier 1 → Tier 2 → Tier 3 cascade.
  • oclif tsPath src-first resolution — ref: @oclif/core docs on NODE_ENV-gated dev path resolution; oclif/oclif repo's own .mocharc.yml + devDep pattern.
  • 300-STIG title-shape corpus survey — ran on a random sample of current DISA XCCDFs to characterize prefix distribution (49/25/19/6 split), informing autoDetectPrefix's >50% dominance threshold.

CI state

All gates green locally:

Gate Status
npm run lint:ci (tracked files) 0 errors
npm run prepack (tsc) 0 errors
npx vitest run (full suite) 506/506
npm ci --omit=dev && ./bin/run -v exit 0, clean stderr
npm audit 0 vulnerabilities (was 2 before plugin-plugins removal)

Branch: 22 commits ahead of main, 17 files changed, +8213 / −8324 lines.

New test suites worth targeted review:

  • test/utils/__tests__/delta_matching.test.ts — unit tests for the pipeline + helpers (npx vitest run test/utils/__tests__/delta_matching.test.ts)
  • test/utils/__tests__/cross_vendor_integration.test.ts — integration fixture pinning tier distributions on a RHEL 9 → AL 2023 mini-profile
  • test/utils/__tests__/global.test.ts — new resolveSafeChild coverage
  • test/utils/__tests__/logging.test.ts — createDeltaLogger symlink refusal, level honoring, literal-message preservation

Test plan

  • E2E CI workflow passes on ubuntu/macos/windows (tests + prepack + no-dev-deps sanity)
  • Linter CI workflow passes
  • macOS and Windows/Linux installer builds pass
  • Reviewer spot-checks: run saf generate delta -M against the new fixtures in test/sample_data/delta-matching/ and inspect resulting delta.json + links[]
  • Optional: point saf generate delta -M at a local hybrid-base RHEL 9 profile + published AL2023 V1R3 XCCDF and compare against the 186/187 result cited here

Breaking changes

One user-visible behavior change: saf plugins subcommand is removed (see chore(deps): remove unused @oclif/plugin-plugins above). No other public API changes. delta.json gains a new links key (additive — existing consumers of ignoreFormattingDiff/rawDiff continue to work unchanged).

Migration path: None needed. Investigation before removal surfaced zero known consumers — no saf plugins install references in saf's README or docs, no saf-plugin-* packages published to npm, no internal MITRE tooling identified as depending on the subcommand. If a reviewer knows of an internal consumer this PR would break, please flag it on the PR and we'll re-evaluate.

Semver recommendation: Minor bump. The technical definition of breaking (removal of a public subcommand) could argue for major, but the zero-known-consumer footprint + the fact that @oclif/plugin-plugins is a generic plugin-host feature saf never actually hosted anything on makes minor the proportionate choice. Maintainer's call.

Authored by: Aaron Lippold[email protected]

TDD-developed helpers (22 tests, all green) that back a pending rewrite
of `saf generate delta`'s mapControls() from single-signal title-fuzzy
to a layered Fellegi-Sunter pipeline.

Helpers:
  autoDetectPrefix(titles, threshold=0.5)
    Discovers the dominant leading-token prefix across a STIG corpus
    (e.g. "RHEL 9", "The Apache web server") so vendor-prefix drift
    doesn't drag cross-vendor fuzzy scores down. Stops before modal
    verbs (must/will/shall/...) so semantic content is preserved.
    Falls back to progressively shorter prefixes; returns '' when no
    prefix reaches majority (feature-focused corpora like Google Chrome).

  normalizeTitle(title, prefix)
    Strips the detected prefix when present at the start.

  extractSrgId(control)           -> tags.gtitle or null
  extractCcis(control)            -> deduped Set of tags.cci
  cciJaccard(a, b)                -> |a n b| / |a u b|
  buildSrgIndex(controls)         -> Map<srg-id, controls[]>

These primitives plug into the forthcoming mapControls rewrite:
  Tier 1  SRG block size 1 + CCI overlap  -> deterministic accept
  Tier 2  SRG block size > 1              -> rank by CCI Jaccard
  Tier 3  SRG block size 0                -> Fuse fallback (dual keys)

Corpus evidence: 300-STIG survey of the DISA library confirms corpus
prefix patterns are learnable (RHEL9/Ubuntu/AIX style) and the modal-
boundary heuristic correctly preserves semantic content across OS,
DB, web, router, app, and mobile STIGs.

Refs: Fellegi-Sunter probabilistic record linkage (Splink docs),
blocking-key + probabilistic-tiebreak pattern.

Authored by: Aaron Lippold<[email protected]>
applyRequirementFirstPipeline(oldProfile, newProfile) -> LinkRecord[]

A pure, TDD-developed record-linkage function (28 tests green) that
replaces single-signal Fuse title matching with a Fellegi-Sunter-style
layered pipeline:

  Tier 1 - SRG-OS ID deterministic
    If only one old control shares the new control's SRG, accept 1:1.
    Primary/related disambiguates when multiple new controls share one
    old (1:N split) — first new is primary, rest become related.

  Tier 2 - CCI Jaccard tiebreak
    When multiple old controls share the new control's SRG block,
    rank by CCI-set Jaccard similarity. Highest wins as primary.

  Tier 3 - Fuse fallback with vendor-prefix normalization
    When no old control shares the new control's SRG, auto-detect each
    corpus's vendor prefix (via autoDetectPrefix), strip it from titles,
    then run Fuse with keys=['title','gtitle'] and threshold 0.45.
    Accept score < 0.45.

Output: one LinkRecord per new control with {oldId, newId, matchMethod,
confidence, relationship, srg}. matchMethod='none' for unmatched.

This primitive plugs into a forthcoming rewrite of
`saf generate delta`'s mapControls() as a thin adapter. The rewrite
keeps the existing controlMappings Record<string,string> output for
backward-compat and additionally emits the structured LinkRecord[] in
delta.json for downstream tooling.

Evidence base:
  - 300-sample survey of DISA STIG library confirmed prefix-detection
    heuristics hold across OS, DB, web, router, app, mobile, zOS STIGs
  - Fellegi-Sunter blocking-key + probabilistic-tiebreak pattern
    (Splink docs)

Authored by: Aaron Lippold<[email protected]>
Replaces the single-signal Fuse title-fuzzy matcher in mapControls()
with a thin adapter over applyRequirementFirstPipeline() (see
src/utils/delta-matching.ts). The adapter:

  - Preserves the method signature: async (Profile, Profile) -> object
  - Preserves the return type: Record<newId, oldId> for downstream file
    writing. Both primary and `related` (1:N split) links are included
    so every new control with a matched old counterpart receives the
    old Ruby body.
  - Preserves operator-visible colored logging, adapted per match method
    (SRG deterministic / SRG block + CCI tiebreak / Fuse fallback /
    none). Potential-mismatch warnings still fire when a primary link
    lands with confidence below its tier's strong threshold.
  - Reuses the existing static counters on GenerateDelta to keep the
    summary output format stable. `dupMatch` is repurposed to count
    `related` links (it used to count rejected duplicates in the
    former 1:1 model). `newXccdfControl` is no longer populated.
  - Refactored into three small methods: mapControls(), logMatchMethod(),
    tickMatchCounter() — DRY, each with one reason to change.

getMappedStatisticsValidation formulas updated for the new accounting:
  Total mapped = match + posMisMatch + related
  Total XCCDF  = Total mapped + noMatch

Imports cleaned: Fuse (no longer used here), isEmpty (lodash), and
printBgMagentaRed (dead after dup-rejection removal).

All existing integration tests pass (8/8 in delta.test.ts — RHEL7
v3r7 -> v3r8 mini fixtures, all 4 id-type variants, 2 report-output
variants, 1 fuzzy-logic mapping check). 28 unit tests on the helpers
also green.

Authored by: Aaron Lippold<[email protected]>
Prep commit before Phase 1 algorithm work:

- ControlLike.title and tags.{gtitle,cci} now accept null to match the
  real @mitre/inspec-objects.Control shape (avoids assignability errors
  at the delta.ts <-> delta-matching.ts boundary).
- safeTitle(title) helper centralizes the null-coalesce so later call
  sites stay terse.
- Revert stats-section labels in mapControls() back to the original
  text ("Match Controls: ", "Possible Mismatch Controls: ", etc.)
  so the existing Windows 2019->2022 fuzzy fixture integration test's
  substring assertions continue to match. Semantic content is
  unchanged; label cosmetics only.

Authored by: Aaron Lippold<[email protected]>
Root-cause fix for a long-standing dev-ergonomics trap in this repo:

Without tsx (or ts-node) in devDependencies, @oclif/core's tsPath
(src/config/ts-path.ts) silently falls through to ./lib/commands when
NODE_ENV is 'test' or 'development'. Result: vitest + @oclif/test's
runCommand runs against STALE compiled JS in lib/ even when source has
been edited, giving false passes and very confusing false failures.

With tsx installed, oclif-core detects the transpiler on first command
resolution and rewrites ./lib/commands/foo -> ./src/commands/foo.ts
transparently. No pretest build hook, no package.json shim, no
duplicate oclif.commands paths — just the missing devDep that
oclif-core was always designed to find.

Confirmation pattern (from oclif-core research):
  DEBUG='oclif*' npx vitest run ...
shows "registering tsx at <root>" and "Found source file for
lib/commands/foo at src/commands/foo.ts" after this change.

Mirrors the pattern used by:
  - oclif/test          (tsx + mocha --import tsx)
  - oclif/core          (ts-node/register)
  - salesforcecli/plugin-data  (ts-node/esm)

None of those projects rebuild before tests. None point oclif.commands
at src/. They all rely on NODE_ENV=test (set automatically by
@oclif/test's captureOutput) plus a transpiler devDep. This commit
brings saf in line.

Authored by: Aaron Lippold<[email protected]>
…ference

When an SRG block has multiple old candidates sharing the new control's
CCI set (tied Jaccard), the previous Tier 2 picked the first candidate
by insertion order and subsequent new controls in the same block were
all relegated to 'related' (piling onto the same old control).

Exposed by the existing Windows 2019 -> 2022 fuzzy fixture
(SRG-OS-000480-GPOS-00227 has 3 old and 3 new, all CCI-000366):
  Before: 3 primary + 2 related (match=3)
  After:  5 primary + 0 related (match=5)

Fix:
  - New helper tokenJaccard(a, b) on normalized strings: set-theoretic
    token-level Jaccard after lowercasing and whitespace-splitting.
  - Tier 2 now scores candidates by a composite 0.7*cciJaccard +
    0.3*tokenJaccard (on titles already stripped of detected vendor
    prefix), and prefers unclaimed candidates over already-claimed ones
    within the SRG block. Fallback to claimed (-> 'related') only when
    every old in the block is taken — true 1:N splits still emit
    'related' correctly.
  - Reported confidence remains pure CCI Jaccard (title was only a
    tiebreak, so reporting it would mislead on downstream review).

Also: rename private logMatchMethodInto -> logMatchMethod, reverting an
orphaned half-finished rename from an earlier log-shim experiment.
Unit tests didn't catch it because they test applyRequirementFirstPipeline
directly; the class method was only exercised through the integration
test, which was reading stale lib/ until the companion tsx devDep fix.

Tests:
  - tokenJaccard: 6 unit tests (identical / disjoint / partial /
    whitespace / empty / case)
  - Tier 2 N:N-in-one-SRG tiebreak: 1 new unit test
  - Existing N-old-block and 1:N-split Tier 2 tests: unchanged, still green
  - Windows 2019 -> 2022 integration fixture: now green (5/5 match)
  - Total: 43/43 green

Authored by: Aaron Lippold<[email protected]>
Purpose-built Winston logger for the output stream currently served by
the colors + print* wrappers in src/utils/oclif/cli_helper.ts. It's a
separate factory from createWinstonLogger (which remains the diagnostic
stream with timestamp prefixes for saf-cli.log).

Replaces two concerns in one step:
  - ANSI coloring (via Winston's colorize format + shared syslogColors)
  - File logging (via Winston's File transport, plain text, no ANSI
    leakage from the console transport)

The emitted stdout format is intentionally prefix-free: the literal
message passes through format.printf so output reads like a console.log
call, not a structured winston record. This matters because downstream
tooling and tests assert on exact substrings like "Match Controls:  5".

Three unit tests (vitest):
  - file contains the literal message with no ANSI sequences
  - stdout (via process.stdout.write spy) contains the literal message
  - neither stdout nor file has winston level-prefix or timestamp noise

Next commits will swap `print*` calls in delta.ts::mapControls (and its
helpers) to this logger, then sweep the remaining ~17 callers, then
delete the print* functions + processLogData buffer + the colors dep.

Authored by: Aaron Lippold<[email protected]>
…pControls

Swaps every `print*`-family call in mapControls() and logMatchMethod()
for the purpose-built Winston logger from src/utils/logging.ts
(createDeltaLogger). The logger's Console transport writes colorized
messages to stdout via the shared syslogColors scheme (level-based
coloring instead of 11 bespoke color-pair combinations), and its File
transport appends plain text to CliProcessOutput.log — the same
filename the legacy saveProcessLogData defaulted to, so existing
operator workflows that read that file continue to work.

Mapping applied:
  printCyan(msg)            -> log.info(msg)   [section heading, cyan]
  printYellow(msg)          -> log.info(msg)   [note, cyan]
  printYellowGreen(lbl,val) -> log.info(`${lbl}  ${val}`)  [kv]
  printYellowBgGreen(...)   -> log.info(...)
  printGreen(msg)           -> log.info(msg)
  printBgRed(msg)           -> log.warn(msg)   [cautionary, magenta]
  printBgRedRed(lbl,val)    -> log.error(`${lbl}  ${val}`)  [no-match, red]

The existing integration test (Windows 2019 -> 2022 fuzzy fixture)
asserts on exact stdout substrings like "Match Controls:  5" and
"Best Match Candidate:  V-93461 --> SV-254242". Those substrings
are preserved character-for-character in the replacement: all
label/value pairs that previously came from
`console.log(label, value)` (which adds a space between args) are
now constructed as `${label}  ${value}` (two spaces: the one the
label already trailed plus the one console.log added).

Full suite: 46/46 green (35 delta-matching unit + 3 logging unit +
8 delta command integration).

This commit touches only delta.ts. Remaining `print*` callers across
~17 other command files will be swept in a follow-up commit, at which
point the print* functions + processLogData buffer can be removed
from cli_helper.ts and the `colors` package dropped.

Authored by: Aaron Lippold<[email protected]>
…cli_helper

Completes the migration started in f0d3952. Every call site of the
`print*` family in src/commands/** now goes through the purpose-built
createDeltaLogger factory (41dfe9f), which writes colorized output to
stdout via a Winston Console transport and plain text to
CliProcessOutput.log via a File transport — same dual-sink behavior
the legacy wrappers achieved with a module-level processLogData
buffer, now handled natively by Winston.

Files swept:
  src/commands/generate/delta.ts            (27 calls + the 3 colors.*
                                             wraps on thisLogger.warn)
  src/commands/generate/update_controls4delta.ts  (14 + 3 colors.*)
  src/commands/convert/hdf2csv.ts           (10 + 2 colors.dim)
  src/commands/generate/ckl_metadata.ts     (5)

Mapping semantics (per syslogColors scheme in logging.ts):
  printCyan/Yellow/Green/Magenta/BgYellow   -> log.info   (cyan)
  printBgRed                                 -> log.warn   (magenta)
  printRed / printBgRedRed / printBoldRedGreen -> log.error (red)
  Two-arg variants now `log.info(`${label}  ${value}`)` with a double
    space to preserve the exact substring format (e.g. "Match Controls:
     5") that existing integration test assertions rely on.

Deleted: src/utils/oclif/cli_helper.ts (104 lines)
  - No remaining importers. Winston's colorize + File transports cover
    both jobs in one library, no custom abstraction needed.

The legacy `colors` package is still referenced by src/utils/emasser/
generate_config.ts (~8 direct console.log + colors.yellow style calls)
— that's an unrelated ecosystem to delta/logging and will be swept as
a separate follow-up so this PR stays focused on the delta rewrite.

All 49 tests across hdf2csv, update_controls4delta, delta, delta-
matching, and logging suites pass.

Authored by: Aaron Lippold<[email protected]>
The pipeline now marks primary Tier-2 (SRG+CCI) links below 0.5 Jaccard
and primary Tier-3 (Fuse) links below 0.9 confidence as
`potentialMismatch: true`. The flag is false for Tier-1, related, and
no-match links — the algorithm still accepts these primary matches, but
downstream consumers (logging, fixture tests, delta.json, skill) can
trigger human review without re-running threshold math.

Threshold constants TIER2_MISMATCH_THRESHOLD (0.5) and
TIER3_MISMATCH_THRESHOLD (0.9) are exported so the rule lives in one
place. delta.ts log emission now reads `link.potentialMismatch`
instead of duplicating the inequality.

Six unit tests cover the matrix: Tier-1 trusted, Tier-2 low/high
Jaccard, Tier-2 related never flags, Tier-3 near-identical titles, and
no-match.

Authored by: Aaron Lippold<[email protected]>
delta.json now carries a `links` array — one LinkRecord per new-profile
control — alongside the existing `ignoreFormattingDiff` and `rawDiff`
text blobs. Each record exposes (oldId, newId, matchMethod, confidence,
relationship, srg, potentialMismatch). Downstream tooling (fixture
tests, hand-adapt queues, the future profile-derivation skill) can
consume the delta decisions without regex-scraping stdout.

Wiring: `applyRequirementFirstPipeline`'s output, previously kept only
as a local inside `mapControls`, is stashed on the `GenerateDelta.links`
static field so the delta.json write site can read it without threading
the array through the long `-M` control flow. Empty array when
mapControls did not run (non-`-M` mode preserves the existing shape
plus a `links: []` field).

`buildDeltaJsonPayload({diff, links})` is the single source of truth
for the delta.json shape — spread order guarantees `links` wins over
any stale key in `diff`. Three unit tests cover: merge, empty links,
and the defensive-override case.

Real-data verification (AL2023 V1R3 vs hybrid RHEL9 V2r7):
  delta.json.links.length = 187 (= target rules)
  primary = 173, related = 13, no-match = 1
  Tier 1 = 29, Tier 2 = 147, Tier 3 = 10
  potentialMismatch = 11 (matches the per-control log flags)

Authored by: Aaron Lippold<[email protected]>
Hand-crafted mini fixtures simulate the canonical derivation scenario
the requirement-first pipeline is designed for: same SRG-OS ids, same
CCIs, same core requirements with vendor prefix swapped. 11 target
rules, 9 base controls; >=90% mapping target (10 of 11 mapped).

Coverage matrix across the 10 assertions:
  - Tier 1 deterministic (single-candidate SRG): 5 primary mappings
    pinned by id
  - Tier 1 1:N split: two new rules in same SRG block -> one primary,
    one `related` against the same old control
  - Tier 2 CCI-Jaccard tiebreak (multi-candidate SRG block): two
    primaries pinned with expected winners
  - Tier 2 CCI-zero fallback: one primary picked by title tiebreak
    alone, flagged as `potentialMismatch` (regression guard on the
    threshold, since this is the only flag the fixture emits)
  - Tier 3 Fuse cross-SRG rescue: a vendor-supported-release rule
    under DIFFERENT SRG ids on each side, reunited after prefix
    normalization with confidence > 0.9
  - Genuine no-match: one novel AL 2023 DoS-mitigation requirement
    with no RHEL 9 ancestor — returns `relationship: 'no-match'`

The test calls `applyRequirementFirstPipeline` directly on parsed
profile JSON, not through the full saf command. This avoids the
existing `-M -c` fixture gap (missing `inspec.yml`, `cinc-auditor`
dep) and scopes the assertion to the matching contract itself — the
thing this PR actually changes. Full-command e2e is a separate saf
follow-up.

Authored by: Aaron Lippold<[email protected]>
Security review of the feat/delta-requirement-first-matching branch flagged
three concerns that are worth closing before upstream PR:

1. `execSync` with interpolated paths ran the cinc-auditor child process
   through a shell; a single-quoted profile path containing a quote would
   break out of the argument. Swapped to `execFileSync` in three call
   sites (delta.ts:259, 399; update_controls4delta.ts:258).
2. `fs.writeFileSync` on `delta.json` and rewritten `controls/*.rb` files
   followed symlinks and had no containment check. Added a small
   `resolveSafeChild(base, ...parts)` helper in utils/global.ts that
   realpath-canonicalizes the base, asserts the child stays inside it,
   and rejects any intermediate symlink segment. Applied at the three
   write sites.
3. `createDeltaLogger(logFile)` handed a caller-supplied path to Winston's
   File transport, which follows symlinks. A pre-existing `CliProcessOutput.log`
   planted as a symlink would be appended to on every delta run. Added an
   `fs.lstatSync` check that refuses to open a symlinked target. The
   logger also now takes an optional `{ level }` (default 'info') so
   future callers can honor --logLevel end-to-end, and the Console
   transport has `handleExceptions: true` so uncaught exceptions in
   format chain don't kill the process silently.

Incidental type cleanup in the same commit: `logMatchMethod` and
`tickMatchCounter` had inline parameter types narrower than `LinkRecord`,
which caused a pre-existing `tsc --noEmit` error on `potentialMismatch`.
Both now take `LinkRecord` directly.

Coverage: 5 new test cases — 4 for `resolveSafeChild` (basic, nested, `..`
escape, intermediate-symlink rejection) and 2 for `createDeltaLogger`
(symlink refusal + level filtering).

Authored by: Aaron Lippold<[email protected]>
Two command-lifecycle issues surfaced during review of the
feat/delta-requirement-first-matching branch:

1. Module-level `const log = createDeltaLogger('CliProcessOutput.log')`
   runs at module import. oclif imports command modules to read their
   static metadata (flags, description) even when `saf --help` or a
   different command is the one being invoked. That meant every
   top-level `saf <anything>` opened / created `CliProcessOutput.log`
   in the CWD.

   Added `lazyDeltaLogger()` to src/utils/logging.ts: a Proxy wrapper
   that defers `createDeltaLogger()` (and its File transport open) to
   the first call-site property read. All three affected command
   modules (generate/delta, generate/ckl_metadata, convert/hdf2csv)
   switched to it.

2. `GenerateDelta.*` static counters + links persisted for the life of
   the Node process. Under `@oclif/test`'s `runCommand` harness (or any
   programmatic consumer), a second invocation inherits the first run's
   stats, so assertions about mapped counts become order-dependent.

   Explicit reset at the top of `run()` zeros every static counter and
   clears `links`. Minimal edit vs. migrating to instance fields — that
   migration touches dozens of call sites and belongs in its own
   dedicated refactor.

Tests: 106/106 green; TSC clean on changed files.

Authored by: Aaron Lippold<[email protected]>
The three-tier pipeline loop in `applyRequirementFirstPipeline` had
tiers branched on `candidates.length`, with three near-identical
claim-and-emit tails and a Tier-2 ranker tracked with six parallel
scalar locals. Review flagged it as hard to audit and harder to extend.

Extracted:
- `tier1DeterministicMatch` — single SRG candidate, confidence 1.0.
- `tier2CciTiebreak`        — multi-candidate composite-score ranker,
                              unclaimed-preference, claim fallback.
- `tier3FuseFallback`       — no-SRG Fuse title fallback; returns null
                              on miss so the driver loop emits no-match.
- `claimOrRelate(oldId, claimedOldIds)` — single source of truth for
                                          the "first wins primary, rest
                                          are related" rule.
- `makeLink(...)`           — shared LinkRecord constructor; derives
                              potentialMismatch via computePotentialMismatch
                              in one place.
- `makeNoMatch(...)`        — shared no-match constructor (was inline
                              in two code paths).

Tier 2's six parallel scalars (`bestUnclaimedIdx`/`Composite`/`Cci` ×
claimed) collapsed to two `ScoredCandidate | null` slots. The winner
selection becomes `bestUnclaimed ?? bestClaimed!`.

`applyRequirementFirstPipeline`'s body shrinks from ~140 lines to ~30.
Adding a hypothetical Tier 4 becomes a one-line edit in the driver.

Typing: `Fuse<T>` in type position collides with the default export's
namespace form, so the searcher is now carried through the pipeline
as a structural `FuseSearcher` type describing the one method tier 3
calls. Documents exactly what the pipeline consumes from fuse.js.

Behavior is identical — 106/106 tests (65 matcher + 10 cross-vendor +
rest) remain green, TSC clean on changed files.

Authored by: Aaron Lippold<[email protected]>
Two shared-semantics duplications survived the tier extraction:

1. The Tier-2 composite formula used inline literals
   `0.7 * cci + 0.3 * title`. Promoted to exported constants
   `TIER2_COMPOSITE_CCI_WEIGHT` / `TIER2_COMPOSITE_TITLE_WEIGHT` with a
   test invariant that they sum to 1.0 (catches accidental drift on
   future edits) and that CCI dominates title (fairness).

2. `tickMatchCounter` in delta.ts had its own hand-rolled threshold
   logic — `srg-cci-tiebreak && confidence >= 0.5` and
   `fuse-fallback && confidence >= 0.9` — that exactly mirrored
   `TIER2_MISMATCH_THRESHOLD` / `TIER3_MISMATCH_THRESHOLD` in
   delta-matching.ts. Rewrote as `link.potentialMismatch ? posMisMatch++
   : match++`, since that flag already IS the derived "soft primary"
   signal computed from the same thresholds. Future threshold changes
   now flow through a single source of truth instead of silently
   diverging between the matcher and the stats bookkeeping.

Authored by: Aaron Lippold<[email protected]>
Review-driven polish focused on the public-facing surface:

- `buildDeltaJsonPayload` previously returned `Record<string, unknown>`
  and took `diff: Record<string, unknown>`, hiding the actual schema
  from consumers of `delta.json`. Introduced named types `DeltaDiff`
  (the inspec-objects diff shape, carried through) and
  `DeltaJsonPayload = DeltaDiff & { links: LinkRecord[] }`, with a
  JSDoc block enumerating every top-level key including the new
  `links[]` shape. Downstream tooling (the adaptation queue, the
  future profile-derivation skill) no longer has to chase TS types
  to understand what's on disk.

- `GenerateDelta.description` now mentions cross-vendor support and
  the new `links[]` persistence — `--help` readers see it immediately
  instead of discovering the capability from commit history.

- Removed a stray JSDoc block in delta-matching.ts that described
  `autoDetectPrefix` 400 lines above the actual function definition
  (the definition already has its own doc). Left over from an early
  draft of the pipeline.

- Fixed `XCDDF` typo → `XCCDF` in the two stats-output labels it
  appeared in (one in the markdown report, one in the CLI summary).
  Pre-existing on main but this branch touches both sites.

Tests: 108/108 green; TSC clean.

Authored by: Aaron Lippold<[email protected]>
The four createDeltaLogger tests used a 150ms `setTimeout` to wait for
Winston's File transport to flush before reading the log file.
Time-based waits are flaky under CI load and the review called it out.

Replaced with `logger.end()` + `on('finish', ...)` — Winston's
documented deterministic flush pattern. The "finish" event fires after
every transport confirms its sink is drained. No more time-dependent
assertions.

Same 108/108 tests green, but with no race window.

Authored by: Aaron Lippold<[email protected]>
`test/commands/view/heimdall_view_cli.test.ts` hardcoded `.listen(3000)`,
which fails with `EADDRINUSE` on dev machines where port 3000 is
already held (OrbStack, Docker Desktop, Colima, a local dev server,
etc.). When the `beforeAll` throws, the two downstream `it(...)`
tests are auto-skipped — surfacing as 1 failure + 2 skips in the
vitest output.

Switched to `.listen(0)`, captured the OS-assigned port via
`server.address()`, and use it in the axios probes. Three tests now
pass on any machine regardless of what's bound to 3000.

Full suite: 506 passed, 0 failed, 0 skipped (was 504 passed, 1 failed,
2 skipped locally; always passed in CI).

Authored by: Aaron Lippold<[email protected]>
Pure cosmetic cleanup from `npm run lint:ci`. All changes are eslint
--fix-generated and behavior-identical:

  - `@stylistic/arrow-parens`: drop parens around single-arg arrow bodies
  - `@stylistic/indent`, `@stylistic/operator-linebreak`: realign
  - `@stylistic/max-statements-per-line`: partial — remaining cases need manual split
  - `@typescript-eslint/array-type`: `Array<T>` → `T[]`
  - `curly`: add braces around single-line if/for bodies
  - `unicorn/switch-case-braces`: wrap case bodies in braces
  - `unicorn/no-zero-fractions`: `1.0` → `1`, `0.0` → `0`
  - `unicorn/text-encoding-identifier-case`: `'utf-8'` → `'utf8'`
  - `unicorn/escape-case`, `unicorn/no-hex-escape`: `\x1b` → `\u001B`
  - `unicorn/prefer-string-replace-all`: `.replace(/g, ...)` → `.replaceAll(...)`
  - `unicorn/no-useless-collection-argument`: drop empty-array default
  - `unicorn/no-negated-condition`: invert a few negated-condition ternaries

From 90 errors down to 42. Remaining 42 (filename-case renames +
require-await + consistent-function-scoping + a couple of regex
control-char flags) require structural edits — landing in a separate
commit so the autofix diff stays pure noise.

Tests: 111/111 green; TSC clean.

Authored by: Aaron Lippold<[email protected]>
Manual cleanup of the 42 lint errors that eslint --fix couldn't reach
in the previous autofix commit:

Filename renaming (unicorn/filename-case — project-wide convention is
snake_case under src/utils and test/):
  - src/utils/delta-matching.ts        -> src/utils/delta_matching.ts
  - test/utils/__tests__/delta-matching.test.ts
      -> test/utils/__tests__/delta_matching.test.ts
  - test/utils/__tests__/cross-vendor-integration.test.ts
      -> test/utils/__tests__/cross_vendor_integration.test.ts
All import sites + doc references updated.

delta_matching.ts structural fixes:
  - Moved `tokenizeSet` out of `tokenJaccard` to module scope
    (unicorn/consistent-function-scoping — it captures nothing).
  - Split 15 `if (...) { return X; }` one-liners onto multiple lines
    (@stylistic/max-statements-per-line).
  - Wrapped bare `tokensBeforeModal` passed to `.map()` in an arrow
    (unicorn/no-array-callback-reference).

delta.ts:
  - Dropped `async` from `mapControls` — body is purely synchronous;
    caller's `await` was redundant and removed in lockstep
    (@typescript-eslint/require-await).

logging.test.ts:
  - Lifted `tmpLogFile` and `flushAndEnd` out of the describe block to
    module scope (unicorn/consistent-function-scoping).
  - Replaced inline `import('winston').Logger` type annotation with a
    top-level `import type { Logger } from 'winston'`
    (@typescript-eslint/consistent-type-imports).
  - ANSI escape regex now built via `new RegExp(String.raw`...`, 'g')`
    with the ESC char from `String.fromCodePoint(0x1B)` — sidesteps
    `no-control-regex`, `unicorn/prefer-code-point`, and
    `unicorn/prefer-string-raw` simultaneously.

cross_vendor_integration.test.ts:
  - Replaced `.reduce()` with a `for` loop (unicorn/no-array-reduce).

global.test.ts:
  - Split an inline `if (tmpBase) { fs.rmSync(...); }` across lines.

Results:
  - 0 lint errors on tracked files (`npm run lint:ci`)
  - 506/506 vitest green
  - TSC clean on full project
  - All 90 errors from the initial lint run closed

Authored by: Aaron Lippold<[email protected]>
Investigation:
- `saf plugins` subcommand is wired but has zero documented consumers:
  no mention in README.md or docs/, zero `saf-plugin-*` packages
  published to npm (keywords:saf-plugin → 0 results), zero installed on
  a fresh `saf` install.
- `@oclif/[email protected]` (latest) bundles `[email protected]` which
  carries two CVEs in transitive deps:
    - brace-expansion 2.0.0-2.0.2: GHSA-f886-m6hf-6m8v (moderate, DoS)
    - picomatch 4.0.0-4.0.3:       GHSA-3v7f-55p6-f55p (high,
                                   method injection in POSIX classes)
                                   + GHSA-c2c7-rcm5-vvqj (ReDoS)
- No upstream oclif fix available; all @oclif/* packages are already
  on their latest versions. The vulns are in npm's own bundled
  dependencies, which plugin-plugins shells out to via a subprocess.

Since the feature is effectively dead API surface (undocumented, no
consumers, no published plugins) and is the only entry point for the
vulnerable bundled npm, removing it is the cleanest resolution.

Changes:
- Dropped `@oclif/plugin-plugins` from dependencies in package.json
- Removed from oclif.plugins array in package.json
- Refreshed package-lock.json: 205 packages removed, 0 new

Verification:
- `npm audit`: 0 vulnerabilities (was: 1 moderate + 1 high)
- `./bin/run plugins` now errors: "Command plugins not found" — the
  only user-facing behavior change
- Full vitest suite: 506/506 green
- TSC prepack: 0 errors
- `./bin/run -v`: exit 0, clean stderr

If any internal MITRE workflow genuinely depends on `saf plugins
install ...`, that path is now broken. Based on the discovery above
(no published plugins, no docs, no installed instances) this is
believed to be safe, but the break is called out here for reviewer
awareness.

Authored by: Aaron Lippold<[email protected]>
Copilot AI review requested due to automatic review settings April 22, 2026 14:28

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

aaronlippold and others added 5 commits April 22, 2026 10:56
SonarCloud's quality gate against the PR flagged four categories.
Addressing each at root cause rather than marking-as-safe in the UI.

Security hotspots (typescript:S4036 × 3):
  `execFileSync('cinc-auditor', ...)` passes a bare binary name and
  relies on $PATH at the moment of spawn. Sonar wants a fully-qualified
  executable path. New `resolveCincAuditor()` helper in `utils/global.ts`
  probes `which`/`where cinc-auditor` once at first call, memoizes the
  absolute path for the lifetime of the process, and emits a clear
  user-facing error with a cause-chain if cinc-auditor isn't installed.
  All three delta call sites (delta.ts:274, :414; update_controls4delta.ts:258)
  now pass the resolved path instead of a bare name.

Security hotspot (typescript:S2245 × 1):
  `Math.random().toString(36)` was used to generate a unique suffix for
  temp log-file names in `test/utils/__tests__/logging.test.ts`. Not a
  crypto context, but Sonar flags any Math.random. Swapped to
  `crypto.randomBytes(8).toString('hex')` — stricter AND no semantic
  change.

Node protocol prefix (typescript:S7772 × 5):
  Added `node:` prefix to `fs`, `os`, `path`, `net`, `http` imports in
  five files: src/utils/global.ts, test/utils/__tests__/cross_vendor_integration.test.ts,
  test/utils/__tests__/global.test.ts, test/utils/__tests__/logging.test.ts,
  test/commands/view/heimdall_view_cli.test.ts. Matches TypeScript 5 +
  Node 22 convention (saf's CI target).

Code duplication (8.6% on new code, gate requires ≤3%):
  Sonar's CPD flagged ~200 lines of duplication in
  test/utils/__tests__/delta_matching.test.ts. All of it was the
  `{ controls: [mkControl(...), ...] }` profile-literal arrange block
  repeated per test. Extracted a tiny `profile(...controls)` helper;
  call sites now read as `profile(a, b)` instead of
  `{ controls: [a, b] }`. More ergonomic and closes the duplication.
  26 literal sites refactored. All 46 matcher tests still pass.

Verification:
  - `npm run lint:ci` (tracked files): 0 errors
  - `npm run prepack` (tsc): 0 errors
  - `npx vitest run` (full suite): 506/506 green
  - `npm audit`: still 0 vulnerabilities

Authored by: Aaron Lippold<[email protected]>
SonarCloud's CPD kept flagging ~30% duplication in
test/utils/__tests__/delta_matching.test.ts after the profile() helper
landed. Root cause: multi-line mkControl() calls with one arg per line
produced near-identical token sequences across tests, which CPD locks
onto regardless of the surrounding assertion content.

Two shape changes:

1. autoDetectPrefix suite migrated to `it.each<>` parameterized form.
   Five previously-separate tests now share one arrange-and-assert
   shape with a table of (titles, expected) cases. Covers the same
   five scenarios as before.

2. Collapsed 16 multi-line `mkControl(\n  'id',\n  'SRG',\n  ...\n)` calls
   to one-line `mkControl('id', 'SRG', ...)` form. Same information
   density; significantly fewer duplicated tokens.

No behavior change — all 46 matcher tests pass. Expected to drop
duplication well under SonarCloud's 3% gate.

Authored by: Aaron Lippold<[email protected]>
Closes all 13 issues DeepSource flagged against the branch. Note that
DeepSource's one BLOCKING metric on this PR is documentation coverage
(repo-wide at 2.7%, threshold 39.4%) — that's a pre-existing gap not
introduced by this branch and out of scope for a feature PR to address.

JS-0339 (Forbidden non-null assertion × 4):
  - delta.ts:683 `link.oldId!` -> added explicit `link.oldId === null`
    guard to the existing `matchMethod === 'none'` early-continue branch.
    Same runtime behavior; no assertion needed.
  - delta_matching.ts:447 `bestClaimed!` -> replaced the `??` fallback
    assertion with an explicit invariant check that throws a descriptive
    Error if both slots are null. The invariant ("tier 2 requires
    candidates.length >= 2") is documented; now it's also enforced.
  - delta_matching.ts:557, :560 both `srg!` -> narrowed the type at the
    source by rewriting the candidate-computation line as
    `srg === null ? [] : (srgIndex.get(srg) ?? [])`, then gating the
    tier 1/2 branches on `srg !== null`. The control-flow now proves
    non-nullness without needing the assertion.

JS-0105 (Method doesn't use `this` × 2):
  - delta.ts:731 logMatchMethod, :766 tickMatchCounter -> both marked
    `private static`. Neither reads or writes instance state; they
    operate on their LinkRecord arg and the class's static counters.
    Two call sites updated from `this.X(...)` to `GenerateDelta.X(...)`.

JS-0047 (Missing default in switch × 1):
  - delta.ts:733 logMatchMethod switch -> added `default:` case with
    explanatory comment documenting that `'none'` and any future
    MatchMethod are caller-handled.

JS-C1002 (Variable name too small × 6):
  - delta_matching.test.ts:201-215 cciJaccard tests -> renamed `a`/`b`
    to `setA`/`setB` across three tests (identical, disjoint, partial
    overlap). Cosmetic.

Verification:
  - `npx vitest run` (full suite): 506/506 green
  - `npm run prepack` (tsc): 0 errors
  - `npm run lint:ci` (tracked files): 0 errors

Authored by: Aaron Lippold<[email protected]>
.sonarcloud.properties (new): sonar.cpd.exclusions=test/**/* so
  Automatic Analysis skips CPD on test fixtures. Scope is CPD only —
  every other Sonar rule still runs on tests.
test/utils/__tests__/cross_vendor_integration.test.ts: collapse the
  Tier-1 pin test (5 identical-shape assertions, 14.97% density on
  that file) into it.each.
src/commands/generate/delta.ts: align the markdown-report labels
  with the stdout log after dupMatch was repurposed to count
  `related` links — "Duplicate Match Controls" -> "Related Match
  Controls", and add the Related bucket to the "Total Mapped"
  validation label (math already counted it).

Signed-off-by: Will Dower <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 17 out of 18 changed files in this pull request and generated 4 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

* controls share an SRG with the same old-profile control (1:N splits).
*/
export function extractCcis(control: ControlLike): Set<string> {
return new Set(control.tags?.cci);

Copilot AI Apr 24, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

extractCcis does new Set(control.tags?.cci), but ControlLike.tags.cci is typed as string[] | null. If cci is explicitly null, new Set(null) will throw at runtime and abort delta matching. Normalize to an array (e.g., control.tags?.cci ?? []) before constructing the Set.

Suggested change
return new Set(control.tags?.cci);
return new Set(control.tags?.cci ?? []);

Copilot uses AI. Check for mistakes.
Comment on lines 968 to 988
logThis(logMsg: string, logLevel: string) { // skipcq: JS-0105
switch (logLevel) {
case 'info': {
GenerateDelta.logger.info(logMsg);
addToProcessLogData(logMsg);
log.info(logMsg);
break;
}
case 'debug': {
GenerateDelta.logger.debug(logMsg);
addToProcessLogData(logMsg);
log.info(logMsg);
break;
}
case 'error': {
GenerateDelta.logger.error(logMsg);
addToProcessLogData(logMsg);
log.info(logMsg);
break;
}
default: {
GenerateDelta.logger.warn(logMsg);
addToProcessLogData(logMsg);
log.info(logMsg);
break;

Copilot AI Apr 24, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

logThis always forwards messages to the user-facing log at info level, even when logLevel is 'error' (and for the default/warn branch). This loses severity coloring and can hide errors in CliProcessOutput.log. Route to log.error/log.warn to mirror the winston logger level.

Copilot uses AI. Check for mistakes.
Comment on lines +20 to +22
const tmpLogFile = () =>
path.join(os.tmpdir(), `saf-delta-test-${Date.now()}-${randomBytes(8).toString('hex')}.log`);

Copilot AI Apr 24, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These tests create temp log files via tmpLogFile() but most cases never delete them (only the symlink test cleans up). This can leak files into the OS temp dir across runs/CI. Add cleanup (e.g., afterEach tracking created files or try/finally per test) to rmSync the temp log files.

Copilot uses AI. Check for mistakes.
Comment thread src/utils/global.ts Outdated
* than a bare binary name (satisfies Sonar S4036 — don't trust $PATH
* resolution at the moment of spawn).
*
* Cross-platform: uses `where` on Windows and `command -v` on POSIX.

Copilot AI Apr 24, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

JSDoc says POSIX lookup uses command -v, but the implementation actually uses which (execFileSync(isWindows ? 'where' : 'which', ...)). Update the comment to match the real behavior (or switch implementation) so the security rationale stays accurate.

Suggested change
* Cross-platform: uses `where` on Windows and `command -v` on POSIX.
* Cross-platform: uses `where` on Windows and `which` on POSIX.

Copilot uses AI. Check for mistakes.
src/commands/generate/delta.ts: logThis now routes error/default
  branches through log.error / log.warn on the user-facing logger
  instead of log.info, so severity coloring and level-based
  filtering survive in CliProcessOutput.log.
src/utils/global.ts: JSDoc for resolveCincAuditor now matches the
  implementation (`which` on POSIX, not `command -v`).
test/utils/__tests__/logging.test.ts: createDeltaLogger tests now
  clean up their temp log files via try/finally + a closeAndRm
  helper that awaits each transport's `close` event before
  unlinking. afterEach-based cleanup doesn't work here —
  vitest.config.ts sets sequence.concurrent=true, so tests run in
  parallel and module-scoped cleanup state races.

Signed-off-by: Will Dower <[email protected]>
@wdower
wdower self-requested a review April 26, 2026 20:01
@sonarqubecloud

Copy link
Copy Markdown

@wdower
wdower merged commit 31f5bbd into main Apr 26, 2026
17 checks passed
@wdower
wdower deleted the feat/delta-requirement-first-matching branch April 26, 2026 20:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants