Files
msd-core/scripts/lib/drift-scan.cjs
Tom Boucher bbdf7e8e84 chore(#4654): add local/no-unconfined-path-join and drain it to zero — Phase 4 of #4636 (#4674)
* chore(#4654): add local/no-unconfined-path-join and drain it to zero

Phase 4 of epic #4636 — the ratchet, and the phase that makes the epic hold.

THE MEASUREMENT THAT RESHAPED THE PHASE. An AST census (the repo's own parser,
not grep) found what the epic never enumerated: ADR-4650 named seven containment
implementations; `src/` alone held roughly 24 more hand-rolled gates across ~13
files, several guarding a write or an `fs.rmSync`. Two verified by reading rather
than pattern-matching — `research-store.cts` comments its own as "ensure the
resolved file path stays inside the store dir" immediately before a write, and
`capability-lifecycle.cts` gates `fs.rmSync` with one.

So the epic's Done-when "one containment predicate, used at every site" was FALSE
when Phase 3 reported it satisfied. It is true now: the rule is clean across
src/, scripts/, gsd-core/bin/ and hooks/ with an EMPTY allowlist.

WHY NOT THE RULE THE ISSUE PROPOSED. #4654 proposed flagging `path.join` whose
first argument is a managed root and whose later arguments derive from argv. That
is a taint analysis over 2046 call sites, in ESLint, without type information;
"derives from argv" is not locally decidable. Any approximation either floods or
is trivially evaded, and a rule that fires on hundreds of correct sites earns an
allowlist of hundreds — the opposite of a ratchet. What is actually duplicated is
the COMPARISON, not the join, and that has one recognizable shape.

  Arm 1  X.startsWith(Y + sep)            the hand-rolled containment idiom
  Arm 2  a containment predicate called as a bare statement, answer discarded

Arm 2 is the issue's "asserts the result was narrowed, not merely that a helper
was called". Its example `validatePath(x, root).resolved` is already
structurally impossible — Phase 3 un-exported `validatePath` — so the remaining
expressible failure is ignoring the answer, which is the defect that recurred
five times in this epic. The census found exactly one live instance
(`milestone.cts:1643`); it now returns the proven `ContainedPath` so consumers
stop re-deriving the path the comment above it was extracted to stop them
re-deriving.

The rule deliberately does NOT try to catch validate-one-path-use-another where
the answer is used but a different variable flows onward. That needs flow
analysis; the branded `ContainedPath` from Phase 3 is the defense there, and the
two are complementary.

PER-SITE FAMILY CHOICE, NOT A DEFAULT. Phase 3's lesson binds: collapsing a
lexical site onto the realpath family broke four tests and was caught only by the
matrix. Every migrated site was triaged individually. The six
installer-migrations tree-walks and the six capability-lifecycle gates take the
LEXICAL family because their operands are already realpath-resolved and they
deliberately treat the final component as a link; boundary sites take realpath.

TWO SITES WITH AN INVERTED CONTRACT, which a mechanical swap would have broken.
`installer-migrations.cts:127` and `runtime-artifact-install-plan.cts:144` REJECT
`target === root` by contract, while the canonical comparison ACCEPTS it. Swapped
naively, a migration could `rmdir` the user's config root and a third-party
descriptor could write at configHome itself. Both keep `=== root` as an explicit
additional arm alongside the predicate call — the predicate decides containment,
the call site keeps its own extra condition (ADR-4650 decision 6).

ONE DUPLICATE DELETED OUTRIGHT: `planning-inspect.cts`'s `isWithinRoot` was
byte-identical to `isContainedIn` and said so in its own docstring.
`isContainedIn` is now exported for callers that have already resolved both
operands and need only the comparison, with a doc note that a caller which has
NOT resolved them must use a full predicate instead.

THE MARKER, AND WHY IT IS NOT THE ALLOWLIST. Nine sites are justified holdouts and
carry `// allow-handrolled-containment: <reason>` with a mandatory, reviewable
reason. Two justifications: (a) not a containment decision — an ancestor-walk loop
condition, sub-repo grouping, worktree identity matching, declared-path coverage;
(b) it IS containment but the canonical predicate is unreachable —
`capability-validator.cjs` is a committed pre-build `.cjs` and the compiled
`security.cjs` is untracked build output, so requiring it would break a fresh
clone. `scripts/lib/drift-scan.cjs` runs under `lint:ci` with the same exposure.
The marker was renamed from `allow-lexical-prefix-match` mid-phase because that
name asserted only (a) and would have stated something false at the (b) sites.

A marker suppresses BEFORE the violation counter increments, so a file whose
every occurrence is marked still reports `staleAllowlistEntry` — otherwise a
drained entry lingers and silently re-permits the site later.

DEMONSTRATED RED, per #4654: a hand-rolled copy reintroduced into a real `src/`
file made `npm run lint` fail with the rule's full guidance message; removing it
returned the tree to clean. Both halves recorded — red alone proves nothing,
since a rule red for an unrelated reason looks identical.

DISCLOSED: `defaultRequireFromInstallRoot` (gsd-tools.cjs) previously carried two
distinct rejection messages and two manual realpath calls; routing it through
`tryWithinRoot` collapses them to one message, and a missing module now surfaces
as MODULE_NOT_FOUND rather than ENOENT. No test asserts either message. The
security property is preserved and slightly strengthened — the candidate is
realpathed and containment re-checked, and the dangling-symlink oracle closure
comes along with it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(#4654): record the containment ratchet in CONTEXT.md and the security model

Both entries previously described the seam without the thing that keeps it a
seam. They now state what the rule bans, and — more usefully for whoever reads
this next — what it deliberately does NOT attempt: deciding per path.join call
whether an argument came from user input. That question is not locally
decidable, and an approximation across ~2000 join sites would earn an exemption
list of hundreds, which is the opposite of a ratchet.

Also records the marker's two legitimate justifications and that its reason is
mandatory, so the escape stays reviewable rather than becoming a mute button.

Glossary gate 270 refs exit 0; install-tree goldens and CONTEXT-INDEX.json
regenerated and confirmed byte-identical rather than assumed — which also
confirms eslint-rules/ is not a shipped path.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(#4654): close review findings and the two matrix failures

MATRIX FAILURE 1 — a collapsed message broke a negative-proof test, and my
evidence for collapsing it was wrong. I searched tests/ for the literal string
"resolves outside its install root", found nothing, and reported that no test
asserted it. The test matches a REGEX SUBSTRING, /outside its install root/, so
the literal search missed it. What broke was "NEGATIVE PROOF: a symlinked module
pointing OUTSIDE the install root is not loaded" — the test guarding the exact
property I claimed was preserved. defaultRequireFromInstallRoot now does both
checks again with both messages byte-identical, each routed through the
canonical predicate, which is better than the original since that hand-rolled
both comparisons.

MATRIX FAILURE 2 — shipped migrations are checksum-locked, and a marker cannot
serve there. migrationChecksum hashes plan.toString(), which INCLUDES comments,
so a suppression marker inside a plan body drifts the baseline exactly as an
edit does. Measured: with markers in place, two of the four still differed from
their committed checksums. The four shipped bodies are now byte-identical to
next, and the rule's config excludes those four paths BY NAME rather than by a
directory wildcard, so a NEW migration is still covered. Six containment
comparisons stay un-ratcheted there; that gap is recorded in the rule's Known
gaps, in CONTEXT.md and in the security model rather than left implicit.
Justification (c) is removed from the marker's documented reasons, because a
marker was proven unable to express it.

ADVERSARIAL REVIEW — the sharpest finding was that the rule banned the CORRECT
shape while permitting the incorrect one: startsWith(root) with no separator is
the genuinely unsafe form, since it accepts a sibling such as root-evil, and my
own test blessed it as valid. Flagging every bare startsWith would swamp the
rule, so that stays a STATED gap rather than a silent one. Closed for real: the
template-literal spelling, which the census never saw because it only inspected
plus-concatenation — that surfaced TWELVE more sites, now triaged and migrated.
A separator reached through a const alias is now resolved via scope analysis.
And isContainedIn, exported in Phase 3, was missing from the discarded-result
set, so a bare no-op call went unflagged on the one function the epic funnels
through.

SECURITY REVIEW — the marker could over-suppress two ways: a block comment
worked identically to a line comment, and one marker silently covered every
violation sharing its line. It now requires a Line comment positioned after the
flagged node ends, so it anchors to the node it trails. Four sites had dropped
an unreachable-but-deliberate equality rejection against the root; each is
restored as the call site's own arm. eslint.config.mjs still documented the OLD
marker token, which my rename missed — it would have sent the next author in
circles.

A FALSE GREEN, recorded because it nearly stuck: lint:ci reported exit 0 from a
stale eslint cache while twelve real violations existed. Every lint check here
now clears the cache first.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(#4654): anchor a suppression marker to the violation it actually trails

The matrix caught this; my own test caught it, on its first execution. The case
"two violations on one line: trailing marker suppresses only the one it trails"
expected 1 error and got 0 — both were suppressed.

ROOT CAUSE: the anchoring accepted any Line comment on the node's line whose
range started at or after the node's end. A trailing marker at the END of a line
sits after EVERY node on that line, so that condition held for all of them.
"After the node" does not identify WHICH node the marker trails. The fix reads
as correct and is not.

FIX: deferred reporting. Violations accumulate during traversal instead of being
reported immediately; at Program:exit each marker claims exactly ONE pending
violation — the one on its line whose end is nearest before the marker begins —
and every unclaimed violation is then counted and reported. One marker, one
suppression. An earlier violation sharing the line is still reported, which is
the property the security review asked for and the previous attempt only
appeared to deliver.

The counter now increments at flush time rather than during traversal, so a
suppressed occurrence still does not keep an allowlist entry alive.

AND A TOOL THAT SHOULD HAVE EXISTED BEFORE THE FIRST MATRIX RUN. `node --test`
is hard-blocked here, so this rule's test file could only ever be executed on
the remote matrix — which is why a broken anchoring shipped into a run. ESLint's
programmatic Linter API is not a test runner, and exercising the rule through it
verifies every case locally in seconds. All 24 now pass locally, including the
two-on-one-line case that failed remotely. That loop should have been built
before the rule was first sent to the matrix rather than after it failed twice.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* chore(#4654): backfill PR 4674 into the changeset and complete 70-docs.json

The phase gate requires enablementSequence and the Diataxis quadrants; 70-docs
now carries both, with the how-to quadrant skipped for a stated reason rather
than an empty field. The audience for this deliverable is a contributor who
trips the rule, and the task-oriented guidance reaches them in the ESLint
message itself — which names the correct predicate, says how to choose between
the realpath and lexical families, cites the Phase 3 regression caused by
choosing wrong, and gives the marker syntax. A docs/how-to page would be a
second, driftable copy read by nobody at the moment of failure.

enablementSequence is recorded as what it actually is: a VERIFICATION sequence,
not an enablement one. The rule is never off, so there is no off-to-on
transition to describe.

scripts/lint-docs-required.cjs now passes (ok_docs_updated) — it could not
evaluate against the mandated pr:0 placeholder.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: sim <sim@local>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-12 22:17:46 -04:00

309 lines
14 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
'use strict';
/**
* Shared anti-divergence scanner machinery (epic #3180, ADR-3180 Decision 4).
*
* Extracted from `scripts/lint-plan-count-drift.cjs` (#3183) so that
* `scripts/lint-milestone-window-drift.cjs` (#3184) and any future
* `scripts/lint-<derivation>-drift.cjs` guard consume ONE tree-walk /
* root-confinement / literal-tokenizer / sanitizer implementation instead of
* each copying it verbatim — the exact generative-fix-divergence class this
* epic exists to remove, now applied to the guards themselves (see
* `.gsd/phase/refactor-3184-milestone-window-single-owner/40-design.md`,
* "Rejected: let the new drift guard copy Phase 1's tree-walk /
* root-confinement / sanitizer").
*
* `lint-plan-count-drift.cjs` re-exports every symbol it exported before this
* extraction (`readRegexLiteralAt`, `MAX_REGEX_LITERAL_LEN`, `isInsideRoot`,
* `sanitizeForReport`), so `tests/plan-count-single-owner.test.cjs` — the
* ReDoS and root-confinement regression net for this exact machinery —
* continues to pass unchanged and is the regression net for this move too.
*/
const fs = require('node:fs');
const path = require('node:path');
// Longest regex literal this scanner will consider, in characters. Real
// plan/summary filename filters (and milestone-window regex literals) are far
// shorter; the bound is what keeps the scan linear. The tokenizer restarts at
// every `/` on the line (so that a literal preceded by a stray unpaired `/`
// is still found, matching the previous regex's "find anywhere" behaviour),
// which without a per-literal bound would be quadratic on a pathological
// line. With it the whole-line cost is O(n * MAX_REGEX_LITERAL_LEN) with no
// backtracking at all.
const MAX_REGEX_LITERAL_LEN = 400;
// Directory names this scanner never descends into or reports out of —
// `.git` (repo internals, e.g. a persisted CI token in `.git/config`),
// `node_modules` (thousands of third-party files, none of them authored
// source), `dist` (build output). Named once and used at BOTH skip sites
// below: the cheap `entry.name` fast path in `walk`, and the resolved-path
// component check in `isUnderSkippedDir` — a symlink whose OWN name is not
// in this set but whose target resolves through a directory that IS (e.g.
// `src/g -> ../.git`, `src/nm -> ../node_modules`) must still be skipped, or
// the name-only check is a trivial bypass.
const SKIP_DIR_NAMES = new Set(['node_modules', 'dist', '.git']);
/**
* Read the JS regex literal starting at `line[start]` (which must be `/`).
* Returns `{ text, end }` — `text` includes the delimiters and any trailing
* flags, `end` is the index one past the literal — or null if no literal
* closes within MAX_REGEX_LITERAL_LEN characters.
*
* Single left-to-right pass, no backtracking. It models the two constructs a
* backtracking pattern gets wrong, which is why this is a tokenizer and not a
* regex:
* - `\x` escapes consume BOTH characters, so an escaped `\/` never
* terminates the literal;
* - inside a `[...]` character class a bare `/` does NOT terminate, so
* `/PLAN[\\/].*\.md$/` is one literal rather than two fragments. The
* previous regex silently MISSED every re-derivation using a
* cross-platform path-separator class for exactly this reason.
*/
// Deterministic regression seam for the MAJOR-2 bound (issue #3951/#3987): a
// counter of how many characters this tokenizer has actually examined, so a
// test can assert the bound HOLDS (total work stays a small linear multiple
// of the number of scan attempts × MAX_REGEX_LITERAL_LEN) without resorting
// to a wall-clock elapsed-time assertion, which this repo's test rules ban
// ("Clock Seams: Do not assert on wall-clock time.") and which is exactly
// what flaked on a slow shared CI runner. `resetRegexScanStats`/
// `getRegexScanStats` are read-modify-reset around a single scan under test;
// they are process-global and NOT safe under concurrent scans, which is fine
// for this synchronous, single-threaded CLI tool and its tests.
let regexScanStats = { calls: 0, charsExamined: 0 };
function resetRegexScanStats() {
regexScanStats = { calls: 0, charsExamined: 0 };
}
function getRegexScanStats() {
return { ...regexScanStats };
}
function readRegexLiteralAt(line, start) {
if (line[start] !== '/') return null;
regexScanStats.calls++;
const limit = Math.min(line.length, start + MAX_REGEX_LITERAL_LEN);
let inClass = false;
let i = start + 1;
for (; i < limit; i++) {
const ch = line[i];
if (ch === '\\') {
i++; // escape consumes the next character, whatever it is
continue;
}
if (ch === '\r' || ch === '\n') {
// a literal cannot span lines
regexScanStats.charsExamined += i - start;
return null;
}
if (ch === '[') {
inClass = true;
} else if (ch === ']') {
inClass = false;
} else if (ch === '/' && !inClass) {
// Trailing flags are bounded by the SAME `limit` as the literal body
// itself (not `line.length`) — a literal followed by an unbounded run
// of lowercase letters must not make `text` grow past
// MAX_REGEX_LITERAL_LEN either.
let end = i + 1;
while (end < limit && line[end] >= 'a' && line[end] <= 'z') end++;
regexScanStats.charsExamined += end - start;
return { text: line.slice(start, end), end };
}
}
regexScanStats.charsExamined += limit - start;
return null;
}
// Symlinks report `isDirectory()`/`isFile()` as false on the Dirent from
// `readdirSync`, so a symlinked `.cts` (or a symlinked directory containing
// one) was previously invisible to this scanner — an evasion of a guard
// whose stated design principle (ADR-3180 Decision 4a) is whole-repo
// discovery with no allowlist. Resolve each entry with `fs.statSync` (which
// follows symlinks) to classify it, skipping broken links. `ctx.visitedRealDirs`
// guards against a symlink cycle sending `walk` into infinite recursion.
//
// Every sibling drift guard in `scripts/` that does NOT import this module
// (`lint-phase-id-drift.cjs`, `lint-package-identity-drift.cjs`,
// `lint-portable-timeout.cjs`, `lint-test-file-count.cjs`,
// `lint-allow-test-rule-refs.cjs`) uses the `Dirent` classification straight
// off `readdirSync` and does NOT follow symlinks at all. This scanner follows
// them so a symlinked source file cannot evade ADR-3180 Decision 4a's
// whole-repo discovery — root confinement (`isInsideRoot` below) is the price
// of doing so: without it, a symlink planted anywhere under a scan directory
// could walk this scanner out to read and report arbitrary files elsewhere on
// disk.
//
// DIRECTORY vs FILE symlinks are confined to two DIFFERENT roots, tracked as
// `ctx.scanDirRoot` (the realpath of the current top-level scan-dir entry,
// e.g. `<realRoot>/src`) vs `ctx.realRoot` (the whole repo):
// - a DIRECTORY symlink is descended ONLY if its resolved realpath is
// inside `ctx.scanDirRoot` — NOT merely inside `ctx.realRoot`. Without
// this, `src/up -> ..` (or `-> <realRoot>`) resolves inside the repo
// root and `walk` descends the ENTIRE repo, reporting violations under
// paths like `tests/not-src.cts` or `docs/other.cts` — files the caller's
// scan-dir list scopes it OUT of. This is a deliberate, fail-CLOSED
// trade-off: a directory symlink pointing elsewhere INSIDE the repo (but
// outside the scan directory) is simply not followed. The alternative —
// descending it — is exactly the whole-repo sweep this rule exists to
// prevent, and a fork PR could use that sweep to redden `lint:ci` on
// files this guard was never meant to read. The narrower rule is worth
// more than the missed edge case.
// - a FILE symlink is still scanned if its resolved realpath is inside
// `ctx.realRoot` (the whole repo, not just the scan directory) — this is
// what keeps `src/alias.cts -> vendor/real.cts` covered (test (f)): an
// aliased file genuinely is part of the compiled surface even when its
// real target lives outside `src/`, and it is still reported under its
// canonical (real) path.
//
// A resolved path is inside a root only if it IS that root or begins with
// root + separator — a plain `startsWith(root)` would also accept a sibling
// directory whose name merely starts with the root's name (`/repo-evil`).
function isInsideRoot(realPath, realRoot) {
return realPath === realRoot || realPath.startsWith(realRoot + path.sep); // allow-handrolled-containment: lint:ci guard; runs before build:lib, compiled security.cjs may not exist
}
// True when `realPath` (already confirmed inside `realRoot` by `isInsideRoot`)
// resolves THROUGH a skip-list directory anywhere along its path relative to
// the root — not just when `realPath` itself IS one. This is what closes the
// symlink bypass the `entry.name` fast path alone cannot: `walk` tests
// `entry.name` (the symlink's OWN name in its parent directory), but a
// symlink named something innocuous can still RESOLVE into `.git` /
// `node_modules` / `dist` (`src/g -> ../.git`, `src/leak.cts ->
// ../.git/config`, `src/nm -> ../node_modules`) — `isInsideRoot` alone admits
// all three, because every one of those real paths is still under the root.
function isUnderSkippedDir(realPath, realRoot) {
const rel = path.relative(realRoot, realPath);
return rel.split(path.sep).some((segment) => SKIP_DIR_NAMES.has(segment));
}
// `ctx.scanExt` is a `Set` of file extensions (e.g. `.cts`/`.ts`/`.mts`) the
// caller wants reported — threaded through `ctx` rather than as a positional
// parameter so recursive `walk(full, acc, ctx)` calls stay unchanged.
function walk(dir, acc, ctx) {
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return acc;
}
for (const entry of entries) {
const full = path.join(dir, entry.name);
if (SKIP_DIR_NAMES.has(entry.name)) continue; // cheap fast path
let stat;
try {
stat = entry.isSymbolicLink() ? fs.statSync(full) : entry;
} catch {
continue; // broken symlink target
}
let realPath;
try {
realPath = fs.realpathSync(full);
} catch {
continue; // broken symlink target (race, or a link stat() followed but realpath cannot)
}
if (stat.isDirectory()) {
// Directories (symlinked or real) are confined to the CURRENT scan
// directory root, not merely the repo root — see the comment above
// `isInsideRoot` for why (`src/up -> ..` whole-repo sweep).
if (!isInsideRoot(realPath, ctx.scanDirRoot)) continue;
if (isUnderSkippedDir(realPath, ctx.realRoot)) continue; // symlink resolves through a skipped dir
if (ctx.visitedRealDirs.has(realPath)) continue; // symlink cycle guard
ctx.visitedRealDirs.add(realPath);
walk(full, acc, ctx);
} else if (stat.isFile() && ctx.scanExt.has(path.extname(entry.name))) {
// Files are confined to the whole repo root — a symlinked FILE whose
// real target lives outside the scan directory but inside the repo
// (e.g. `src/alias.cts -> vendor/real.cts`) is still part of the
// compiled surface and must be scanned.
if (!isInsideRoot(realPath, ctx.realRoot)) continue;
if (isUnderSkippedDir(realPath, ctx.realRoot)) continue; // symlink resolves through a skipped dir
if (ctx.visitedRealFiles.has(realPath)) continue; // two symlinks, same real file
ctx.visitedRealFiles.add(realPath);
acc.push(realPath);
}
}
return acc;
}
/**
* Whole-repo tree-walk driver shared by every `lint-<derivation>-drift.cjs`
* guard. Resolves `root`, walks each of `scanDirs` filtered to `scanExt`
* (symlink-following, root-confined, cycle-guarded — see `walk` above), reads
* each discovered file, and calls `onFile(relPath, text)` for it — `relPath`
* is repo-relative and already the file's canonical (real) path, so a
* per-file exemption keyed on `relPath` matches consistently regardless of
* which symlink reached it.
*
* `onFile` returns an array of violation objects (or an empty array / null /
* undefined for "no violations in this file"); `scanTree` flattens them all
* into one returned array. Pure I/O orchestration — detection logic lives
* entirely in the caller's `onFile`.
*/
function scanTree({ root, scanDirs, scanExt, onFile }) {
const violations = [];
let realRoot;
try {
realRoot = fs.realpathSync(root);
} catch {
return violations; // root itself does not exist / is unreadable
}
for (const dir of scanDirs) {
const scanDirPath = path.join(root, dir);
let scanDirRoot;
try {
scanDirRoot = fs.realpathSync(scanDirPath);
} catch {
continue; // scan directory itself does not exist / is unreadable
}
const ctx = { realRoot, scanDirRoot, scanExt, visitedRealDirs: new Set(), visitedRealFiles: new Set() };
for (const file of walk(scanDirPath, [], ctx)) {
const rel = path.relative(realRoot, file);
let text;
try {
text = fs.readFileSync(file, 'utf8');
} catch {
continue;
}
const found = onFile(rel, text);
if (found && found.length > 0) violations.push(...found);
}
}
return violations;
}
// A reported fragment AND a reported file path are both attacker-controlled
// source text on a fork PR (a repo can legally track a filename containing
// control bytes, so the path is exactly as attacker-controlled as the
// fragment), and both are written straight to a CI log. Replace C0/C1
// control bytes (ANSI escapes included) with a visible \xNN, AND the
// non-Latin-1 formatting/bidi/line-separator codepoints below with \uNNNN, so
// a crafted literal or filename cannot rewrite the terminal rendering of the
// report or hide/reorder its own text:
// - U+200B-U+200F: zero-width space/joiners and directional marks
// - U+2028/U+2029: Unicode LINE SEPARATOR / PARAGRAPH SEPARATOR (line
// breaks a `\n`-only log scan would not catch)
// - U+202A-U+202E: bidi embedding/override controls (RLO etc.)
// - U+2066-U+2069: bidi isolate controls
function sanitizeForReport(text) {
return text
// eslint-disable-next-line no-control-regex -- the control range IS the target
.replace(/[\x00-\x1f\x7f-\x9f]/g, (c) => '\\x' + c.charCodeAt(0).toString(16).padStart(2, '0'))
.replace(/[\u200B-\u200F\u2028\u2029\u202A-\u202E\u2066-\u2069]/g, (c) => '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0'));
}
module.exports = {
SKIP_DIR_NAMES,
isInsideRoot,
isUnderSkippedDir,
walk,
readRegexLiteralAt,
MAX_REGEX_LITERAL_LEN,
sanitizeForReport,
scanTree,
resetRegexScanStats,
getRegexScanStats,
};