From 43e101f73724884611393c06ee1102c229ea82f3 Mon Sep 17 00:00:00 2001
From: "OpenGenesis (MPL 2.0)"
<153564363+opengenesislink@users.noreply.github.com>
Date: Sat, 7 Nov 2026 19:28:56 +0100
Subject: [PATCH] feat(yengine): add no-write .state inventory for controlled
legacy migration
---
.../workflows/ogl-yengine-binaryformatter.yml | 4 +
.../BINARYFORMATTER_RUNTIME_CLEANUP.md | 24 ++++
tools/ci/audit_yengine_states.py | 108 ++++++++++++++++++
tools/ci/test_yengine_state_audit.py | 57 +++++++++
4 files changed, 193 insertions(+)
create mode 100644 tools/ci/audit_yengine_states.py
create mode 100644 tools/ci/test_yengine_state_audit.py
diff --git a/.github/workflows/ogl-yengine-binaryformatter.yml b/.github/workflows/ogl-yengine-binaryformatter.yml
index 653a54c1..e129e1c0 100644
--- a/.github/workflows/ogl-yengine-binaryformatter.yml
+++ b/.github/workflows/ogl-yengine-binaryformatter.yml
@@ -7,6 +7,8 @@ on:
- 'OpenSim/Region/ScriptEngine/YEngine/**'
- 'tools/ci/YEngineBinaryFormatterRegression/**'
- 'tools/ci/verify_yengine_binaryformatter_safety.py'
+ - 'tools/ci/audit_yengine_states.py'
+ - 'tools/ci/test_yengine_state_audit.py'
- '.github/workflows/ogl-yengine-binaryformatter.yml'
workflow_dispatch:
@@ -30,5 +32,7 @@ jobs:
./runprebuild.sh
- name: Build full OpenGenesisLINK G1 .NET 10 solution
run: dotnet build OpenSim.sln -c Release
+ - name: Test read-only YEngine state file audit
+ run: python3 tools/ci/test_yengine_state_audit.py
- name: Exercise YEngine safe state roundtrips and legacy rejection
run: dotnet run --project tools/ci/YEngineBinaryFormatterRegression/YEngineBinaryFormatterRegression.csproj -c Release
diff --git a/doc/NexVerse/BINARYFORMATTER_RUNTIME_CLEANUP.md b/doc/NexVerse/BINARYFORMATTER_RUNTIME_CLEANUP.md
index 9875e846..10fa6cd2 100644
--- a/doc/NexVerse/BINARYFORMATTER_RUNTIME_CLEANUP.md
+++ b/doc/NexVerse/BINARYFORMATTER_RUNTIME_CLEANUP.md
@@ -38,3 +38,27 @@ conversion/restart policy is needed for such records.
This PR does **not** automatically rewrite or remove old script data, affect
the primary `main` branch or change the standalone Keyframe migration PR.
+
+## Read-only inventory of saved YEngine scripts before staging
+
+Run only against a copy of the YEngine `.state` directory:
+
+```bash
+python3 tools/ci/audit_yengine_states.py \
+ --directory /path/to/backed-up-script-states \
+ --report /tmp/ogl-yengine-state-audit.json
+```
+
+The report records file names relative to the supplied backup, SHA-256 of
+the original XML, snapshot SHA-256, size and parsing status. It does not
+contact the grid, database, object store or any remote URLs, and does not
+alter original files. XML is limited to 8 MiB and DTD/entity declarations
+are refused.
+
+**Important:** YEngine migration snapshots are opaque binary event/state
+streams. The audit cannot conclusively determine whether an individual
+snapshot contains a `BinaryFormatter` graph without interpreting the
+full format. It marks valid snapshots `inspect-required`, not
+`legacy-detected`. The only valid compatibility verdict comes from a
+controlled, backed-up staging restore; **do not assume all snapshots are
+upgrade-safe because the audit succeeded.**
diff --git a/tools/ci/audit_yengine_states.py b/tools/ci/audit_yengine_states.py
new file mode 100644
index 00000000..75aee10f
--- /dev/null
+++ b/tools/ci/audit_yengine_states.py
@@ -0,0 +1,108 @@
+#!/usr/bin/env python3
+"""Read-only inventory of YEngine .state snapshots; does NOT deserialize them.
+
+This tool deliberately does not guess whether a BinaryFormatter graph is
+present by scanning bytes for arbitrary tag values. Each opaque snapshot
+requires a staged restore or a format-aware offline migration review.
+"""
+import argparse
+import base64
+import binascii
+from collections import Counter
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import sys
+import xml.etree.ElementTree as ET
+
+MAX_XML = 8 * 1024 * 1024
+MAX_FILES = 100000
+PROHIBITED_XML = re.compile(rb" dict:
+ row = {"path": str(path.relative_to(root)), "status": "inspect-required"}
+ if path.is_symlink():
+ row["status"] = "symlink-skipped"
+ return row
+ try:
+ size = path.stat().st_size
+ row["file_bytes"] = size
+ if size > MAX_XML:
+ row["status"] = "oversize"
+ return row
+ raw = path.read_bytes()
+ row["file_sha256"] = hashlib.sha256(raw).hexdigest()
+ if PROHIBITED_XML.search(raw):
+ row["status"] = "blocked-dtd"
+ return row
+ document = ET.fromstring(raw)
+ if document.tag != "ScriptState":
+ row["status"] = "not-yengine-state"
+ return row
+ snapshot = document.find("Snapshot")
+ if snapshot is None or snapshot.text is None:
+ row["status"] = "missing-snapshot"
+ return row
+ encoded = "".join(snapshot.itertext())
+ encoded = re.sub(r"\s+", "", encoded)
+ if not encoded:
+ row["status"] = "missing-snapshot"
+ return row
+ binary = base64.b64decode(encoded, validate=True)
+ row["snapshot_bytes"] = len(binary)
+ row["snapshot_sha256"] = hashlib.sha256(binary).hexdigest()
+ row["format"] = "opaque-yengine-migration-stream"
+ row["requires_staging_restore"] = True
+ return row
+ except (ET.ParseError, UnicodeError):
+ row["status"] = "invalid-xml"
+ except (OSError, binascii.Error, ValueError):
+ row["status"] = "invalid-state-data"
+ return row
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--directory", required=True, help="root of a copy of YEngine state files")
+ parser.add_argument("--report", required=True, help="new JSON report path, must not exist")
+ args = parser.parse_args()
+ directory = Path(args.directory).resolve()
+ report = Path(args.report).absolute()
+ if not directory.is_dir() or report.exists() or report.suffix != ".json":
+ parser.error("input must be a directory and report must be a new .json file")
+ if report.is_symlink():
+ parser.error("report path must not be a symbolic link")
+
+ results = []
+ for parent, dirs, names in os.walk(directory, followlinks=False):
+ dirs[:] = [d for d in dirs if not (Path(parent) / d).is_symlink()]
+ for name in sorted(names):
+ if not name.endswith(".state"):
+ continue
+ if len(results) >= MAX_FILES:
+ raise SystemExit("too many .state files; aborting")
+ results.append(inspect(Path(parent) / name, directory))
+
+ results.sort(key=lambda x: x["path"])
+ stats = Counter(row["status"] for row in results)
+ summary = {
+ "total": len(results),
+ "counts": dict(sorted(stats.items())),
+ "warning": "Snapshot classification is NOT a legacy BinaryFormatter detector. "
+ "Never delete or rewrite originals. Inspect on an isolated staging restore.",
+ "files": results,
+ }
+ # FileMode.CreateNew equivalent. Never overwrite a report or any .state.
+ with report.open("x", encoding="utf-8") as output:
+ json.dump(summary, output, ensure_ascii=False, indent=2)
+ output.write("\n")
+ print("Read-only YEngine .state audit:", len(results), "files;", dict(stats))
+ print("Report:", report)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/ci/test_yengine_state_audit.py b/tools/ci/test_yengine_state_audit.py
new file mode 100644
index 00000000..b518ff6c
--- /dev/null
+++ b/tools/ci/test_yengine_state_audit.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python3
+"""CI exercises a bounded, no-write YEngine state audit on synthetic files."""
+import base64
+import hashlib
+import json
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+
+TOOL = Path(__file__).with_name("audit_yengine_states.py")
+
+
+def run(root, report, expected=0):
+ p = subprocess.run([sys.executable, str(TOOL), "--directory", str(root),
+ "--report", str(report)], text=True, capture_output=True, timeout=30)
+ assert p.returncode == expected, (p.stdout, p.stderr)
+
+
+with tempfile.TemporaryDirectory(prefix="ogl-yengine-audit-") as temp:
+ root = Path(temp) / "script-data"
+ root.mkdir()
+ data = b"opaque-script-stream\x00\x15\x16"
+ good = root / "good.state"
+ good.write_text("" +
+ base64.b64encode(data).decode("ascii") +
+ "")
+ malformed = root / "malformed.state"
+ malformed.write_text("unterminated")
+ dtd = root / "entity.state"
+ dtd.write_text("]>" +
+ "&ext;")
+ missing = root / "missing.state"
+ missing.write_text("")
+ large = root / "oversize.state"
+ large.write_bytes(b"X" * (8 * 1024 * 1024 + 1))
+ (root / "outside.state").symlink_to(good)
+ before = {p.name: hashlib.sha256(p.read_bytes()).hexdigest()
+ for p in [good, malformed, dtd, missing, large]}
+ report = Path(temp) / "audit.json"
+ run(root, report)
+ rows = json.loads(report.read_text())
+ assert rows["total"] == 6
+ got = {x["path"]: x for x in rows["files"]}
+ assert got["good.state"]["status"] == "inspect-required"
+ assert got["good.state"]["snapshot_sha256"] == hashlib.sha256(data).hexdigest()
+ assert got["malformed.state"]["status"] == "invalid-xml"
+ assert got["entity.state"]["status"] == "blocked-dtd"
+ assert got["missing.state"]["status"] == "missing-snapshot"
+ assert got["oversize.state"]["status"] == "oversize"
+ assert got["outside.state"]["status"] == "symlink-skipped"
+ run(root, report, expected=2) # report collision is rejected
+ for p in [good, malformed, dtd, missing, large]:
+ assert before[p.name] == hashlib.sha256(p.read_bytes()).hexdigest()
+ assert report.exists()
+print("PASS: YEngine audit validates bounds, DTD rejection, hashes, no overwrites "
+ "or changes to original snapshots")