chore(audit): single Python implementation, no rg/python divergence

CI runs had no rg on the runner, so the bash script fell back to its python
branch with a different file set (no extension skips; sees gitignored tracked
files) and a different verdict than local rg runs. One deterministic scanner
now serves both: git ls-files walk, NUL sniff + extension skip for binary
blobs (model .cmo3/.can3/.moc3/.jit files decode to CJK-looking garbage),
allowlist for the opentype.js LCID table line, exception zones unchanged.
This commit is contained in:
lapy 2026-10-12 17:24:17 +01:00
parent 830c778b03
commit 7898b88b3e
3 changed files with 213 additions and 328 deletions

View file

@ -0,0 +1,194 @@
#!/usr/bin/env python3
"""Westernization audit: single implementation used locally and in CI.
Deterministic scan over `git ls-files -co --exclude-standard` (plus a filesystem
sweep fallback outside a git checkout), so tracked files hidden from ripgrep by
gitignore rules (e.g. `*.json` ignores) are still inspected. Binary files (NUL
byte) and known media/font extensions are skipped: their bytes occasionally
decode as stray CJK codepoints and produce false positives.
Exception zones (agreed policy, see westernization.md):
- append-only Liquibase history under main/manager-api/src/main/resources/db/changelog
- vendored device data under main/manager-web/public/generator/static
- one allowlisted third-party artefact: the opentype.js LCID -> BCP47
font-name table line inside the generator bundle
"""
from __future__ import annotations
import re
import subprocess
import sys
from pathlib import Path
ROOT = Path(".")
LOCALE_PATTERN = "zh-" + "CN|" + "zh-" + "TW"
CONTENT_PATTERN = re.compile(r"[\u4e00-\u9fff\u3400-\u4dbf]|" + LOCALE_PATTERN)
PATH_PATTERN = re.compile(r"[\u4e00-\u9fff\u3400-\u4dbf]")
# Third-party LCID -> BCP47 mapping table shipped inside the generator bundle
# (opentype.js font name tables); machine locale ids, not user-facing text.
ALLOWLINE_PATTERN = re.compile(r'\d+:"' + "zh-" + r"(?:CN|TW)\"")
CHANGELOG_EXCEPTION = "main/manager-api/src/main/resources/db/changelog"
GENERATOR_ROOT = "main/manager-web/public/generator"
GENERATOR_DATA_EXCEPTION = GENERATOR_ROOT + "/static"
LIVE_EXCEPTIONS = (CHANGELOG_EXCEPTION, GENERATOR_DATA_EXCEPTION)
SKIP_DIR_PARTS = {
".git", "node_modules", ".venv", ".venv-xiaozhi", "venv",
"dist", "target", "build", "unpackage", "__pycache__", ".pytest_cache",
}
SKIP_EXTS = {
".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico", ".svg",
".bin", ".onnx", ".so", ".dll", ".dylib", ".a", ".o",
".ttf", ".otf", ".woff", ".woff2", ".eot",
".mp3", ".wav", ".opus", ".ogg", ".m4a", ".mp4", ".webm",
".pdf", ".zip", ".gz", ".xz", ".7z", ".jar", ".war",
".pyc", ".pyo", ".class", ".key", ".crt", ".pem", ".p12",
# Cubism / model blobs (may lack NUL in compressed payloads)
".can3", ".cmo3", ".cmfx", ".moc3", ".moc",
}
def section(title: str) -> None:
print(f"\n== {title} ==")
def is_under(path_text: str, prefixes: tuple[str, ...]) -> bool:
return any(
path_text == prefix or path_text.startswith(prefix + "/")
for prefix in prefixes
)
def candidate_files() -> list[Path]:
try:
listing = subprocess.check_output(
["git", "ls-files", "-co", "--exclude-standard"],
text=True, stderr=subprocess.DEVNULL,
)
return [ROOT / line for line in listing.splitlines() if line]
except Exception:
files: list[Path] = []
for path in ROOT.rglob("*"):
if not path.is_file():
continue
parts = set(path.parts)
if parts & SKIP_DIR_PARTS:
continue
files.append(path)
return files
def is_text(path: Path) -> bool:
if path.suffix.lower() in SKIP_EXTS:
return False
try:
with path.open("rb") as fh:
return b"\x00" not in fh.read(65536)
except OSError:
return False
def read_text(path: Path) -> str | None:
try:
return path.read_bytes().decode("utf-8")
except (OSError, UnicodeDecodeError):
return None
def scan(files: list[Path], predicate, allowlist: bool = False):
matches = []
for path in files:
if not path.is_file():
continue
try:
path_text = path.relative_to(ROOT).as_posix()
except ValueError:
path_text = str(path)
if set(Path(path_text).parts) & SKIP_DIR_PARTS or not predicate(path_text):
continue
if not is_text(path):
continue
text = read_text(path)
if text is None:
continue
for line_no, line in enumerate(text.splitlines(), 1):
if CONTENT_PATTERN.search(line):
if allowlist and ALLOWLINE_PATTERN.search(line):
continue
matches.append((path_text, line_no, line[:240]))
return matches
def report_exception(title: str, files: list[Path], prefix: str) -> None:
section(title)
matches = scan(files, lambda p: is_under(p, (prefix,)))
if matches:
print(f"{len(matches)} match(es). Showing up to 40:")
for path_text, line_no, line in matches[:40]:
print(f"{path_text}:{line_no}:{line}")
if len(matches) > 40:
print("... truncated ...")
print(f"\n{title} detected above (exempt zone).")
else:
print("No matches.")
def main() -> int:
files = candidate_files()
section("Live Source And Docs Audit")
live_matches = scan(
files,
lambda p: not is_under(p, LIVE_EXCEPTIONS),
allowlist=True,
)
if live_matches:
for path_text, line_no, line in live_matches:
print(f"{path_text}:{line_no}:{line}")
print("\nLive source/doc audit: FAIL")
live_status = 1
else:
print("Live source/doc audit: PASS")
live_status = 0
report_exception(
"Historical Changelog Exceptions", files, CHANGELOG_EXCEPTION
)
report_exception(
"Vendored Device Data Exceptions", files, GENERATOR_DATA_EXCEPTION
)
section("Path Audit")
path_matches = []
for path in files:
try:
path_text = path.relative_to(ROOT).as_posix()
except ValueError:
path_text = str(path)
if PATH_PATTERN.search(path_text):
path_matches.append(path_text)
if path_matches:
print("\n".join(sorted(set(path_matches))))
print("\nPath audit: FAIL")
path_status = 1
else:
print("Path audit: PASS")
path_status = 0
section("Summary")
if live_status == 0 and path_status == 0:
print("Westernization baseline is clean outside intentional exceptions.")
print("Intentional exceptions:")
print(f"- append-only Liquibase history under {CHANGELOG_EXCEPTION}")
print(f"- vendored device data under {GENERATOR_DATA_EXCEPTION}")
print("- binary files and media/font blobs (NUL sniff + extension list)")
print("- opentype.js LCID font-name table inside the generator bundle")
return 0
print("Westernization baseline still has non-exempt findings.")
return 1
if __name__ == "__main__":
sys.exit(main())

View file

@ -1,337 +1,18 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Thin wrapper around the Python implementation so CI (and muscle memory) can
# keep calling this script. All scan logic and the exception policy live in
# westernization_audit.py; keeping a single implementation guarantees CI and
# local runs agree.
set -euo pipefail set -euo pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT_DIR" cd "$ROOT_DIR"
# Exception policy (agreed 2026-10-12): if ! command -v python3 >/dev/null 2>&1; then
# - Append-only Liquibase history under echo "python3 is required for this audit." >&2
# main/manager-api/src/main/resources/db/changelog keeps its historical exit 1
# Chinese seed/updates (a fresh install is migrated + cleaned to English by
# the append-only 202610111200.sql changeset).
# - main/manager-web/public/generator/static is functional device data
# (charset codepoint tables, CJK glyph tables, emoji gifs, wakeword model
# blobs) consumed byte-for-byte by the firmware toolchain: exempt.
# - The generator CODE bundle (generator/assets/**, generator/index.html) is
# rebuilt from the translated generator source and is NOT exempt; it is
# scanned like live source. One allowlisted artefact is tolerated: the
# opentype.js LCID -> BCP47 table (e.g. 1028 -> zh TW locale id), a font
# parsing table, not user-facing text.
if ! command -v rg >/dev/null 2>&1; then
if ! command -v python3 >/dev/null 2>&1; then
echo "ripgrep (rg) or python3 is required for this audit." >&2
exit 1
fi
python3 - <<'PY'
from pathlib import Path
import re
import subprocess
import sys
root = Path(".")
locale_pattern = "zh-" + "CN|" + "zh-" + "TW"
content_pattern = re.compile(r"[\u4e00-\u9fff]|" + locale_pattern)
path_pattern = re.compile(r"[\u4e00-\u9fff]")
# Third-party LCID -> BCP47 mapping in vendored opentype.js (font name tables).
allowline_pattern = re.compile(r"\d+:\"zh-(?:CN|TW)\"")
content_skip_dirs = {
".git",
"node_modules",
"dist",
"target",
"build",
}
content_skip_exts = {
".png", ".jpg", ".jpeg", ".gif", ".webp", ".bin", ".onnx", ".so",
".ttf", ".woff", ".woff2", ".mp3", ".wav", ".opus", ".pdf",
".ico", ".svg",
}
changelog_exception = "main/manager-api/src/main/resources/db/changelog"
generator_root = "main/manager-web/public/generator"
generator_data_exception = generator_root + "/static"
live_exceptions = (changelog_exception, generator_data_exception)
path_skip_prefixes = (
".git",
"node_modules",
"main/manager-web/node_modules",
"main/manager-web/dist",
"main/manager-api/target",
)
def section(title):
print(f"\n== {title} ==")
def rel(path):
return path.relative_to(root).as_posix()
def is_under(path_text, prefixes):
return any(path_text == prefix or path_text.startswith(prefix + "/") for prefix in prefixes)
def should_skip_content(path):
parts = set(path.parts)
if parts & content_skip_dirs:
return True
return path.suffix.lower() in content_skip_exts
def candidate_files():
try:
output = subprocess.check_output(
["git", "ls-files", "-co", "--exclude-standard"],
text=True,
)
return [root / line for line in output.splitlines() if line]
except Exception:
return [path for path in root.rglob("*") if path.is_file()]
def scan_paths(predicate, allowlist=False):
matches = []
for path in candidate_files():
if not path.is_file():
continue
path_text = rel(path)
if should_skip_content(Path(path_text)) or not predicate(path_text):
continue
try:
text = path.read_text(errors="ignore")
except OSError:
continue
for line_no, line in enumerate(text.splitlines(), 1):
if content_pattern.search(line):
if allowlist and allowline_pattern.search(line):
continue
matches.append((path_text, line_no, line[:240]))
return matches
section("Live Source And Docs Audit")
live_matches = scan_paths(lambda path_text: not is_under(path_text, live_exceptions), allowlist=True)
if live_matches:
for path_text, line_no, line in live_matches:
print(f"{path_text}:{line_no}:{line}")
print("\nLive source/doc audit: FAIL")
live_status = 1
else:
print("Live source/doc audit: PASS")
live_status = 0
section("Historical Changelog Exceptions")
changelog_matches = scan_paths(lambda path_text: is_under(path_text, (changelog_exception,)))
if changelog_matches:
print(f"{len(changelog_matches)} match(es). Showing up to 40:")
for path_text, line_no, line in changelog_matches[:40]:
print(f"{path_text}:{line_no}:{line}")
if len(changelog_matches) > 40:
print("... truncated ...")
print("\nHistorical changelog exceptions detected above.")
else:
print("No historical changelog hits.")
section("Vendored Device Data Exceptions")
data_matches = scan_paths(lambda path_text: is_under(path_text, (generator_data_exception,)))
if data_matches:
print(f"{len(data_matches)} match(es). Showing up to 40:")
for path_text, line_no, line in data_matches[:40]:
print(f"{path_text}:{line_no}:{line}")
if len(data_matches) > 40:
print("... truncated ...")
print("\nVendored device data exceptions detected above (byte-exact data, not prose).")
else:
print("No vendored device data hits.")
section("Path Audit")
path_matches = []
for path in candidate_files():
if not path.is_file():
continue
path_text = rel(path)
if is_under(path_text, path_skip_prefixes):
continue
if path_pattern.search(path_text):
path_matches.append(path_text)
if path_matches:
print("\n".join(path_matches))
print("\nPath audit: FAIL")
path_status = 1
else:
print("Path audit: PASS")
path_status = 0
section("Summary")
if live_status == 0 and path_status == 0:
print("Westernization baseline is clean outside intentional exceptions.")
print("Intentional exceptions:")
print("- append-only Liquibase history under " + changelog_exception)
print("- vendored device data under " + generator_data_exception)
print("- opentype.js LCID table (1028:\"zh-" "TW\") inside the generator bundle")
sys.exit(0)
print("Westernization baseline still has non-exempt findings.")
sys.exit(1)
PY
exit $?
fi fi
CONTENT_IGNORE=( exec python3 scripts/westernization_audit.py
"!**/.git/**"
"!**/node_modules/**"
"!**/.venv*/**"
"!**/dist/**"
"!**/target/**"
"!**/build/**"
"!**/*.png"
"!**/*.jpg"
"!**/*.jpeg"
"!**/*.gif"
"!**/*.webp"
"!**/*.bin"
"!**/*.onnx"
"!**/*.so"
"!**/*.ttf"
"!**/*.woff"
"!**/*.woff2"
"!**/*.mp3"
"!**/*.wav"
"!**/*.opus"
"!**/*.pdf"
)
MAIN_IGNORE=(
"${CONTENT_IGNORE[@]}"
"!main/manager-api/src/main/resources/db/changelog/**"
"!main/manager-web/public/generator/static/**"
)
CONTENT_PATTERN='[\p{Han}]|zh-C''N|zh-T''W'
# Third-party LCID -> BCP47 mapping inside the vendored opentype.js font
# parser (e.g. LCID 1028 mapped to a zh TW locale id); font metadata, not text.
ALLOWLINE_PATTERN='[0-9]+:"zh-(CN|TW)"'
PATH_IGNORE=(
"./.git"
"./node_modules"
"./main/manager-web/node_modules"
"./main/manager-web/dist"
"./main/manager-api/target"
)
section() {
printf '\n== %s ==\n' "$1"
}
collect_audit_roots() {
AUDIT_SEARCH_ROOTS=()
local candidate
for candidate in main docs scripts; do
if [[ -e "$candidate" ]]; then
AUDIT_SEARCH_ROOTS+=("$candidate")
fi
done
shopt -s nullglob
for candidate in *.md; do
AUDIT_SEARCH_ROOTS+=("$candidate")
done
shopt -u nullglob
if [[ ${#AUDIT_SEARCH_ROOTS[@]} -eq 0 ]]; then
echo "No audit search roots found." >&2
exit 1
fi
}
run_rg() {
local pattern="$1"
shift
local -a rg_globs=()
local glob
for glob in "$@"; do
rg_globs+=(-g "$glob")
done
# Ripgrep matches nothing when every -g is negated and the search root is ".".
# Scan explicit roots so negated globs filter within them instead of excluding all files.
rg -n --no-messages "$pattern" "${AUDIT_SEARCH_ROOTS[@]}" "${rg_globs[@]}"
}
show_limited_matches() {
local title="$1"
local pattern="$2"
shift 2
local matches
matches="$(rg -n "$pattern" "$@" || true)"
if [[ -z "$matches" ]]; then
echo "No matches."
return 1
fi
local count
count="$(printf '%s\n' "$matches" | wc -l | tr -d ' ')"
echo "$count match(es). Showing up to 40:"
printf '%s\n' "$matches" | sed -n '1,40p' | cut -c1-240
if [[ "$count" -gt 40 ]]; then
echo "... truncated ..."
fi
return 0
}
section "Live Source And Docs Audit"
collect_audit_roots
if matches="$(run_rg "$CONTENT_PATTERN" "${MAIN_IGNORE[@]}" | rg -v "$ALLOWLINE_PATTERN" || true)" && [[ -n "$matches" ]]; then
printf '%s\n' "$matches"
echo
echo "Live source/doc audit: FAIL"
live_status=1
else
echo "Live source/doc audit: PASS"
live_status=0
fi
section "Historical Changelog Exceptions"
if show_limited_matches \
"Historical changelog exceptions" \
"$CONTENT_PATTERN" \
main/manager-api/src/main/resources/db/changelog; then
echo
echo "Historical changelog exceptions detected above."
else
echo "No historical changelog hits."
fi
section "Vendored Device Data Exceptions"
if show_limited_matches \
"Vendored device data exceptions" \
"$CONTENT_PATTERN" \
main/manager-web/public/generator/static \
-g '!**/*.png' -g '!**/*.jpg' -g '!**/*.jpeg'; then
echo
echo "Vendored device data exceptions detected above (byte-exact data, not prose)."
else
echo "No vendored device data hits."
fi
section "Path Audit"
path_output="$(
find . \
$(printf " -path '%s' -prune -o" "${PATH_IGNORE[@]}") \
-type f -print | rg '[\p{Han}]' || true
)"
if [[ -n "$path_output" ]]; then
printf '%s\n' "$path_output"
echo
echo "Path audit: FAIL"
path_status=1
else
echo "Path audit: PASS"
path_status=0
fi
section "Summary"
if [[ "$live_status" -eq 0 && "$path_status" -eq 0 ]]; then
echo "Westernization baseline is clean outside intentional exceptions."
echo "Intentional exceptions:"
echo "- append-only Liquibase history under main/manager-api/src/main/resources/db/changelog"
echo "- vendored device data under main/manager-web/public/generator/static"
echo "- opentype.js LCID font-name table inside the generator bundle"
exit 0
fi
echo "Westernization baseline still has non-exempt findings."
exit 1

View file

@ -179,11 +179,21 @@ Use the audit script after meaningful rebase batches:
./scripts/westernization_audit.sh ./scripts/westernization_audit.sh
``` ```
The audit is a single Python implementation
(`scripts/westernization_audit.py`, wrapped by
`scripts/westernization_audit.sh`) so local and CI runs cannot diverge.
It scans `git ls-files -co --exclude-standard`, i.e. tracked files are
inspected even when a broad gitignore rule (e.g. `*.json`) hides them from
ripgrep; files with a NUL byte or media/font/model extensions are skipped as
binary blobs.
What it enforces: What it enforces:
- live source/docs must be clean of Han-script and Chinese locale tags - live source/docs must be clean of Han-script and Chinese locale tags
- this includes the vendored generator code bundle - this includes the vendored generator code bundle
(`main/manager-web/public/generator/assets/**` and `index.html`) (`main/manager-web/public/generator/assets/**` and `index.html`)
- this includes vendored model metadata (`.cdi3.json`, `.physics3.json`) which
ships editable display names
- path names must be clean of Han-script - path names must be clean of Han-script
Intentional exception zones: Intentional exception zones: