diff --git a/CHANGELOG.md b/CHANGELOG.md
index b44a7fa2f..963594cad 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -61,6 +61,17 @@
- Scoring-request wire schema `1.1` now requires an exact provider-neutral `task_revision_fingerprint` in addition to the logical task identifier. The fingerprint participates in request identity, is propagated by the essay adapter from the complete prompt fingerprint, and prevents changed task content from being silently pooled under one request or calibration item.
- Criterion-level many-facet handoffs now use exact task revisions as the Rust estimator item axis while retaining aligned logical task and task-family labels for audit. Duplicate cells, support, resource bounds, respondent–item connectedness, item–rater connectedness, and response provenance are all revision-indexed; one revision cannot be rebound to a different logical task or family.
- Added an explicit, fail-closed schema-`1.0` request migration that verifies canonical content, fingerprint, public handle, and the authoritative engine-policy projection; requires a caller-supplied task revision; preserves normalized caller metadata; and intentionally does not migrate legacy observations or results. Content identity prevents accidental pooling but does not establish cross-revision comparability, which still requires anchors, invariance/DIF, drift, and recovery evidence.
+
+### Security
+
+#### Descriptor-safe bounded JSON input for automation scripts
+
+- Consolidated governed automation JSON readers behind a descriptor-safe shared
+ loader with a 32 MiB inclusive byte bound and a non-recursive 128-level depth
+ bound.
+- Rejected symbolic links, FIFOs, directories, path replacement, invalid UTF-8,
+ malformed JSON, non-object roots, oversized input, and excessive nesting with
+ deterministic tests.
## [0.7.0] - 2026-08-04
diff --git a/docs/bounded_json_input_security.md b/docs/bounded_json_input_security.md
new file mode 100644
index 000000000..d001914bb
--- /dev/null
+++ b/docs/bounded_json_input_security.md
@@ -0,0 +1,40 @@
+# Descriptor-safe bounded JSON input
+
+Repository automation treats JSON artifacts as untrusted local or CI inputs. All
+governed readers delegate to `scripts._bounded_json.read_json_object`.
+
+The loader:
+
+1. opens the leaf with `O_CLOEXEC`, `O_NONBLOCK`, and `O_NOFOLLOW` when those
+ platform flags are available;
+2. validates the opened descriptor with `fstat` as a regular file;
+3. compares the descriptor identity with `lstat` before and after the read;
+4. reads at most 32 MiB plus one byte through that same descriptor;
+5. scans structural nesting non-recursively with an inclusive depth limit of 128,
+ ignoring delimiters inside strings and escaped characters;
+6. decodes strict UTF-8, delegates syntax and value construction to `json.loads`,
+ and requires an object root.
+
+Callers that distinguish syntactically invalid JSON from non-object roots must
+preserve those failure classes when translating loader errors into domain checks.
+
+These controls bound availability risk and reject symbolic-link leaves, FIFOs,
+directories, oversized inputs, excessive nesting, and detectable path
+replacement. They do not make arbitrary JSON semantically trustworthy, replace
+operating-system permission boundaries, or authorize processing from a hostile
+writable parent directory.
+
+## References
+
+MITRE. (2026, April 30). *CWE-400: Uncontrolled resource consumption* (CWE
+Version 4.20). https://cwe.mitre.org/data/definitions/400.html
+
+MITRE. (2026, April 30). *CWE-674: Uncontrolled recursion* (CWE Version 4.20).
+https://cwe.mitre.org/data/definitions/674.html
+
+Python Software Foundation. (2026). *json—JSON encoder and decoder* (Python
+3.12.13 documentation). https://docs.python.org/3.12/library/json.html
+
+Python Software Foundation. (2026). *os—Miscellaneous operating system
+interfaces* (Python 3.12.13 documentation).
+https://docs.python.org/3.12/library/os.html
diff --git a/docs/changelog.d/bounded-json-input-hardening.md b/docs/changelog.d/bounded-json-input-hardening.md
new file mode 100644
index 000000000..771ce77a6
--- /dev/null
+++ b/docs/changelog.d/bounded-json-input-hardening.md
@@ -0,0 +1,10 @@
+# Descriptor-safe bounded JSON input for automation scripts
+
+## Security
+
+- Consolidated governed automation JSON readers behind a descriptor-safe shared
+ loader with a 32 MiB inclusive byte bound and a non-recursive 128-level depth
+ bound.
+- Rejected symbolic links, FIFOs, directories, path replacement, invalid UTF-8,
+ malformed JSON, non-object roots, oversized input, and excessive nesting with
+ deterministic tests.
diff --git a/scripts/_bounded_json.py b/scripts/_bounded_json.py
new file mode 100644
index 000000000..d840e2bbf
--- /dev/null
+++ b/scripts/_bounded_json.py
@@ -0,0 +1,160 @@
+"""Descriptor-safe bounded JSON input for repository automation.
+
+The module opens the requested leaf without following symbolic links where the
+platform supports that flag, validates the opened descriptor as a stable regular
+file, performs one bounded read, validates structural depth without recursion,
+then delegates syntax and value construction to :mod:`json`.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import stat
+from pathlib import Path
+from typing import Any, Final
+
+MAX_JSON_BYTES: Final = 32 * 1024 * 1024
+MAX_JSON_DEPTH: Final = 128
+_READ_CHUNK_BYTES: Final = 64 * 1024
+_SAFE_OPEN_ERROR = "JSON input could not be opened as a stable regular file"
+_UNSTABLE_PATH_ERROR = "JSON input path changed during the bounded read"
+
+
+def _positive_limit(value: object, field_name: str) -> int:
+ """Return ``value`` as a positive, non-Boolean integer."""
+ if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
+ raise ValueError(f"{field_name} must be a positive integer")
+ return value
+
+
+def _open_flags() -> int:
+ """Return portable descriptor flags for non-following, nonblocking reads."""
+ return (
+ os.O_RDONLY
+ | getattr(os, "O_CLOEXEC", 0)
+ | getattr(os, "O_NONBLOCK", 0)
+ | getattr(os, "O_NOFOLLOW", 0)
+ )
+
+
+def _descriptor_identity(file_status: os.stat_result) -> tuple[int, int]:
+ """Return the device and inode identity for one stat result."""
+ return file_status.st_dev, file_status.st_ino
+
+
+def _validate_path_identity(path: Path, descriptor_status: os.stat_result) -> None:
+ """Require ``path`` to still name the regular file held by the descriptor."""
+ try:
+ path_status = os.lstat(path)
+ except OSError:
+ raise ValueError(_UNSTABLE_PATH_ERROR) from None
+ if not stat.S_ISREG(path_status.st_mode):
+ raise ValueError(_SAFE_OPEN_ERROR)
+ if _descriptor_identity(path_status) != _descriptor_identity(descriptor_status):
+ raise ValueError(_UNSTABLE_PATH_ERROR)
+
+
+def _read_bounded_descriptor(file_descriptor: int, *, byte_limit: int) -> bytes:
+ """Read at most ``byte_limit + 1`` bytes from an opened descriptor."""
+ remaining = byte_limit + 1
+ chunks: list[bytes] = []
+ while remaining:
+ chunk = os.read(file_descriptor, min(_READ_CHUNK_BYTES, remaining))
+ if not chunk:
+ break
+ chunks.append(chunk)
+ remaining -= len(chunk)
+ content = b"".join(chunks)
+ if len(content) > byte_limit:
+ raise ValueError(f"JSON input exceeds maximum allowed size {byte_limit} bytes")
+ return content
+
+
+def _read_stable_regular_file(path: Path, *, byte_limit: int) -> bytes:
+ """Open, identify, and bounded-read one stable regular file."""
+ try:
+ file_descriptor = os.open(path, _open_flags())
+ except OSError:
+ raise ValueError(_SAFE_OPEN_ERROR) from None
+ try:
+ descriptor_status = os.fstat(file_descriptor)
+ if not stat.S_ISREG(descriptor_status.st_mode):
+ raise ValueError(_SAFE_OPEN_ERROR)
+ _validate_path_identity(path, descriptor_status)
+ content = _read_bounded_descriptor(file_descriptor, byte_limit=byte_limit)
+ _validate_path_identity(path, descriptor_status)
+ return content
+ finally:
+ os.close(file_descriptor)
+
+
+def _validate_json_depth(content: bytes, *, max_depth: int) -> None:
+ """Reject object or array nesting deeper than ``max_depth``."""
+ depth = 0
+ in_string = False
+ escaped = False
+ for byte in content:
+ if in_string:
+ if escaped:
+ escaped = False
+ elif byte == 0x5C:
+ escaped = True
+ elif byte == 0x22:
+ in_string = False
+ continue
+ if byte == 0x22:
+ in_string = True
+ elif byte in (0x5B, 0x7B):
+ depth += 1
+ if depth > max_depth:
+ raise ValueError(
+ f"JSON input exceeds maximum allowed depth {max_depth}"
+ )
+ elif byte in (0x5D, 0x7D) and depth:
+ depth -= 1
+
+
+def read_json_object(
+ path: Path,
+ *,
+ max_bytes: int = MAX_JSON_BYTES,
+ max_depth: int = MAX_JSON_DEPTH,
+) -> dict[str, Any]:
+ """Read a stable, bounded UTF-8 JSON object from ``path``.
+
+ Args:
+ path: Leaf file to open without following a symbolic link where
+ supported by the operating system.
+ max_bytes: Inclusive maximum number of bytes accepted.
+ max_depth: Inclusive maximum object/array nesting depth.
+
+ Returns:
+ The decoded JSON object.
+
+ Raises:
+ ValueError: If limits are invalid, the input is not a stable regular
+ file, the byte/depth limit is exceeded, or decoder recursion fails.
+ ValueError: Also raised when the input is not valid UTF-8 or JSON.
+ RuntimeError: If the decoded root is not an object.
+ """
+ byte_limit = _positive_limit(max_bytes, "max_bytes")
+ depth_limit = _positive_limit(max_depth, "max_depth")
+ content = _read_stable_regular_file(path, byte_limit=byte_limit)
+ _validate_json_depth(content, max_depth=depth_limit)
+ try:
+ text = content.decode("utf-8")
+ except UnicodeDecodeError:
+ raise ValueError("JSON input is not valid UTF-8") from None
+ try:
+ payload = json.loads(text)
+ except json.JSONDecodeError:
+ raise ValueError("JSON input is not valid JSON") from None
+ except RecursionError as exc:
+ raise ValueError("JSON input exceeds decoder recursion capacity") from exc
+ if not isinstance(payload, dict):
+ raise RuntimeError("JSON artifact must be an object")
+ return payload
+
+
+__all__ = ["MAX_JSON_BYTES", "MAX_JSON_DEPTH", "read_json_object"]
diff --git a/scripts/build_benchmark_report.py b/scripts/build_benchmark_report.py
index 00889572e..491b5bfe0 100644
--- a/scripts/build_benchmark_report.py
+++ b/scripts/build_benchmark_report.py
@@ -12,13 +12,15 @@
from pathlib import Path
from typing import Any
+try:
+ from scripts._bounded_json import read_json_object
+except ModuleNotFoundError:
+ from _bounded_json import read_json_object
+
def _read_json(path: Path) -> dict[str, Any]:
- with path.open(encoding="utf-8") as fh:
- payload = json.load(fh)
- if not isinstance(payload, dict):
- raise RuntimeError(f"JSON artifact must be an object: {path}")
- return payload
+ """Read one descriptor-safe bounded JSON object from disk."""
+ return read_json_object(path)
def _sha256(path: Path) -> str:
@@ -89,7 +91,9 @@ def _required_backends(benchmark: dict[str, Any]) -> list[str]:
return sorted(backends)
-def _artifact_coverage(benchmark: dict[str, Any], steps: list[dict[str, Any]]) -> dict[str, Any]:
+def _artifact_coverage(
+ benchmark: dict[str, Any], steps: list[dict[str, Any]]
+) -> dict[str, Any]:
required = benchmark.get("required_artifacts", [])
if not isinstance(required, list):
required = []
@@ -125,14 +129,16 @@ def _command_durations(steps: list[dict[str, Any]]) -> list[dict[str, Any]]:
return rows
-def _render_rows(rows: list[dict[str, Any]], columns: list[tuple[str, str]]) -> list[str]:
+def _render_rows(
+ rows: list[dict[str, Any]], columns: list[tuple[str, str]]
+) -> list[str]:
rendered = []
for row in rows:
cells = []
for key, label in columns:
value = escape(_format_value(row.get(key)))
if not cells:
- cells.append(f"
{value} | ")
+ cells.append(f'{value} | ')
else:
cells.append(f"{value} | ")
rendered.append("" + "".join(cells) + "
")
@@ -152,7 +158,7 @@ def _render_report_html(report: dict[str, Any]) -> str:
)
artifact_rows = [
""
- f"| {escape(name)} | "
+ f'{escape(name)} | '
f"{'go' if name in set(report.get('artifact_coverage', {}).get('present', [])) else 'missing'} | "
"
"
for name in report.get("artifact_coverage", {}).get("required", [])
@@ -163,7 +169,12 @@ def _render_report_html(report: dict[str, Any]) -> str:
("Runtime Budget", f"{report.get('runtime_budget_seconds', '')}s"),
("Total Runtime", f"{report.get('total_duration_seconds', '')}s"),
("Budget Result", report.get("budget_ok")),
- ("Observed Backends", ", ".join(scenario.get("observed_backends", [])) if isinstance(scenario, dict) else ""),
+ (
+ "Observed Backends",
+ ", ".join(scenario.get("observed_backends", []))
+ if isinstance(scenario, dict)
+ else "",
+ ),
("Source Commit", report.get("source_commit", "")),
]
card_markup = [
@@ -212,7 +223,7 @@ def _render_report_html(report: dict[str, Any]) -> str:
'',
"
",
"Command duration table",
- "| Step | Command | Backend | Seconds | Output |
",
+ '| Step | Command | Backend | Seconds | Output |
',
"",
*command_rows,
"",
@@ -224,7 +235,7 @@ def _render_report_html(report: dict[str, Any]) -> str:
'',
"
",
"Required artifact coverage table",
- "| Artifact | Status |
",
+ '| Artifact | Status |
',
"",
*artifact_rows,
"",
@@ -413,7 +424,9 @@ def build_report(args: argparse.Namespace) -> dict[str, Any]:
)
required_backends = _required_backends(benchmark)
observed_backends = _observed_backends(steps)
- missing_backends = [backend for backend in required_backends if backend not in observed_backends]
+ missing_backends = [
+ backend for backend in required_backends if backend not in observed_backends
+ ]
artifact_coverage = _artifact_coverage(benchmark, steps)
status_ok = (
acceptance.get("status") == "ok"
@@ -445,20 +458,32 @@ def build_report(args: argparse.Namespace) -> dict[str, Any]:
}
html_path.write_text(_render_report_html(report), encoding="utf-8")
report["html_report_sha256"] = _sha256(html_path)
- report_path.write_text(json.dumps(report, indent=2, sort_keys=True), encoding="utf-8")
+ report_path.write_text(
+ json.dumps(report, indent=2, sort_keys=True), encoding="utf-8"
+ )
return report
def build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(description="Build fast-mlsirm benchmark evidence from release acceptance output.")
- parser.add_argument("--repo-root", default=".", help="Repository root used to record source commit.")
- parser.add_argument("--acceptance", required=True, help="Path to release acceptance_summary.json.")
+ parser = argparse.ArgumentParser(
+ description="Build fast-mlsirm benchmark evidence from release acceptance output."
+ )
+ parser.add_argument(
+ "--repo-root", default=".", help="Repository root used to record source commit."
+ )
+ parser.add_argument(
+ "--acceptance", required=True, help="Path to release acceptance_summary.json."
+ )
parser.add_argument(
"--benchmark-manifest",
default="examples/enterprise_demo/benchmark_manifest.json",
help="Path to benchmark_manifest.json.",
)
- parser.add_argument("--out", default="benchmark-evidence", help="Output directory for benchmark report files.")
+ parser.add_argument(
+ "--out",
+ default="benchmark-evidence",
+ help="Output directory for benchmark report files.",
+ )
return parser
diff --git a/scripts/build_buyer_packet.py b/scripts/build_buyer_packet.py
index e14a24a44..75dc3bea1 100644
--- a/scripts/build_buyer_packet.py
+++ b/scripts/build_buyer_packet.py
@@ -13,6 +13,11 @@
from pathlib import Path
from typing import Any
+try:
+ from scripts._bounded_json import read_json_object
+except ModuleNotFoundError:
+ from _bounded_json import read_json_object
+
PRODUCT_DOCS = [
"README.md",
@@ -48,11 +53,8 @@ def _sha256(path: Path) -> str:
def _read_json(path: Path) -> dict[str, Any]:
- with path.open(encoding="utf-8") as fh:
- payload = json.load(fh)
- if not isinstance(payload, dict):
- raise RuntimeError(f"JSON artifact must be an object: {path}")
- return payload
+ """Read one descriptor-safe bounded JSON object from disk."""
+ return read_json_object(path)
def _source_commit(repo_root: Path) -> str:
@@ -111,7 +113,11 @@ def _collect_files(
benchmark_report = _read_json(benchmark_report_path)
_add_file(files, "benchmark/benchmark_report.json", benchmark_report_path)
html_report_file = benchmark_report.get("html_report_file")
- html_report_path = Path(str(html_report_file)) if isinstance(html_report_file, str) and html_report_file else None
+ html_report_path = (
+ Path(str(html_report_file))
+ if isinstance(html_report_file, str) and html_report_file
+ else None
+ )
if html_report_path is not None and not html_report_path.is_absolute():
html_report_path = benchmark_report_path.parent / html_report_path
if html_report_path is None:
@@ -120,9 +126,15 @@ def _collect_files(
if release_evidence_index_path is not None:
release_index = _read_json(release_evidence_index_path)
- _add_file(files, "release/release_evidence_index.json", release_evidence_index_path)
+ _add_file(
+ files, "release/release_evidence_index.json", release_evidence_index_path
+ )
html_report_file = release_index.get("html_report_file")
- html_report_path = Path(str(html_report_file)) if isinstance(html_report_file, str) and html_report_file else None
+ html_report_path = (
+ Path(str(html_report_file))
+ if isinstance(html_report_file, str) and html_report_file
+ else None
+ )
if html_report_path is not None and not html_report_path.is_absolute():
html_report_path = release_evidence_index_path.parent / html_report_path
if html_report_path is None:
@@ -157,15 +169,23 @@ def _coverage(files: dict[str, Path]) -> dict[str, bool]:
return {
"acceptance_summary": "acceptance/acceptance_summary.json" in files,
"sales_readiness_manifest": "sales/sales_readiness_manifest.json" in files,
- "wheel": any(path.startswith("dist/") and path.endswith(".whl") for path in files),
- "sdist": any(path.startswith("dist/") and path.endswith(".tar.gz") for path in files),
+ "wheel": any(
+ path.startswith("dist/") and path.endswith(".whl") for path in files
+ ),
+ "sdist": any(
+ path.startswith("dist/") and path.endswith(".tar.gz") for path in files
+ ),
"product_docs": all(relative in files for relative in PRODUCT_DOCS),
"product_manifests": all(relative in files for relative in PRODUCT_MANIFESTS),
- "acceptance_artifacts": any(path.startswith("acceptance/artifacts/") for path in files),
+ "acceptance_artifacts": any(
+ path.startswith("acceptance/artifacts/") for path in files
+ ),
"html_report": "buyer_evidence_report.html" in files,
- "benchmark_report": "benchmark/benchmark_report.json" in files and "benchmark/benchmark_report.html" in files,
+ "benchmark_report": "benchmark/benchmark_report.json" in files
+ and "benchmark/benchmark_report.html" in files,
"release_evidence_index": (
- "release/release_evidence_index.json" in files and "release/release_evidence_index.html" in files
+ "release/release_evidence_index.json" in files
+ and "release/release_evidence_index.html" in files
),
}
@@ -191,7 +211,7 @@ def _render_report_html(manifest: dict[str, Any]) -> str:
"\n".join(
[
"",
- f"| {escape(name.replace('_', ' ').title())} | ",
+ f'{escape(name.replace("_", " ").title())} | ',
f"{escape(_format_value(ok))} | ",
"
",
]
@@ -207,7 +227,7 @@ def _render_report_html(manifest: dict[str, Any]) -> str:
"\n".join(
[
"",
- f"| {escape(str(item.get('archive_path', '')))} | ",
+ f'{escape(str(item.get("archive_path", "")))} | ',
f"{escape(str(item.get('size_bytes', '')))} | ",
f"{escape(str(item.get('sha256', '')))} | ",
"
",
@@ -225,7 +245,10 @@ def _render_report_html(manifest: dict[str, Any]) -> str:
("Contract Value", contract_value_display),
("Artifact Count", manifest.get("artifact_count", "")),
("Source Commit", manifest.get("source_commit", "")),
- ("Packet ZIP SHA256", manifest.get("zip_sha256", "calculated after archive write")),
+ (
+ "Packet ZIP SHA256",
+ manifest.get("zip_sha256", "calculated after archive write"),
+ ),
]
card_markup = [
"\n".join(
@@ -269,7 +292,7 @@ def _render_report_html(manifest: dict[str, Any]) -> str:
'',
"
",
"Required evidence coverage table",
- "| Evidence | Status |
",
+ '| Evidence | Status |
',
"",
*coverage_rows,
"",
@@ -281,7 +304,7 @@ def _render_report_html(manifest: dict[str, Any]) -> str:
'',
"
",
"Artifact digest table",
- "| Archive Path | Bytes | SHA256 |
",
+ '| Archive Path | Bytes | SHA256 |
',
"",
*file_rows,
"",
@@ -462,9 +485,13 @@ def build_packet(args: argparse.Namespace) -> dict[str, Any]:
acceptance_path=Path(args.acceptance).resolve(),
sales_readiness_path=Path(args.sales_readiness).resolve(),
dist_dir=Path(args.dist).resolve(),
- benchmark_report_path=Path(args.benchmark_report).resolve() if getattr(args, "benchmark_report", None) else None,
+ benchmark_report_path=Path(args.benchmark_report).resolve()
+ if getattr(args, "benchmark_report", None)
+ else None,
release_evidence_index_path=(
- Path(args.release_evidence_index).resolve() if getattr(args, "release_evidence_index", None) else None
+ Path(args.release_evidence_index).resolve()
+ if getattr(args, "release_evidence_index", None)
+ else None
),
)
file_entries = [
@@ -500,16 +527,22 @@ def build_packet(args: argparse.Namespace) -> dict[str, Any]:
]
coverage = _coverage(files)
optional_coverage = {"benchmark_report", "release_evidence_index"}
- required_coverage = {name: ok for name, ok in coverage.items() if name not in optional_coverage}
+ required_coverage = {
+ name: ok for name, ok in coverage.items() if name not in optional_coverage
+ }
if not all(required_coverage.values()):
missing = [name for name, ok in required_coverage.items() if not ok]
- raise RuntimeError(f"buyer evidence packet is missing required coverage: {missing}")
+ raise RuntimeError(
+ f"buyer evidence packet is missing required coverage: {missing}"
+ )
manifest["coverage"] = coverage
manifest["artifact_count"] = len(file_entries)
manifest["files"] = file_entries
manifest["report_file"] = str(report_path)
manifest["report_sha256"] = _sha256(report_path)
- manifest_path.write_text(json.dumps(manifest, indent=2, sort_keys=True), encoding="utf-8")
+ manifest_path.write_text(
+ json.dumps(manifest, indent=2, sort_keys=True), encoding="utf-8"
+ )
with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as packet:
for archive_path, path in sorted(files.items()):
@@ -520,20 +553,51 @@ def build_packet(args: argparse.Namespace) -> dict[str, Any]:
manifest["zip_sha256"] = _sha256(zip_path)
report_path.write_text(_render_report_html(manifest), encoding="utf-8")
manifest["report_sha256"] = _sha256(report_path)
- manifest_path.write_text(json.dumps(manifest, indent=2, sort_keys=True), encoding="utf-8")
+ manifest_path.write_text(
+ json.dumps(manifest, indent=2, sort_keys=True), encoding="utf-8"
+ )
return manifest
def build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(description="Build a portable fast-mlsirm buyer evidence packet.")
- parser.add_argument("--repo-root", default=".", help="Repository root containing docs and demo manifests.")
- parser.add_argument("--acceptance", required=True, help="Path to acceptance_summary.json.")
- parser.add_argument("--sales-readiness", required=True, help="Path to sales_readiness_manifest.json.")
- parser.add_argument("--dist", required=True, help="Directory containing the built wheel and sdist.")
- parser.add_argument("--out", default="buyer-evidence-packet", help="Output directory for packet files.")
- parser.add_argument("--contract-value-krw", type=int, default=2_000_000_000, help="Target contract value.")
- parser.add_argument("--benchmark-report", help="Optional benchmark_report.json to include in the packet.")
- parser.add_argument("--release-evidence-index", help="Optional release_evidence_index.json to include in the packet.")
+ parser = argparse.ArgumentParser(
+ description="Build a portable fast-mlsirm buyer evidence packet."
+ )
+ parser.add_argument(
+ "--repo-root",
+ default=".",
+ help="Repository root containing docs and demo manifests.",
+ )
+ parser.add_argument(
+ "--acceptance", required=True, help="Path to acceptance_summary.json."
+ )
+ parser.add_argument(
+ "--sales-readiness",
+ required=True,
+ help="Path to sales_readiness_manifest.json.",
+ )
+ parser.add_argument(
+ "--dist", required=True, help="Directory containing the built wheel and sdist."
+ )
+ parser.add_argument(
+ "--out",
+ default="buyer-evidence-packet",
+ help="Output directory for packet files.",
+ )
+ parser.add_argument(
+ "--contract-value-krw",
+ type=int,
+ default=2_000_000_000,
+ help="Target contract value.",
+ )
+ parser.add_argument(
+ "--benchmark-report",
+ help="Optional benchmark_report.json to include in the packet.",
+ )
+ parser.add_argument(
+ "--release-evidence-index",
+ help="Optional release_evidence_index.json to include in the packet.",
+ )
return parser
@@ -550,7 +614,9 @@ def main(argv: list[str] | None = None) -> int:
{
"status": manifest["status"],
"out": str(Path(args.out).resolve()),
- "manifest": str(Path(args.out).resolve() / "buyer_evidence_manifest.json"),
+ "manifest": str(
+ Path(args.out).resolve() / "buyer_evidence_manifest.json"
+ ),
"report": str(Path(args.out).resolve() / "buyer_evidence_report.html"),
"zip": manifest["zip_file"],
},
diff --git a/scripts/build_commercial_release.py b/scripts/build_commercial_release.py
index 35e4be795..9c7fa83a7 100644
--- a/scripts/build_commercial_release.py
+++ b/scripts/build_commercial_release.py
@@ -14,6 +14,11 @@
from pathlib import Path
from typing import Any, Callable
+try:
+ from scripts._bounded_json import read_json_object
+except ModuleNotFoundError:
+ from _bounded_json import read_json_object
+
Runner = Callable[[list[str], Path], subprocess.CompletedProcess[str]]
@@ -41,11 +46,8 @@ def _source_commit(repo_root: Path) -> str:
def _read_json(path: Path) -> dict[str, Any]:
- with path.open(encoding="utf-8") as fh:
- payload = json.load(fh)
- if not isinstance(payload, dict):
- raise RuntimeError(f"JSON artifact must be an object: {path}")
- return payload
+ """Read one descriptor-safe bounded JSON object from disk."""
+ return read_json_object(path)
def _resolve_path(value: str | Path, *, base: Path) -> Path:
@@ -125,7 +127,7 @@ def _render_html(manifest: dict[str, Any]) -> str:
continue
rows.append(
""
- f"| {escape(str(stage.get('name', '')))} | "
+ f'{escape(str(stage.get("name", "")))} | '
f"{escape(str(stage.get('status', '')))} | "
f"{escape(str(stage.get('duration_seconds', '')))} | "
f"{escape(' '.join(str(part) for part in stage.get('command', [])))} | "
@@ -139,7 +141,7 @@ def _render_html(manifest: dict[str, Any]) -> str:
continue
artifact_rows.append(
"
"
- f"| {escape(name.replace('_', ' ').title())} | "
+ f'{escape(name.replace("_", " ").title())} | '
f"{escape(str(artifact.get('exists', '')))} | "
f"{escape(str(artifact.get('name', '')))} | "
f"{escape(str(artifact.get('sha256', '')))} | "
@@ -147,9 +149,19 @@ def _render_html(manifest: dict[str, Any]) -> str:
)
cards = [
("Status", manifest.get("status", "")),
- ("Contract Value", f"KRW {manifest.get('contract_value_krw', ''):,}" if isinstance(manifest.get("contract_value_krw"), int) else ""),
+ (
+ "Contract Value",
+ f"KRW {manifest.get('contract_value_krw', ''):,}"
+ if isinstance(manifest.get("contract_value_krw"), int)
+ else "",
+ ),
("Source Commit", manifest.get("source_commit", "")),
- ("Stages", len(manifest.get("stages", [])) if isinstance(manifest.get("stages"), list) else ""),
+ (
+ "Stages",
+ len(manifest.get("stages", []))
+ if isinstance(manifest.get("stages"), list)
+ else "",
+ ),
("Failed Stage", manifest.get("failed_stage", "")),
]
card_markup = [
@@ -194,7 +206,7 @@ def _render_html(manifest: dict[str, Any]) -> str:
'',
"
",
"Commercial release stage table",
- "| Stage | Status | Seconds | Command |
",
+ '| Stage | Status | Seconds | Command |
',
"",
*rows,
"",
@@ -206,7 +218,7 @@ def _render_html(manifest: dict[str, Any]) -> str:
'',
"
",
"Commercial release artifact table",
- "| Artifact | Exists | File | SHA256 |
",
+ '| Artifact | Exists | File | SHA256 |
',
"",
*artifact_rows,
"",
@@ -374,7 +386,9 @@ def _report_css() -> str:
"""
-def _commands(args: argparse.Namespace, repo_root: Path, out_dir: Path) -> list[tuple[str, list[str]]]:
+def _commands(
+ args: argparse.Namespace, repo_root: Path, out_dir: Path
+) -> list[tuple[str, list[str]]]:
python = args.python
scripts = repo_root / "scripts"
dist_dir = _resolve_path(args.dist, base=repo_root).resolve()
@@ -385,7 +399,9 @@ def _commands(args: argparse.Namespace, repo_root: Path, out_dir: Path) -> list[
final_sales = acceptance_dir / "final_sales_readiness_manifest.json"
stages: list[tuple[str, list[str]]] = []
if not args.skip_build:
- stages.append(("build_dist", [python, "-m", "build", "--outdir", str(dist_dir)]))
+ stages.append(
+ ("build_dist", [python, "-m", "build", "--outdir", str(dist_dir)])
+ )
acceptance = [
python,
str(scripts / "release_acceptance.py"),
@@ -499,7 +515,9 @@ def _commands(args: argparse.Namespace, repo_root: Path, out_dir: Path) -> list[
return stages
-def _procurement_command(args: argparse.Namespace, repo_root: Path, out_dir: Path) -> list[str]:
+def _procurement_command(
+ args: argparse.Namespace, repo_root: Path, out_dir: Path
+) -> list[str]:
command = [
args.python,
str(repo_root / "scripts" / "build_procurement_due_diligence.py"),
@@ -521,7 +539,9 @@ def _procurement_command(args: argparse.Namespace, repo_root: Path, out_dir: Pat
return command
-def _pr_queue_command(args: argparse.Namespace, repo_root: Path, out_dir: Path) -> list[str]:
+def _pr_queue_command(
+ args: argparse.Namespace, repo_root: Path, out_dir: Path
+) -> list[str]:
command = [
args.python,
str(repo_root / "scripts" / "build_pr_queue_governance.py"),
@@ -538,11 +558,18 @@ def _pr_queue_command(args: argparse.Namespace, repo_root: Path, out_dir: Path)
]
offline_snapshot = getattr(args, "pr_queue_offline_snapshot", None)
if offline_snapshot:
- command.extend(["--offline-snapshot", str(_resolve_path(offline_snapshot, base=repo_root).resolve())])
+ command.extend(
+ [
+ "--offline-snapshot",
+ str(_resolve_path(offline_snapshot, base=repo_root).resolve()),
+ ]
+ )
return command
-def _figma_sync_command(args: argparse.Namespace, repo_root: Path, out_dir: Path) -> list[str]:
+def _figma_sync_command(
+ args: argparse.Namespace, repo_root: Path, out_dir: Path
+) -> list[str]:
command = [
args.python,
str(repo_root / "scripts" / "build_figma_evidence_sync.py"),
@@ -555,11 +582,18 @@ def _figma_sync_command(args: argparse.Namespace, repo_root: Path, out_dir: Path
"--contract-value-krw",
str(args.contract_value_krw),
"--figma-url",
- getattr(args, "figma_url", "https://www.figma.com/design/qD34PfMH8Kr41tFdqLCkem"),
+ getattr(
+ args, "figma_url", "https://www.figma.com/design/qD34PfMH8Kr41tFdqLCkem"
+ ),
]
metadata_snapshot = getattr(args, "figma_metadata_snapshot", None)
if metadata_snapshot:
- command.extend(["--metadata-snapshot", str(_resolve_path(metadata_snapshot, base=repo_root).resolve())])
+ command.extend(
+ [
+ "--metadata-snapshot",
+ str(_resolve_path(metadata_snapshot, base=repo_root).resolve()),
+ ]
+ )
return command
@@ -569,33 +603,75 @@ def _artifacts(args: argparse.Namespace, out_dir: Path) -> dict[str, dict[str, A
dist_dir = _resolve_path(args.dist, base=repo_root).resolve()
return {
"acceptance_summary": _artifact(acceptance_dir / "acceptance_summary.json"),
- "benchmark_report": _artifact(acceptance_dir / "benchmark" / "benchmark_report.json"),
- "benchmark_html": _artifact(acceptance_dir / "benchmark" / "benchmark_report.html"),
+ "benchmark_report": _artifact(
+ acceptance_dir / "benchmark" / "benchmark_report.json"
+ ),
+ "benchmark_html": _artifact(
+ acceptance_dir / "benchmark" / "benchmark_report.html"
+ ),
"sales_readiness": _artifact(acceptance_dir / "sales_readiness_manifest.json"),
- "buyer_packet_manifest": _artifact(out_dir / "buyer-evidence-packet" / "buyer_evidence_manifest.json"),
- "buyer_packet_zip": _artifact(out_dir / "buyer-evidence-packet" / "fast_mlsirm_buyer_evidence_packet.zip"),
- "buyer_packet_html": _artifact(out_dir / "buyer-evidence-packet" / "buyer_evidence_report.html"),
- "release_evidence_index": _artifact(out_dir / "release-evidence-index" / "release_evidence_index.json"),
- "release_evidence_html": _artifact(out_dir / "release-evidence-index" / "release_evidence_index.html"),
- "final_sales_readiness": _artifact(acceptance_dir / "final_sales_readiness_manifest.json"),
- "procurement_due_diligence": _artifact(out_dir / "procurement-due-diligence" / "procurement_due_diligence_manifest.json"),
- "procurement_due_diligence_html": _artifact(out_dir / "procurement-due-diligence" / "procurement_due_diligence_report.html"),
- "pr_queue_governance": _artifact(out_dir / "pr-queue-governance" / "pr_queue_governance_manifest.json"),
- "pr_queue_governance_html": _artifact(out_dir / "pr-queue-governance" / "pr_queue_governance_report.html"),
- "figma_evidence_sync": _artifact(out_dir / "figma-evidence-sync" / "figma_evidence_sync_manifest.json"),
- "figma_evidence_sync_html": _artifact(out_dir / "figma-evidence-sync" / "figma_evidence_sync_report.html"),
- "wheel": _artifact(next(iter(sorted(dist_dir.glob("*.whl"))), dist_dir / "missing.whl")),
- "sdist": _artifact(next(iter(sorted(dist_dir.glob("*.tar.gz"))), dist_dir / "missing.tar.gz")),
+ "buyer_packet_manifest": _artifact(
+ out_dir / "buyer-evidence-packet" / "buyer_evidence_manifest.json"
+ ),
+ "buyer_packet_zip": _artifact(
+ out_dir / "buyer-evidence-packet" / "fast_mlsirm_buyer_evidence_packet.zip"
+ ),
+ "buyer_packet_html": _artifact(
+ out_dir / "buyer-evidence-packet" / "buyer_evidence_report.html"
+ ),
+ "release_evidence_index": _artifact(
+ out_dir / "release-evidence-index" / "release_evidence_index.json"
+ ),
+ "release_evidence_html": _artifact(
+ out_dir / "release-evidence-index" / "release_evidence_index.html"
+ ),
+ "final_sales_readiness": _artifact(
+ acceptance_dir / "final_sales_readiness_manifest.json"
+ ),
+ "procurement_due_diligence": _artifact(
+ out_dir
+ / "procurement-due-diligence"
+ / "procurement_due_diligence_manifest.json"
+ ),
+ "procurement_due_diligence_html": _artifact(
+ out_dir
+ / "procurement-due-diligence"
+ / "procurement_due_diligence_report.html"
+ ),
+ "pr_queue_governance": _artifact(
+ out_dir / "pr-queue-governance" / "pr_queue_governance_manifest.json"
+ ),
+ "pr_queue_governance_html": _artifact(
+ out_dir / "pr-queue-governance" / "pr_queue_governance_report.html"
+ ),
+ "figma_evidence_sync": _artifact(
+ out_dir / "figma-evidence-sync" / "figma_evidence_sync_manifest.json"
+ ),
+ "figma_evidence_sync_html": _artifact(
+ out_dir / "figma-evidence-sync" / "figma_evidence_sync_report.html"
+ ),
+ "wheel": _artifact(
+ next(iter(sorted(dist_dir.glob("*.whl"))), dist_dir / "missing.whl")
+ ),
+ "sdist": _artifact(
+ next(iter(sorted(dist_dir.glob("*.tar.gz"))), dist_dir / "missing.tar.gz")
+ ),
}
-def _write_outputs(manifest: dict[str, Any], manifest_path: Path, html_path: Path) -> None:
+def _write_outputs(
+ manifest: dict[str, Any], manifest_path: Path, html_path: Path
+) -> None:
html_path.write_text(_render_html(manifest), encoding="utf-8")
manifest["html_report_sha256"] = _sha256(html_path)
- manifest_path.write_text(json.dumps(manifest, indent=2, sort_keys=True), encoding="utf-8")
+ manifest_path.write_text(
+ json.dumps(manifest, indent=2, sort_keys=True), encoding="utf-8"
+ )
-def build_commercial_release(args: argparse.Namespace, *, runner: Runner = _run_command) -> dict[str, Any]:
+def build_commercial_release(
+ args: argparse.Namespace, *, runner: Runner = _run_command
+) -> dict[str, Any]:
repo_root = Path(args.repo_root).resolve()
out_dir = _resolve_path(args.out, base=repo_root).resolve()
dist_dir = _resolve_path(args.dist, base=repo_root).resolve()
@@ -625,14 +701,22 @@ def build_commercial_release(args: argparse.Namespace, *, runner: Runner = _run_
break
manifest["total_duration_seconds"] = round(time.perf_counter() - started, 6)
manifest["artifacts"] = _artifacts(args, out_dir)
- if manifest["failed_stage"] is None and all(stage.get("status") == "ok" for stage in manifest["stages"]):
- final_path = out_dir / "release-acceptance" / "final_sales_readiness_manifest.json"
- final_status = _read_json(final_path).get("status") if final_path.exists() else None
+ if manifest["failed_stage"] is None and all(
+ stage.get("status") == "ok" for stage in manifest["stages"]
+ ):
+ final_path = (
+ out_dir / "release-acceptance" / "final_sales_readiness_manifest.json"
+ )
+ final_status = (
+ _read_json(final_path).get("status") if final_path.exists() else None
+ )
manifest["status"] = "ok" if final_status == "ok" else "failed"
if final_status != "ok":
manifest["failed_stage"] = "final_sales_readiness"
_write_outputs(manifest, manifest_path, html_path)
- if manifest["status"] == "ok" and not getattr(args, "skip_procurement_due_diligence", False):
+ if manifest["status"] == "ok" and not getattr(
+ args, "skip_procurement_due_diligence", False
+ ):
stage = _stage(
"procurement_due_diligence",
_procurement_command(args, repo_root, out_dir),
@@ -646,7 +730,9 @@ def build_commercial_release(args: argparse.Namespace, *, runner: Runner = _run_
manifest["total_duration_seconds"] = round(time.perf_counter() - started, 6)
manifest["artifacts"] = _artifacts(args, out_dir)
_write_outputs(manifest, manifest_path, html_path)
- if manifest["status"] == "ok" and not getattr(args, "skip_pr_queue_governance", False):
+ if manifest["status"] == "ok" and not getattr(
+ args, "skip_pr_queue_governance", False
+ ):
stage = _stage(
"pr_queue_governance",
_pr_queue_command(args, repo_root, out_dir),
@@ -660,7 +746,9 @@ def build_commercial_release(args: argparse.Namespace, *, runner: Runner = _run_
manifest["total_duration_seconds"] = round(time.perf_counter() - started, 6)
manifest["artifacts"] = _artifacts(args, out_dir)
_write_outputs(manifest, manifest_path, html_path)
- if manifest["status"] == "ok" and not getattr(args, "skip_figma_evidence_sync", False):
+ if manifest["status"] == "ok" and not getattr(
+ args, "skip_figma_evidence_sync", False
+ ):
stage = _stage(
"figma_evidence_sync",
_figma_sync_command(args, repo_root, out_dir),
@@ -678,28 +766,90 @@ def build_commercial_release(args: argparse.Namespace, *, runner: Runner = _run_
def build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(description="Build the full fast-mlsirm commercial release evidence bundle.")
+ parser = argparse.ArgumentParser(
+ description="Build the full fast-mlsirm commercial release evidence bundle."
+ )
parser.add_argument("--repo-root", default=".", help="Repository root.")
- parser.add_argument("--out", default="commercial-release", help="Output directory for all commercial release evidence.")
- parser.add_argument("--dist", default="dist", help="Directory containing or receiving built wheel and sdist artifacts.")
- parser.add_argument("--python", default=sys.executable, help="Python executable used for subcommands.")
- parser.add_argument("--contract-value-krw", type=int, default=2_000_000_000, help="Target contract value.")
- parser.add_argument("--require-rust", action="store_true", help="Require explicit Rust backend evidence.")
- parser.add_argument("--check-import", action="store_true", help="Validate importability in sales readiness gates.")
- parser.add_argument("--skip-build", action="store_true", help="Use existing dist artifacts instead of running python -m build.")
- parser.add_argument("--skip-procurement-due-diligence", action="store_true", help="Skip the procurement due-diligence evidence stage.")
- parser.add_argument("--skip-pr-queue-governance", action="store_true", help="Skip the PR queue governance evidence stage.")
- parser.add_argument("--skip-figma-evidence-sync", action="store_true", help="Skip the Figma evidence sync stage.")
- parser.add_argument("--offline-github", action="store_true", help="Use offline GitHub snapshot mode for due diligence.")
- parser.add_argument("--pr-queue-offline-snapshot", help="Optional offline PR queue snapshot JSON for governance evidence.")
- parser.add_argument("--pr-queue-max-stale-days", type=int, default=14, help="Age in days after which an open PR is stale.")
- parser.add_argument("--figma-metadata-snapshot", help="Optional exported live Figma metadata snapshot JSON.")
+ parser.add_argument(
+ "--out",
+ default="commercial-release",
+ help="Output directory for all commercial release evidence.",
+ )
+ parser.add_argument(
+ "--dist",
+ default="dist",
+ help="Directory containing or receiving built wheel and sdist artifacts.",
+ )
+ parser.add_argument(
+ "--python",
+ default=sys.executable,
+ help="Python executable used for subcommands.",
+ )
+ parser.add_argument(
+ "--contract-value-krw",
+ type=int,
+ default=2_000_000_000,
+ help="Target contract value.",
+ )
+ parser.add_argument(
+ "--require-rust",
+ action="store_true",
+ help="Require explicit Rust backend evidence.",
+ )
+ parser.add_argument(
+ "--check-import",
+ action="store_true",
+ help="Validate importability in sales readiness gates.",
+ )
+ parser.add_argument(
+ "--skip-build",
+ action="store_true",
+ help="Use existing dist artifacts instead of running python -m build.",
+ )
+ parser.add_argument(
+ "--skip-procurement-due-diligence",
+ action="store_true",
+ help="Skip the procurement due-diligence evidence stage.",
+ )
+ parser.add_argument(
+ "--skip-pr-queue-governance",
+ action="store_true",
+ help="Skip the PR queue governance evidence stage.",
+ )
+ parser.add_argument(
+ "--skip-figma-evidence-sync",
+ action="store_true",
+ help="Skip the Figma evidence sync stage.",
+ )
+ parser.add_argument(
+ "--offline-github",
+ action="store_true",
+ help="Use offline GitHub snapshot mode for due diligence.",
+ )
+ parser.add_argument(
+ "--pr-queue-offline-snapshot",
+ help="Optional offline PR queue snapshot JSON for governance evidence.",
+ )
+ parser.add_argument(
+ "--pr-queue-max-stale-days",
+ type=int,
+ default=14,
+ help="Age in days after which an open PR is stale.",
+ )
+ parser.add_argument(
+ "--figma-metadata-snapshot",
+ help="Optional exported live Figma metadata snapshot JSON.",
+ )
parser.add_argument(
"--figma-url",
default="https://www.figma.com/design/qD34PfMH8Kr41tFdqLCkem",
help="Fallback Figma design URL for the evidence sync stage.",
)
- parser.add_argument("--repo", default="ContextualWisdomLab/fast-mlsirm", help="GitHub repository for due-diligence snapshots.")
+ parser.add_argument(
+ "--repo",
+ default="ContextualWisdomLab/fast-mlsirm",
+ help="GitHub repository for due-diligence snapshots.",
+ )
return parser
@@ -716,7 +866,9 @@ def main(argv: list[str] | None = None) -> int:
{
"status": manifest["status"],
"out": manifest["out"],
- "manifest": str(Path(manifest["out"]) / "commercial_release_manifest.json"),
+ "manifest": str(
+ Path(manifest["out"]) / "commercial_release_manifest.json"
+ ),
"html": manifest["html_report_file"],
"failed_stage": manifest["failed_stage"],
},
diff --git a/scripts/build_figma_evidence_sync.py b/scripts/build_figma_evidence_sync.py
index b9725e320..058ce5159 100644
--- a/scripts/build_figma_evidence_sync.py
+++ b/scripts/build_figma_evidence_sync.py
@@ -12,6 +12,11 @@
from pathlib import Path
from typing import Any
+try:
+ from scripts._bounded_json import read_json_object
+except ModuleNotFoundError:
+ from _bounded_json import read_json_object
+
REQUIRED_FRAME_IDS = [
"01-package-evidence",
@@ -47,11 +52,8 @@ def _sha256(path: Path) -> str:
def _read_json(path: Path) -> dict[str, Any]:
- with path.open(encoding="utf-8") as fh:
- payload = json.load(fh)
- if not isinstance(payload, dict):
- raise RuntimeError(f"JSON artifact must be an object: {path}")
- return payload
+ """Read one descriptor-safe bounded JSON object from disk."""
+ return read_json_object(path)
def _resolve_path(value: str | Path, *, base: Path) -> Path:
@@ -75,8 +77,15 @@ def _source_commit(repo_root: Path) -> str:
return completed.stdout.strip() or "unknown"
-def _check(name: str, category: str, ok: bool, detail: str, **metadata: Any) -> dict[str, Any]:
- payload: dict[str, Any] = {"name": name, "category": category, "ok": ok, "detail": detail}
+def _check(
+ name: str, category: str, ok: bool, detail: str, **metadata: Any
+) -> dict[str, Any]:
+ payload: dict[str, Any] = {
+ "name": name,
+ "category": category,
+ "ok": ok,
+ "detail": detail,
+ }
payload.update(metadata)
return payload
@@ -98,7 +107,11 @@ def _frame_coverage(packet: dict[str, Any]) -> dict[str, Any]:
for frame in frames
if isinstance(frame, dict) and isinstance(frame.get("id"), str)
}
- return {"required": REQUIRED_FRAME_IDS, "present": sorted(ids), "missing": sorted(set(REQUIRED_FRAME_IDS) - ids)}
+ return {
+ "required": REQUIRED_FRAME_IDS,
+ "present": sorted(ids),
+ "missing": sorted(set(REQUIRED_FRAME_IDS) - ids),
+ }
def _snapshot_text(snapshot: dict[str, Any]) -> str:
@@ -185,7 +198,7 @@ def _render_report(manifest: dict[str, Any]) -> str:
continue
rows.append(
""
- f"| {escape(str(check.get('name', '')))} | "
+ f'{escape(str(check.get("name", "")))} | '
f"{escape(str(check.get('category', '')))} | "
f"{escape('go' if check.get('ok') else 'failed')} | "
f"{escape(str(check.get('detail', '')))} | "
@@ -193,13 +206,27 @@ def _render_report(manifest: dict[str, Any]) -> str:
)
cards = [
("Status", manifest.get("status", "")),
- ("Code Connect", "disabled" if manifest.get("code_connect") is False else manifest.get("code_connect", "")),
+ (
+ "Code Connect",
+ "disabled"
+ if manifest.get("code_connect") is False
+ else manifest.get("code_connect", ""),
+ ),
("Frames", len(manifest.get("frame_coverage", {}).get("present", []))),
- ("Missing Tokens", len(manifest.get("required_token_coverage", {}).get("missing", []))),
- ("Metadata Snapshot", "checked" if manifest.get("metadata_snapshot", {}).get("checked") else "not required"),
+ (
+ "Missing Tokens",
+ len(manifest.get("required_token_coverage", {}).get("missing", [])),
+ ),
+ (
+ "Metadata Snapshot",
+ "checked"
+ if manifest.get("metadata_snapshot", {}).get("checked")
+ else "not required",
+ ),
]
card_markup = [
- "" f"{escape(label)}{escape(str(value))}"
+ ''
+ f"{escape(label)}{escape(str(value))}"
for label, value in cards
]
return "\n".join(
@@ -224,7 +251,7 @@ def _render_report(manifest: dict[str, Any]) -> str:
'Sync Checks
',
'',
"
Figma evidence sync table",
- "| Check | Category | Status | Detail |
",
+ '| Check | Category | Status | Detail |
',
*rows,
"
",
'This report verifies repo-local Figma packet evidence. Live Figma metadata is optional and supplied as an exported snapshot.
',
@@ -245,18 +272,32 @@ def build_figma_evidence_sync(args: argparse.Namespace) -> dict[str, Any]:
code_connect = packet.get("code_connect")
figma_url = str(packet.get("figma_artifact_url") or args.figma_url)
url_ok = figma_url.startswith("https://www.figma.com/design/")
- snapshot_info: dict[str, Any] = {"checked": False, "path": None, "token_coverage": {"missing": []}}
+ snapshot_info: dict[str, Any] = {
+ "checked": False,
+ "path": None,
+ "token_coverage": {"missing": []},
+ }
metadata_snapshot = getattr(args, "metadata_snapshot", None)
metadata_check_ok = True
if metadata_snapshot:
snapshot_path = _resolve_path(metadata_snapshot, base=repo_root).resolve()
snapshot = _read_json(snapshot_path)
snapshot_coverage = _coverage(_snapshot_text(snapshot), REQUIRED_TOKENS)
- snapshot_info = {"checked": True, "path": str(snapshot_path), "token_coverage": snapshot_coverage}
+ snapshot_info = {
+ "checked": True,
+ "path": str(snapshot_path),
+ "token_coverage": snapshot_coverage,
+ }
metadata_check_ok = snapshot_coverage["missing"] == []
checks = [
- _check("figma:packet", "figma_packet", packet_path.exists(), "Figma design packet JSON exists", path=str(packet_path)),
+ _check(
+ "figma:packet",
+ "figma_packet",
+ packet_path.exists(),
+ "Figma design packet JSON exists",
+ path=str(packet_path),
+ ),
_check(
"figma:code_connect_disabled",
"figma_policy",
@@ -299,7 +340,8 @@ def build_figma_evidence_sync(args: argparse.Namespace) -> dict[str, Any]:
"command": "build_figma_evidence_sync",
"status": "ok" if not failed else "failed",
"contract_value_krw": args.contract_value_krw,
- "generated_at": getattr(args, "generated_at", None) or datetime.now(UTC).isoformat(timespec="seconds"),
+ "generated_at": getattr(args, "generated_at", None)
+ or datetime.now(UTC).isoformat(timespec="seconds"),
"source_commit": _source_commit(repo_root),
"repo_root": str(repo_root),
"packet": str(packet_path),
@@ -316,21 +358,35 @@ def build_figma_evidence_sync(args: argparse.Namespace) -> dict[str, Any]:
html_path.write_text(_render_report(manifest), encoding="utf-8")
manifest["html_report_file"] = str(html_path)
manifest["html_report_sha256"] = _sha256(html_path)
- manifest_path.write_text(json.dumps(manifest, indent=2, sort_keys=True), encoding="utf-8")
+ manifest_path.write_text(
+ json.dumps(manifest, indent=2, sort_keys=True), encoding="utf-8"
+ )
return manifest
def build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(description="Build Figma evidence sync checks for fast-mlsirm.")
+ parser = argparse.ArgumentParser(
+ description="Build Figma evidence sync checks for fast-mlsirm."
+ )
parser.add_argument("--repo-root", default=".", help="Repository root.")
parser.add_argument(
"--packet",
default="examples/enterprise_demo/figma_design_packet.json",
help="Path to figma_design_packet.json.",
)
- parser.add_argument("--metadata-snapshot", help="Optional exported live Figma metadata JSON snapshot.")
- parser.add_argument("--out", default="figma-evidence-sync", help="Output directory.")
- parser.add_argument("--contract-value-krw", type=int, default=2_000_000_000, help="Target contract value.")
+ parser.add_argument(
+ "--metadata-snapshot",
+ help="Optional exported live Figma metadata JSON snapshot.",
+ )
+ parser.add_argument(
+ "--out", default="figma-evidence-sync", help="Output directory."
+ )
+ parser.add_argument(
+ "--contract-value-krw",
+ type=int,
+ default=2_000_000_000,
+ help="Target contract value.",
+ )
parser.add_argument(
"--figma-url",
default="https://www.figma.com/design/qD34PfMH8Kr41tFdqLCkem",
@@ -347,12 +403,14 @@ def main(argv: list[str] | None = None) -> int:
except Exception as exc:
print(json.dumps({"status": "failed", "error": str(exc)}, ensure_ascii=False))
return 1
+ repo_root = Path(args.repo_root).resolve()
+ out_dir = _resolve_path(args.out, base=repo_root).resolve()
print(
json.dumps(
{
"status": manifest["status"],
- "out": str(Path(args.out).resolve()),
- "manifest": str(Path(args.out).resolve() / "figma_evidence_sync_manifest.json"),
+ "out": str(out_dir),
+ "manifest": str(out_dir / "figma_evidence_sync_manifest.json"),
"html": manifest["html_report_file"],
"failed_checks": len(manifest["failed_checks"]),
},
@@ -364,4 +422,4 @@ def main(argv: list[str] | None = None) -> int:
if __name__ == "__main__":
- raise SystemExit(main())
\ No newline at end of file
+ raise SystemExit(main())
diff --git a/scripts/build_pr_queue_governance.py b/scripts/build_pr_queue_governance.py
index 5b2d49979..1917d1f2f 100644
--- a/scripts/build_pr_queue_governance.py
+++ b/scripts/build_pr_queue_governance.py
@@ -15,6 +15,11 @@
from typing import Any
from urllib.parse import urlparse
+try:
+ from scripts._bounded_json import read_json_object
+except ModuleNotFoundError:
+ from _bounded_json import read_json_object
+
RISK_COUNT_KEYS = [
"changes_requested",
@@ -84,12 +89,8 @@ def _sha256(path: Path) -> str:
def _read_json(path: Path) -> dict[str, Any]:
- """Read a JSON object from disk."""
- with path.open(encoding="utf-8") as fh:
- payload = json.load(fh)
- if not isinstance(payload, dict):
- raise RuntimeError(f"JSON artifact must be an object: {path}")
- return payload
+ """Read one descriptor-safe bounded JSON object from disk."""
+ return read_json_object(path)
def _resolve_path(value: str | Path, *, base: Path) -> Path:
@@ -308,14 +309,18 @@ def _issue_references(body: object) -> list[int]:
"""Return sorted issue numbers referenced by closing keywords."""
if not isinstance(body, str):
return []
- return sorted({int(match.group("issue")) for match in _CLOSING_REFERENCE_RE.finditer(body)})
+ return sorted(
+ {int(match.group("issue")) for match in _CLOSING_REFERENCE_RE.finditer(body)}
+ )
def _canonical_issue_references(body: object) -> list[int]:
"""Return sorted issue numbers explicitly designated by ``Canonical-For``."""
if not isinstance(body, str):
return []
- return sorted({int(match.group("issue")) for match in _CANONICAL_REFERENCE_RE.finditer(body)})
+ return sorted(
+ {int(match.group("issue")) for match in _CANONICAL_REFERENCE_RE.finditer(body)}
+ )
def _label_names(pr: dict[str, Any]) -> list[str]:
@@ -382,7 +387,9 @@ def classify_pr(
duplicate_terms = sorted(term for term in DUPLICATE_TERMS if term in text)
changes_requested = review_decision == "CHANGES_REQUESTED"
stale = age_days is not None and age_days > max_stale_days
- review_or_check_delay = review_decision == "REVIEW_REQUIRED" or merge_state == "QUEUED"
+ review_or_check_delay = (
+ review_decision == "REVIEW_REQUIRED" or merge_state == "QUEUED"
+ )
release_scope_conflict = bool(release_scope_terms)
duplicate_candidate = bool(duplicate_terms) and not release_scope_conflict
@@ -463,9 +470,7 @@ def _duplicate_issue_claims(
key=lambda record: record["pr_number"],
)
designated = [
- record["pr_number"]
- for record in records
- if record["canonical_for_issue"]
+ record["pr_number"] for record in records if record["canonical_for_issue"]
]
canonical_pr = designated[0] if len(designated) == 1 else None
conflicts[str(issue_number)] = {
@@ -644,14 +649,21 @@ def _render_report(manifest: dict[str, Any]) -> str:
("Base SHA", manifest.get("base_sha", "")),
("Duplicate conflicts", unresolved_count),
("Duplicate heads", len(manifest.get("duplicate_head_warnings", []))),
- ("File-overlap warnings", len(manifest.get("changed_file_overlap_warnings", []))),
+ (
+ "File-overlap warnings",
+ len(manifest.get("changed_file_overlap_warnings", [])),
+ ),
(
"Changes requested",
- risk_counts.get("changes_requested", "") if isinstance(risk_counts, dict) else "",
+ risk_counts.get("changes_requested", "")
+ if isinstance(risk_counts, dict)
+ else "",
),
(
"Review delay",
- risk_counts.get("review_or_check_delay", "") if isinstance(risk_counts, dict) else "",
+ risk_counts.get("review_or_check_delay", "")
+ if isinstance(risk_counts, dict)
+ else "",
),
]
card_markup = [
@@ -667,13 +679,13 @@ def _render_report(manifest: dict[str, Any]) -> str:
pr_rows.append(
""
f'| '
- f'#{escape(str(pr.get("number", "")))} | '
- f'{escape(str(pr.get("title", "")))} | '
- f'{escape(str(pr.get("headRefOid", "")))} | '
- f'{escape(", ".join(f"#{item}" for item in pr.get("closing_issue_references", [])))} | '
- f'{escape(str(pr.get("reviewDecision", "")))} | '
- f'{escape(str(pr.get("mergeStateStatus", "")))} | '
- f'{escape(", ".join(str(reason) for reason in pr.get("risk_reasons", [])))} | '
+ f"#{escape(str(pr.get('number', '')))}"
+ f"{escape(str(pr.get('title', '')))} | "
+ f"{escape(str(pr.get('headRefOid', '')))} | "
+ f"{escape(', '.join(f'#{item}' for item in pr.get('closing_issue_references', [])))} | "
+ f"{escape(str(pr.get('reviewDecision', '')))} | "
+ f"{escape(str(pr.get('mergeStateStatus', '')))} | "
+ f"{escape(', '.join(str(reason) for reason in pr.get('risk_reasons', [])))} | "
"
"
)
@@ -685,17 +697,17 @@ def _render_report(manifest: dict[str, Any]) -> str:
continue
claimants = claim.get("claimant_prs", [])
claimant_text = ", ".join(
- f'#{record.get("pr_number")} ({record.get("head_sha", "")})'
+ f"#{record.get('pr_number')} ({record.get('head_sha', '')})"
for record in claimants
if isinstance(record, dict)
)
claim_rows.append(
""
f'| #{escape(str(claim.get("issue_number", "")))} | '
- f'{escape(str(claim.get("status", "")))} | '
- f'{escape(str(claim.get("canonical_pr") or ""))} | '
- f'{escape(claimant_text)} | '
- f'{escape(str(claim.get("reason", "")))} | '
+ f"{escape(str(claim.get('status', '')))} | "
+ f"{escape(str(claim.get('canonical_pr') or ''))} | "
+ f"{escape(claimant_text)} | "
+ f"{escape(str(claim.get('reason', '')))} | "
"
"
)
@@ -706,9 +718,9 @@ def _render_report(manifest: dict[str, Any]) -> str:
warning_rows.append(
""
f'| {escape(", ".join(f"#{number}" for number in warning.get("pr_numbers", [])))} | '
- f'{escape(str(warning.get("identical", "")))} | '
- f'{escape(str(warning.get("jaccard", "")))} | '
- f'{escape(", ".join(str(path) for path in warning.get("intersection", [])))} | '
+ f"{escape(str(warning.get('identical', '')))} | "
+ f"{escape(str(warning.get('jaccard', '')))} | "
+ f"{escape(', '.join(str(path) for path in warning.get('intersection', [])))} | "
"
"
)
@@ -719,12 +731,12 @@ def _render_report(manifest: dict[str, Any]) -> str:
history_rows.append(
""
f'| #{escape(str(record.get("pr_number", "")))} | '
- f'{escape(str(record.get("state", "")))} | '
- f'{escape(str(record.get("head_sha", "")))} | '
- f'{escape(", ".join(f"#{item}" for item in record.get("issue_references", [])))} | '
- f'{escape(str(record.get("updated_at", "")))} | '
- f'{escape(str(record.get("closed_at", "")))} | '
- f'{escape(str(record.get("merged_at", "")))} | '
+ f"{escape(str(record.get('state', '')))} | "
+ f"{escape(str(record.get('head_sha', '')))} | "
+ f"{escape(', '.join(f'#{item}' for item in record.get('issue_references', [])))} | "
+ f"{escape(str(record.get('updated_at', '')))} | "
+ f"{escape(str(record.get('closed_at', '')))} | "
+ f"{escape(str(record.get('merged_at', '')))} | "
"
"
)
@@ -735,9 +747,9 @@ def _render_report(manifest: dict[str, Any]) -> str:
check_rows.append(
""
f'| {escape(str(check.get("name", "")))} | '
- f'{escape(str(check.get("category", "")))} | '
- f'{escape("go" if check.get("ok") else "failed")} | '
- f'{escape(str(check.get("detail", "")))} | '
+ f"{escape(str(check.get('category', '')))} | "
+ f"{escape('go' if check.get('ok') else 'failed')} | "
+ f"{escape(str(check.get('detail', '')))} | "
"
"
)
@@ -756,9 +768,9 @@ def _render_report(manifest: dict[str, Any]) -> str:
"",
"",
'fast-mlsirm buyer governance
PR Queue Governance
',
- f'Repository: {escape(str(manifest.get("repo", "")))} · '
- f'Base: {escape(str(manifest.get("base_sha", "")))} · '
- f'Generated: {escape(str(manifest.get("generated_at", "")))}',
+ f"Repository: {escape(str(manifest.get('repo', '')))} · "
+ f"Base: {escape(str(manifest.get('base_sha', '')))} · "
+ f"Generated: {escape(str(manifest.get('generated_at', '')))}",
'Queue Summary
',
*card_markup,
"
",
@@ -766,7 +778,15 @@ def _render_report(manifest: dict[str, Any]) -> str:
*_table(
label="PR queue governance table",
caption="PR queue governance table",
- headings=["PR", "Title", "Head SHA", "Issue references", "Review", "Merge", "Risk reasons"],
+ headings=[
+ "PR",
+ "Title",
+ "Head SHA",
+ "Issue references",
+ "Review",
+ "Merge",
+ "Risk reasons",
+ ],
rows=pr_rows,
),
"",
@@ -774,11 +794,17 @@ def _render_report(manifest: dict[str, Any]) -> str:
*_table(
label="Duplicate issue claim table",
caption="Duplicate issue claim table",
- headings=["Issue", "Status", "Canonical PR", "Active claimants", "Reason"],
+ headings=[
+ "Issue",
+ "Status",
+ "Canonical PR",
+ "Active claimants",
+ "Reason",
+ ],
rows=claim_rows,
),
'A duplicate issue claim is resolved only when exactly one active claimant includes '
- 'Canonical-For: #issue in its body.
',
+ "Canonical-For: #issue in its body.",
'Changed-file Overlap Warnings
',
*_table(
label="Changed-file overlap warning table",
@@ -787,13 +813,21 @@ def _render_report(manifest: dict[str, Any]) -> str:
rows=warning_rows,
),
'One-file intersections are excluded to avoid treating '
- 'shared central files as duplicates.
',
+ "shared central files as duplicates.",
"",
'Issue Claim Audit History
',
*_table(
label="Issue claim audit history table",
caption="Issue claim audit history table",
- headings=["PR", "State", "Head SHA", "Issue references", "Updated", "Closed", "Merged"],
+ headings=[
+ "PR",
+ "State",
+ "Head SHA",
+ "Issue references",
+ "Updated",
+ "Closed",
+ "Merged",
+ ],
rows=history_rows,
),
"",
@@ -814,9 +848,8 @@ def build_pr_queue_governance(args: argparse.Namespace) -> dict[str, Any]:
repo_root = Path(args.repo_root).resolve()
out_dir = _resolve_path(args.out, base=repo_root).resolve()
out_dir.mkdir(parents=True, exist_ok=True)
- generated_at = (
- getattr(args, "generated_at", None)
- or datetime.now(UTC).isoformat(timespec="seconds")
+ generated_at = getattr(args, "generated_at", None) or datetime.now(UTC).isoformat(
+ timespec="seconds"
)
now = _parse_datetime(generated_at)
snapshot = _snapshot_from_args(args, repo_root)
@@ -997,8 +1030,7 @@ def main(argv: list[str] | None = None) -> int:
"status": manifest["status"],
"out": str(Path(args.out).resolve()),
"manifest": str(
- Path(args.out).resolve()
- / "pr_queue_governance_manifest.json"
+ Path(args.out).resolve() / "pr_queue_governance_manifest.json"
),
"html": manifest["html_report_file"],
"open_pr_count": manifest["open_pr_count"],
diff --git a/scripts/build_procurement_due_diligence.py b/scripts/build_procurement_due_diligence.py
index ade0c1b27..5c4a90200 100644
--- a/scripts/build_procurement_due_diligence.py
+++ b/scripts/build_procurement_due_diligence.py
@@ -15,6 +15,11 @@
from pathlib import Path
from typing import Any
+try:
+ from scripts._bounded_json import read_json_object
+except ModuleNotFoundError:
+ from _bounded_json import read_json_object
+
POLICY_FILES = [
"README.md",
@@ -39,11 +44,8 @@ def _sha256(path: Path) -> str:
def _read_json(path: Path) -> dict[str, Any]:
- with path.open(encoding="utf-8") as fh:
- payload = json.load(fh)
- if not isinstance(payload, dict):
- raise RuntimeError(f"JSON artifact must be an object: {path}")
- return payload
+ """Read one descriptor-safe bounded JSON object from disk."""
+ return read_json_object(path)
def _resolve_path(value: str | Path, *, base: Path) -> Path:
@@ -55,7 +57,10 @@ def _resolve_path(value: str | Path, *, base: Path) -> Path:
def _metadata_dict(text: str) -> dict[str, str]:
parsed = Parser().parsestr(text)
- return {key: parsed.get(key, "") for key in ["Name", "Version", "License", "Requires-Python"]}
+ return {
+ key: parsed.get(key, "")
+ for key in ["Name", "Version", "License", "Requires-Python"]
+ }
def parse_wheel(path: Path) -> dict[str, Any]:
@@ -63,7 +68,12 @@ def parse_wheel(path: Path) -> dict[str, Any]:
metadata: dict[str, str] = {}
members: list[str] = []
if not path.exists():
- return {"ok": False, "path": str(path), "missing": sorted(required), "metadata": metadata}
+ return {
+ "ok": False,
+ "path": str(path),
+ "missing": sorted(required),
+ "metadata": metadata,
+ }
with zipfile.ZipFile(path) as archive:
members = archive.namelist()
for name in members:
@@ -71,7 +81,9 @@ def parse_wheel(path: Path) -> dict[str, Any]:
if name.endswith(f".dist-info/{required_name}"):
required[required_name] = name
if required["METADATA"] is not None:
- metadata = _metadata_dict(archive.read(required["METADATA"]).decode("utf-8", errors="replace"))
+ metadata = _metadata_dict(
+ archive.read(required["METADATA"]).decode("utf-8", errors="replace")
+ )
missing = sorted(name for name, member in required.items() if member is None)
return {
"ok": not missing,
@@ -90,14 +102,21 @@ def parse_sdist(path: Path) -> dict[str, Any]:
metadata: dict[str, str] = {}
pkg_info_name = None
if not path.exists():
- return {"ok": False, "path": str(path), "missing": ["PKG-INFO"], "metadata": metadata}
+ return {
+ "ok": False,
+ "path": str(path),
+ "missing": ["PKG-INFO"],
+ "metadata": metadata,
+ }
with tarfile.open(path, "r:gz") as archive:
for member in archive.getmembers():
if member.name.endswith("PKG-INFO"):
pkg_info_name = member.name
fh = archive.extractfile(member)
if fh is not None:
- metadata = _metadata_dict(fh.read().decode("utf-8", errors="replace"))
+ metadata = _metadata_dict(
+ fh.read().decode("utf-8", errors="replace")
+ )
break
return {
"ok": pkg_info_name is not None,
@@ -161,8 +180,15 @@ def _source_commit(repo_root: Path) -> str:
return completed.stdout.strip() or "unknown"
-def _check(name: str, category: str, ok: bool, detail: str, **metadata: Any) -> dict[str, Any]:
- payload: dict[str, Any] = {"name": name, "category": category, "ok": ok, "detail": detail}
+def _check(
+ name: str, category: str, ok: bool, detail: str, **metadata: Any
+) -> dict[str, Any]:
+ payload: dict[str, Any] = {
+ "name": name,
+ "category": category,
+ "ok": ok,
+ "detail": detail,
+ }
payload.update(metadata)
return payload
@@ -181,13 +207,30 @@ def _policy_checks(repo_root: Path) -> list[dict[str, Any]]:
)
)
workflow = repo_root / ".github" / "workflows" / "ci.yml"
- checks.append(_check("workflow:ci", "github", workflow.exists(), "CI workflow file exists", path=str(workflow)))
+ checks.append(
+ _check(
+ "workflow:ci",
+ "github",
+ workflow.exists(),
+ "CI workflow file exists",
+ path=str(workflow),
+ )
+ )
return checks
-def _commercial_checks(path: Path, *, contract_value_krw: int) -> tuple[dict[str, Any], list[dict[str, Any]]]:
+def _commercial_checks(
+ path: Path, *, contract_value_krw: int
+) -> tuple[dict[str, Any], list[dict[str, Any]]]:
if not path.exists():
- return {}, [_check("commercial_release:manifest", "commercial_release", False, f"missing manifest: {path}")]
+ return {}, [
+ _check(
+ "commercial_release:manifest",
+ "commercial_release",
+ False,
+ f"missing manifest: {path}",
+ )
+ ]
payload = _read_json(path)
checks = [
_check(
@@ -210,7 +253,11 @@ def _commercial_checks(path: Path, *, contract_value_krw: int) -> tuple[dict[str
if isinstance(artifacts, dict):
for name in ["wheel", "sdist", "final_sales_readiness"]:
artifact = artifacts.get(name, {})
- ok = isinstance(artifact, dict) and artifact.get("exists") is True and isinstance(artifact.get("sha256"), str)
+ ok = (
+ isinstance(artifact, dict)
+ and artifact.get("exists") is True
+ and isinstance(artifact.get("sha256"), str)
+ )
checks.append(
_check(
f"commercial_release:artifact:{name}",
@@ -228,7 +275,14 @@ def _github_snapshot(repo: str, *, offline: bool) -> dict[str, Any]:
return {"mode": "offline", "repo": repo, "checks": {"snapshot_recorded": True}}
snapshot: dict[str, Any] = {"mode": "live", "repo": repo}
commands = {
- "repo": ["gh", "repo", "view", repo, "--json", "nameWithOwner,defaultBranchRef,visibility,isArchived,pushedAt,updatedAt,url"],
+ "repo": [
+ "gh",
+ "repo",
+ "view",
+ repo,
+ "--json",
+ "nameWithOwner,defaultBranchRef,visibility,isArchived,pushedAt,updatedAt,url",
+ ],
"open_prs": [
"gh",
"pr",
@@ -248,10 +302,16 @@ def _github_snapshot(repo: str, *, offline: bool) -> dict[str, Any]:
snapshot[name] = {
"ok": completed.returncode == 0,
"returncode": completed.returncode,
- "data": json.loads(completed.stdout) if completed.returncode == 0 and completed.stdout.strip() else None,
+ "data": json.loads(completed.stdout)
+ if completed.returncode == 0 and completed.stdout.strip()
+ else None,
"stderr": completed.stderr.strip(),
}
- release = subprocess.run(["gh", "release", "list", "--repo", repo, "--limit", "20"], capture_output=True, text=True)
+ release = subprocess.run(
+ ["gh", "release", "list", "--repo", repo, "--limit", "20"],
+ capture_output=True,
+ text=True,
+ )
snapshot["releases"] = {
"ok": release.returncode == 0,
"returncode": release.returncode,
@@ -263,20 +323,44 @@ def _github_snapshot(repo: str, *, offline: bool) -> dict[str, Any]:
def _github_checks(snapshot: dict[str, Any]) -> list[dict[str, Any]]:
if snapshot.get("mode") == "offline":
- return [_check("github:snapshot", "github", True, "GitHub snapshot intentionally recorded in offline mode")]
+ return [
+ _check(
+ "github:snapshot",
+ "github",
+ True,
+ "GitHub snapshot intentionally recorded in offline mode",
+ )
+ ]
repo_data = snapshot.get("repo", {})
repo_payload = repo_data.get("data", {}) if isinstance(repo_data, dict) else {}
checks = [
- _check("github:repo_snapshot", "github", bool(repo_data.get("ok")), "GitHub repository metadata was read"),
+ _check(
+ "github:repo_snapshot",
+ "github",
+ bool(repo_data.get("ok")),
+ "GitHub repository metadata was read",
+ ),
_check(
"github:not_archived",
"github",
isinstance(repo_payload, dict) and repo_payload.get("isArchived") is False,
"GitHub repository is not archived",
- actual=repo_payload.get("isArchived") if isinstance(repo_payload, dict) else None,
+ actual=repo_payload.get("isArchived")
+ if isinstance(repo_payload, dict)
+ else None,
+ ),
+ _check(
+ "github:open_pr_snapshot",
+ "github",
+ bool(snapshot.get("open_prs", {}).get("ok")),
+ "Open PR state was recorded",
+ ),
+ _check(
+ "github:release_snapshot",
+ "github",
+ bool(snapshot.get("releases", {}).get("ok")),
+ "Release list state was recorded",
),
- _check("github:open_pr_snapshot", "github", bool(snapshot.get("open_prs", {}).get("ok")), "Open PR state was recorded"),
- _check("github:release_snapshot", "github", bool(snapshot.get("releases", {}).get("ok")), "Release list state was recorded"),
]
return checks
@@ -346,7 +430,7 @@ def _render_report(manifest: dict[str, Any]) -> str:
continue
rows.append(
"
"
- f"| {escape(str(check.get('name', '')))} | "
+ f'{escape(str(check.get("name", "")))} | '
f"{escape(str(check.get('category', '')))} | "
f"{escape('go' if check.get('ok') else 'failed')} | "
f"{escape(str(check.get('detail', '')))} | "
@@ -354,14 +438,25 @@ def _render_report(manifest: dict[str, Any]) -> str:
)
cards = [
("Status", manifest.get("status", "")),
- ("Contract Value", f"KRW {manifest.get('contract_value_krw', ''):,}" if isinstance(manifest.get("contract_value_krw"), int) else ""),
+ (
+ "Contract Value",
+ f"KRW {manifest.get('contract_value_krw', ''):,}"
+ if isinstance(manifest.get("contract_value_krw"), int)
+ else "",
+ ),
("Project Version", manifest.get("project", {}).get("version", "")),
("Source Commit", manifest.get("source_commit", "")),
("Checks", len(checks) if isinstance(checks, list) else ""),
- ("Failed", len(manifest.get("failed_checks", [])) if isinstance(manifest.get("failed_checks"), list) else ""),
+ (
+ "Failed",
+ len(manifest.get("failed_checks", []))
+ if isinstance(manifest.get("failed_checks"), list)
+ else "",
+ ),
]
card_markup = [
- "" f"{escape(label)}{escape(str(value))}"
+ ''
+ f"{escape(label)}{escape(str(value))}"
for label, value in cards
]
return "\n".join(
@@ -386,7 +481,7 @@ def _render_report(manifest: dict[str, Any]) -> str:
'Due-Diligence Checks
',
'',
"
Procurement due diligence check table",
- "| Check | Category | Status | Detail |
",
+ '| Check | Category | Status | Detail |
',
*rows,
"
",
'This report records procurement evidence only. It is not a valuation guarantee or regulated-use approval.
',
@@ -398,24 +493,62 @@ def _render_report(manifest: dict[str, Any]) -> str:
def build_procurement_due_diligence(args: argparse.Namespace) -> dict[str, Any]:
repo_root = Path(args.repo_root).resolve()
dist_dir = _resolve_path(args.dist, base=repo_root).resolve()
- commercial_path = _resolve_path(args.commercial_release_manifest, base=repo_root).resolve()
+ commercial_path = _resolve_path(
+ args.commercial_release_manifest, base=repo_root
+ ).resolve()
out_dir = _resolve_path(args.out, base=repo_root).resolve()
out_dir.mkdir(parents=True, exist_ok=True)
project = _project_metadata(repo_root)
wheels = sorted(dist_dir.glob("*.whl"))
sdists = sorted(dist_dir.glob("*.tar.gz"))
- wheel = parse_wheel(wheels[0]) if wheels else {"ok": False, "missing": ["wheel"], "metadata": {}}
- sdist = parse_sdist(sdists[0]) if sdists else {"ok": False, "missing": ["sdist"], "metadata": {}}
- commercial, checks = _commercial_checks(commercial_path, contract_value_krw=args.contract_value_krw)
+ wheel = (
+ parse_wheel(wheels[0])
+ if wheels
+ else {"ok": False, "missing": ["wheel"], "metadata": {}}
+ )
+ sdist = (
+ parse_sdist(sdists[0])
+ if sdists
+ else {"ok": False, "missing": ["sdist"], "metadata": {}}
+ )
+ commercial, checks = _commercial_checks(
+ commercial_path, contract_value_krw=args.contract_value_krw
+ )
checks = [
- _check("dist:wheel", "package", bool(wheels), "wheel artifact exists", count=len(wheels)),
- _check("dist:sdist", "package", bool(sdists), "source distribution artifact exists", count=len(sdists)),
- _check("wheel:metadata", "package", bool(wheel.get("ok")), "wheel contains METADATA, WHEEL, and RECORD", missing=wheel.get("missing")),
- _check("sdist:metadata", "package", bool(sdist.get("ok")), "source distribution contains PKG-INFO", missing=sdist.get("missing")),
+ _check(
+ "dist:wheel",
+ "package",
+ bool(wheels),
+ "wheel artifact exists",
+ count=len(wheels),
+ ),
+ _check(
+ "dist:sdist",
+ "package",
+ bool(sdists),
+ "source distribution artifact exists",
+ count=len(sdists),
+ ),
+ _check(
+ "wheel:metadata",
+ "package",
+ bool(wheel.get("ok")),
+ "wheel contains METADATA, WHEEL, and RECORD",
+ missing=wheel.get("missing"),
+ ),
+ _check(
+ "sdist:metadata",
+ "package",
+ bool(sdist.get("ok")),
+ "source distribution contains PKG-INFO",
+ missing=sdist.get("missing"),
+ ),
_check(
"package:version",
"package",
- project.get("version") == wheel.get("metadata", {}).get("Version") == sdist.get("metadata", {}).get("Version"),
+ project.get("version")
+ == wheel.get("metadata", {}).get("Version")
+ == sdist.get("metadata", {}).get("Version"),
"pyproject, wheel, and source distribution versions match",
pyproject=project.get("version"),
wheel=wheel.get("metadata", {}).get("Version"),
@@ -447,23 +580,44 @@ def build_procurement_due_diligence(args: argparse.Namespace) -> dict[str, Any]:
html_path.write_text(_render_report(manifest), encoding="utf-8")
manifest["html_report_file"] = str(html_path)
manifest["html_report_sha256"] = _sha256(html_path)
- manifest_path.write_text(json.dumps(manifest, indent=2, sort_keys=True), encoding="utf-8")
+ manifest_path.write_text(
+ json.dumps(manifest, indent=2, sort_keys=True), encoding="utf-8"
+ )
return manifest
def build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(description="Build procurement due-diligence evidence for fast-mlsirm.")
+ parser = argparse.ArgumentParser(
+ description="Build procurement due-diligence evidence for fast-mlsirm."
+ )
parser.add_argument("--repo-root", default=".", help="Repository root.")
- parser.add_argument("--dist", default="dist", help="Directory containing wheel and sdist artifacts.")
+ parser.add_argument(
+ "--dist", default="dist", help="Directory containing wheel and sdist artifacts."
+ )
parser.add_argument(
"--commercial-release-manifest",
default="commercial-release/commercial_release_manifest.json",
help="Path to commercial_release_manifest.json.",
)
- parser.add_argument("--out", default="procurement-due-diligence", help="Output directory.")
- parser.add_argument("--repo", default="ContextualWisdomLab/fast-mlsirm", help="GitHub repository name.")
- parser.add_argument("--contract-value-krw", type=int, default=2_000_000_000, help="Target contract value.")
- parser.add_argument("--offline-github", action="store_true", help="Record an offline GitHub snapshot instead of calling gh.")
+ parser.add_argument(
+ "--out", default="procurement-due-diligence", help="Output directory."
+ )
+ parser.add_argument(
+ "--repo",
+ default="ContextualWisdomLab/fast-mlsirm",
+ help="GitHub repository name.",
+ )
+ parser.add_argument(
+ "--contract-value-krw",
+ type=int,
+ default=2_000_000_000,
+ help="Target contract value.",
+ )
+ parser.add_argument(
+ "--offline-github",
+ action="store_true",
+ help="Record an offline GitHub snapshot instead of calling gh.",
+ )
return parser
@@ -480,7 +634,9 @@ def main(argv: list[str] | None = None) -> int:
{
"status": manifest["status"],
"out": str(Path(args.out).resolve()),
- "manifest": str(Path(args.out).resolve() / "procurement_due_diligence_manifest.json"),
+ "manifest": str(
+ Path(args.out).resolve() / "procurement_due_diligence_manifest.json"
+ ),
"html": manifest["html_report_file"],
"failed_checks": len(manifest["failed_checks"]),
},
diff --git a/scripts/build_release_evidence_index.py b/scripts/build_release_evidence_index.py
index cf1b1dcce..6547a2c4e 100644
--- a/scripts/build_release_evidence_index.py
+++ b/scripts/build_release_evidence_index.py
@@ -12,6 +12,11 @@
from pathlib import Path
from typing import Any
+try:
+ from scripts._bounded_json import read_json_object
+except ModuleNotFoundError:
+ from _bounded_json import read_json_object
+
REQUIRED_COVERAGE = {
"acceptance_summary",
@@ -27,11 +32,8 @@
def _read_json(path: Path) -> dict[str, Any]:
- with path.open(encoding="utf-8") as fh:
- payload = json.load(fh)
- if not isinstance(payload, dict):
- raise RuntimeError(f"JSON artifact must be an object: {path}")
- return payload
+ """Read one descriptor-safe bounded JSON object from disk."""
+ return read_json_object(path)
def _sha256(path: Path) -> str:
@@ -127,14 +129,16 @@ def _format_value(value: Any) -> str:
return str(value)
-def _render_rows(rows: list[dict[str, Any]], columns: list[tuple[str, str]]) -> list[str]:
+def _render_rows(
+ rows: list[dict[str, Any]], columns: list[tuple[str, str]]
+) -> list[str]:
rendered = []
for row in rows:
cells = []
for key, _label in columns:
value = escape(_format_value(row.get(key)))
if not cells:
- cells.append(f"{value} | ")
+ cells.append(f'{value} | ')
else:
cells.append(f"{value} | ")
rendered.append("" + "".join(cells) + "
")
@@ -148,7 +152,7 @@ def _render_report_html(index: dict[str, Any]) -> str:
for name, ok in sorted(coverage.items()):
coverage_rows.append(
""
- f"| {escape(name.replace('_', ' ').title())} | "
+ f'{escape(name.replace("_", " ").title())} | '
f"{escape(_format_value(ok))} | "
"
"
)
@@ -164,11 +168,26 @@ def _render_report_html(index: dict[str, Any]) -> str:
)
cards = [
("Status", index.get("status", "")),
- ("Contract Value", f"KRW {index.get('contract_value_krw', ''):,}" if isinstance(index.get("contract_value_krw"), int) else ""),
+ (
+ "Contract Value",
+ f"KRW {index.get('contract_value_krw', ''):,}"
+ if isinstance(index.get("contract_value_krw"), int)
+ else "",
+ ),
("Version", index.get("project_version", "")),
("Source Commit", index.get("source_commit", "")),
- ("Dist Artifacts", len(index.get("dist", {}).get("artifacts", [])) if isinstance(index.get("dist"), dict) else ""),
- ("Failed Checks", len(index.get("failures", [])) if isinstance(index.get("failures"), list) else ""),
+ (
+ "Dist Artifacts",
+ len(index.get("dist", {}).get("artifacts", []))
+ if isinstance(index.get("dist"), dict)
+ else "",
+ ),
+ (
+ "Failed Checks",
+ len(index.get("failures", []))
+ if isinstance(index.get("failures"), list)
+ else "",
+ ),
]
card_markup = [
"\n".join(
@@ -216,7 +235,7 @@ def _render_report_html(index: dict[str, Any]) -> str:
'',
"
",
"Required evidence coverage table",
- "| Evidence | Status |
",
+ '| Evidence | Status |
',
"",
*coverage_rows,
"",
@@ -228,7 +247,7 @@ def _render_report_html(index: dict[str, Any]) -> str:
'',
"
",
"Release artifact digest table",
- "| Role | Name | Bytes | SHA256 |
",
+ '| Role | Name | Bytes | SHA256 |
',
"",
*file_rows,
"",
@@ -417,9 +436,15 @@ def build_index(args: argparse.Namespace) -> dict[str, Any]:
benchmark = _read_json(benchmark_path)
buyer_packet = _read_json(buyer_packet_path)
- benchmark_html = _resolve_artifact_path(benchmark.get("html_report_file"), base=benchmark_path.parent)
- buyer_zip = _resolve_artifact_path(buyer_packet.get("zip_file"), base=buyer_packet_path.parent)
- buyer_html = _resolve_artifact_path(buyer_packet.get("report_file"), base=buyer_packet_path.parent)
+ benchmark_html = _resolve_artifact_path(
+ benchmark.get("html_report_file"), base=benchmark_path.parent
+ )
+ buyer_zip = _resolve_artifact_path(
+ buyer_packet.get("zip_file"), base=buyer_packet_path.parent
+ )
+ buyer_html = _resolve_artifact_path(
+ buyer_packet.get("report_file"), base=buyer_packet_path.parent
+ )
dist_artifacts = _dist_entries(dist_dir)
files: list[dict[str, Any]] = []
@@ -449,23 +474,46 @@ def build_index(args: argparse.Namespace) -> dict[str, Any]:
"acceptance_summary": acceptance_path.exists() and acceptance_path.is_file(),
"sales_readiness_manifest": sales_path.exists() and sales_path.is_file(),
"benchmark_report": benchmark_path.exists() and benchmark_path.is_file(),
- "benchmark_html_report": benchmark_html is not None and benchmark_html.exists() and benchmark_html.is_file(),
- "buyer_packet_manifest": buyer_packet_path.exists() and buyer_packet_path.is_file(),
- "buyer_packet_zip": buyer_zip is not None and buyer_zip.exists() and buyer_zip.is_file(),
- "buyer_packet_html_report": buyer_html is not None and buyer_html.exists() and buyer_html.is_file(),
+ "benchmark_html_report": benchmark_html is not None
+ and benchmark_html.exists()
+ and benchmark_html.is_file(),
+ "buyer_packet_manifest": buyer_packet_path.exists()
+ and buyer_packet_path.is_file(),
+ "buyer_packet_zip": buyer_zip is not None
+ and buyer_zip.exists()
+ and buyer_zip.is_file(),
+ "buyer_packet_html_report": buyer_html is not None
+ and buyer_html.exists()
+ and buyer_html.is_file(),
"wheel": any(entry.get("kind") == "wheel" for entry in dist_artifacts),
"sdist": any(entry.get("kind") == "sdist" for entry in dist_artifacts),
}
- benchmark_html_sha = _sha256(benchmark_html) if coverage["benchmark_html_report"] and benchmark_html is not None else None
+ benchmark_html_sha = (
+ _sha256(benchmark_html)
+ if coverage["benchmark_html_report"] and benchmark_html is not None
+ else None
+ )
if benchmark_html_sha != benchmark.get("html_report_sha256"):
failures.append("benchmark HTML SHA256 does not match benchmark_report.json")
- buyer_zip_sha = _sha256(buyer_zip) if coverage["buyer_packet_zip"] and buyer_zip is not None else None
+ buyer_zip_sha = (
+ _sha256(buyer_zip)
+ if coverage["buyer_packet_zip"] and buyer_zip is not None
+ else None
+ )
if buyer_zip_sha != buyer_packet.get("zip_sha256"):
- failures.append("buyer packet ZIP SHA256 does not match buyer_evidence_manifest.json")
- buyer_html_sha = _sha256(buyer_html) if coverage["buyer_packet_html_report"] and buyer_html is not None else None
+ failures.append(
+ "buyer packet ZIP SHA256 does not match buyer_evidence_manifest.json"
+ )
+ buyer_html_sha = (
+ _sha256(buyer_html)
+ if coverage["buyer_packet_html_report"] and buyer_html is not None
+ else None
+ )
if buyer_html_sha != buyer_packet.get("report_sha256"):
- failures.append("buyer packet HTML SHA256 does not match buyer_evidence_manifest.json")
+ failures.append(
+ "buyer packet HTML SHA256 does not match buyer_evidence_manifest.json"
+ )
if acceptance.get("status") != "ok":
failures.append("acceptance_summary.json status is not ok")
@@ -475,9 +523,13 @@ def build_index(args: argparse.Namespace) -> dict[str, Any]:
failures.append("benchmark_report.json status or budget is not ok")
if buyer_packet.get("status") != "ok":
failures.append("buyer_evidence_manifest.json status is not ok")
- missing_coverage = [name for name in sorted(REQUIRED_COVERAGE) if coverage.get(name) is not True]
+ missing_coverage = [
+ name for name in sorted(REQUIRED_COVERAGE) if coverage.get(name) is not True
+ ]
if missing_coverage:
- failures.append(f"missing required release evidence coverage: {missing_coverage}")
+ failures.append(
+ f"missing required release evidence coverage: {missing_coverage}"
+ )
index: dict[str, Any] = {
"command": "build_release_evidence_index",
@@ -490,20 +542,28 @@ def build_index(args: argparse.Namespace) -> dict[str, Any]:
"coverage": coverage,
"dist": {
"directory": str(dist_dir),
- "wheel_count": sum(1 for entry in dist_artifacts if entry.get("kind") == "wheel"),
- "sdist_count": sum(1 for entry in dist_artifacts if entry.get("kind") == "sdist"),
+ "wheel_count": sum(
+ 1 for entry in dist_artifacts if entry.get("kind") == "wheel"
+ ),
+ "sdist_count": sum(
+ 1 for entry in dist_artifacts if entry.get("kind") == "sdist"
+ ),
"artifacts": dist_artifacts,
},
"acceptance": {
"file": str(acceptance_path),
"status": acceptance.get("status"),
"total_duration_seconds": acceptance.get("total_duration_seconds"),
- "command_count": len([step for step in acceptance.get("steps", []) if isinstance(step, dict)]),
+ "command_count": len(
+ [step for step in acceptance.get("steps", []) if isinstance(step, dict)]
+ ),
},
"sales_readiness": {
"file": str(sales_path),
"status": sales.get("status"),
- "failed_check_count": len(sales.get("failed_checks", [])) if isinstance(sales.get("failed_checks"), list) else None,
+ "failed_check_count": len(sales.get("failed_checks", []))
+ if isinstance(sales.get("failed_checks"), list)
+ else None,
"require_20b_product": sales.get("require_20b_product"),
"require_buyer_packet": sales.get("require_buyer_packet"),
"require_benchmark_report": sales.get("require_benchmark_report"),
@@ -514,7 +574,9 @@ def build_index(args: argparse.Namespace) -> dict[str, Any]:
"budget_ok": benchmark.get("budget_ok"),
"runtime_budget_seconds": benchmark.get("runtime_budget_seconds"),
"total_duration_seconds": benchmark.get("total_duration_seconds"),
- "html_report_file": str(benchmark_html) if benchmark_html is not None else None,
+ "html_report_file": str(benchmark_html)
+ if benchmark_html is not None
+ else None,
"html_report_sha256": benchmark.get("html_report_sha256"),
},
"buyer_packet": {
@@ -526,11 +588,16 @@ def build_index(args: argparse.Namespace) -> dict[str, Any]:
"report_file": str(buyer_html) if buyer_html is not None else None,
"report_sha256": buyer_packet.get("report_sha256"),
},
- "files": sorted(files, key=lambda item: (str(item.get("role", "")), str(item.get("name", "")))),
+ "files": sorted(
+ files,
+ key=lambda item: (str(item.get("role", "")), str(item.get("name", ""))),
+ ),
"failures": sorted(set(failures)),
"html_report_file": str(html_path),
}
- index["status"] = "ok" if not index["failures"] and all(index["coverage"].values()) else "failed"
+ index["status"] = (
+ "ok" if not index["failures"] and all(index["coverage"].values()) else "failed"
+ )
html_path.write_text(_render_report_html(index), encoding="utf-8")
index["html_report_sha256"] = _sha256(html_path)
index_path.write_text(json.dumps(index, indent=2, sort_keys=True), encoding="utf-8")
@@ -538,15 +605,46 @@ def build_index(args: argparse.Namespace) -> dict[str, Any]:
def build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(description="Build a release evidence index for fast-mlsirm.")
- parser.add_argument("--repo-root", default=".", help="Repository root used to record source commit and version.")
- parser.add_argument("--acceptance", required=True, help="Path to acceptance_summary.json.")
- parser.add_argument("--sales-readiness", required=True, help="Path to sales_readiness_manifest.json.")
- parser.add_argument("--benchmark-report", required=True, help="Path to benchmark_report.json.")
- parser.add_argument("--buyer-packet-manifest", required=True, help="Path to buyer_evidence_manifest.json.")
- parser.add_argument("--dist", required=True, help="Directory containing release wheel and sdist artifacts.")
- parser.add_argument("--out", default="release-evidence-index", help="Output directory for release evidence index files.")
- parser.add_argument("--contract-value-krw", type=int, default=2_000_000_000, help="Target contract value.")
+ parser = argparse.ArgumentParser(
+ description="Build a release evidence index for fast-mlsirm."
+ )
+ parser.add_argument(
+ "--repo-root",
+ default=".",
+ help="Repository root used to record source commit and version.",
+ )
+ parser.add_argument(
+ "--acceptance", required=True, help="Path to acceptance_summary.json."
+ )
+ parser.add_argument(
+ "--sales-readiness",
+ required=True,
+ help="Path to sales_readiness_manifest.json.",
+ )
+ parser.add_argument(
+ "--benchmark-report", required=True, help="Path to benchmark_report.json."
+ )
+ parser.add_argument(
+ "--buyer-packet-manifest",
+ required=True,
+ help="Path to buyer_evidence_manifest.json.",
+ )
+ parser.add_argument(
+ "--dist",
+ required=True,
+ help="Directory containing release wheel and sdist artifacts.",
+ )
+ parser.add_argument(
+ "--out",
+ default="release-evidence-index",
+ help="Output directory for release evidence index files.",
+ )
+ parser.add_argument(
+ "--contract-value-krw",
+ type=int,
+ default=2_000_000_000,
+ help="Target contract value.",
+ )
return parser
diff --git a/scripts/sales_readiness.py b/scripts/sales_readiness.py
index a4ccff4eb..16103aa37 100644
--- a/scripts/sales_readiness.py
+++ b/scripts/sales_readiness.py
@@ -16,6 +16,11 @@
from pathlib import Path
from typing import Any
+try:
+ from scripts._bounded_json import read_json_object
+except ModuleNotFoundError:
+ from _bounded_json import read_json_object
+
REQUIRED_POLICY_FILES = [
"README.md",
@@ -241,8 +246,8 @@ def _read_text(path: Path) -> str:
def _read_json(path: Path) -> dict[str, Any]:
- with path.open(encoding="utf-8") as fh:
- return json.load(fh)
+ """Read one descriptor-safe bounded JSON object from disk."""
+ return read_json_object(path)
def _sha256(path: Path) -> str:
@@ -284,7 +289,9 @@ def _validate_required_files(repo_root: Path) -> list[dict[str, object]]:
for relative in REQUIRED_POLICY_FILES:
path = repo_root / relative
ok = path.exists() and path.is_file() and path.stat().st_size > 0
- checks.append(_check(f"file:{relative}", ok, "required product evidence file exists"))
+ checks.append(
+ _check(f"file:{relative}", ok, "required product evidence file exists")
+ )
return checks
@@ -308,17 +315,25 @@ def _validate_doc_tokens(repo_root: Path) -> list[dict[str, object]]:
return checks
-def _validate_20b_product_evidence(repo_root: Path, *, contract_value_krw: int) -> list[dict[str, object]]:
+def _validate_20b_product_evidence(
+ repo_root: Path, *, contract_value_krw: int
+) -> list[dict[str, object]]:
checks: list[dict[str, object]] = []
for relative in REQUIRED_20B_PRODUCT_FILES:
path = repo_root / relative
ok = path.exists() and path.is_file() and path.stat().st_size > 0
- checks.append(_check(f"20b:file:{relative}", ok, "required 20B product evidence file exists"))
+ checks.append(
+ _check(
+ f"20b:file:{relative}", ok, "required 20B product evidence file exists"
+ )
+ )
for relative, tokens in REQUIRED_20B_DOC_TOKENS.items():
path = repo_root / relative
if not path.exists():
- checks.append(_check(f"20b:doc_tokens:{relative}", False, "document missing"))
+ checks.append(
+ _check(f"20b:doc_tokens:{relative}", False, "document missing")
+ )
continue
text = _read_text(path)
missing = [token for token in tokens if token not in text]
@@ -338,16 +353,19 @@ def _validate_20b_product_evidence(repo_root: Path, *, contract_value_krw: int)
continue
try:
payload = _read_json(path)
- except Exception as exc:
- checks.append(_check(f"20b:json:{relative}", False, f"manifest is not valid JSON: {exc}"))
- continue
- if not isinstance(payload, dict):
+ except RuntimeError:
checks.append(
_check(
f"20b:json_shape:{relative}",
False,
"manifest must be a JSON object",
- actual_type=type(payload).__name__,
+ )
+ )
+ continue
+ except Exception as exc:
+ checks.append(
+ _check(
+ f"20b:json:{relative}", False, f"manifest is not valid JSON: {exc}"
)
)
continue
@@ -356,7 +374,12 @@ def _validate_20b_product_evidence(repo_root: Path, *, contract_value_krw: int)
field
for field in fields
if field in payload
- and (payload[field] is None or (isinstance(payload[field], (list, dict, str)) and not payload[field]))
+ and (
+ payload[field] is None
+ or (
+ isinstance(payload[field], (list, dict, str)) and not payload[field]
+ )
+ )
]
checks.append(
_check(
@@ -392,7 +415,8 @@ def _validate_20b_product_evidence(repo_root: Path, *, contract_value_krw: int)
checks.append(
_check(
"20b:figma_artifact_url",
- isinstance(figma_url, str) and figma_url.startswith("https://www.figma.com/design/"),
+ isinstance(figma_url, str)
+ and figma_url.startswith("https://www.figma.com/design/"),
(
"optional Figma artifact URL must start with https://www.figma.com/design/; "
"FigJam /board/ URLs do not satisfy the design-file evidence contract"
@@ -443,10 +467,22 @@ def _validate_acceptance_summary(
) -> list[dict[str, object]]:
checks: list[dict[str, object]] = []
if not acceptance_path.exists():
- return [_check("acceptance:summary", False, f"missing acceptance summary: {acceptance_path}")]
+ return [
+ _check(
+ "acceptance:summary",
+ False,
+ f"missing acceptance summary: {acceptance_path}",
+ )
+ ]
summary = _read_json(acceptance_path)
- checks.append(_check("acceptance:status", summary.get("status") == "ok", "acceptance summary status is ok"))
+ checks.append(
+ _check(
+ "acceptance:status",
+ summary.get("status") == "ok",
+ "acceptance summary status is ok",
+ )
+ )
steps = summary.get("steps", [])
commands = {step.get("command") for step in steps if isinstance(step, dict)}
@@ -460,11 +496,16 @@ def _validate_acceptance_summary(
)
)
- fit_backends = [step.get("backend") for step in steps if isinstance(step, dict) and step.get("command") == "fit"]
+ fit_backends = [
+ step.get("backend")
+ for step in steps
+ if isinstance(step, dict) and step.get("command") == "fit"
+ ]
checks.append(
_check(
"acceptance:fit_backend_record",
- all(backend in {"numpy", "rust"} for backend in fit_backends) and bool(fit_backends),
+ all(backend in {"numpy", "rust"} for backend in fit_backends)
+ and bool(fit_backends),
"fit steps record resolved backend",
backends=fit_backends,
)
@@ -530,12 +571,24 @@ def _validate_acceptance_summary(
def _validate_dist(dist_dir: Path | None) -> list[dict[str, object]]:
if dist_dir is None:
- return [_check("dist:skipped", True, "distribution artifact check not requested")]
+ return [
+ _check("dist:skipped", True, "distribution artifact check not requested")
+ ]
wheels = sorted(dist_dir.glob("*.whl"))
sdists = sorted(dist_dir.glob("*.tar.gz"))
return [
- _check("dist:wheel", bool(wheels), "wheel artifact exists", files=[str(path) for path in wheels]),
- _check("dist:sdist", bool(sdists), "source distribution artifact exists", files=[str(path) for path in sdists]),
+ _check(
+ "dist:wheel",
+ bool(wheels),
+ "wheel artifact exists",
+ files=[str(path) for path in wheels],
+ ),
+ _check(
+ "dist:sdist",
+ bool(sdists),
+ "source distribution artifact exists",
+ files=[str(path) for path in sdists],
+ ),
]
@@ -554,13 +607,31 @@ def _validate_buyer_packet(
)
]
if not manifest_path.exists():
- return [_check("buyer_packet:manifest", False, f"missing buyer packet manifest: {manifest_path}")]
+ return [
+ _check(
+ "buyer_packet:manifest",
+ False,
+ f"missing buyer packet manifest: {manifest_path}",
+ )
+ ]
try:
payload = _read_json(manifest_path)
except Exception as exc:
- return [_check("buyer_packet:manifest", False, f"buyer packet manifest is not valid JSON: {exc}")]
+ return [
+ _check(
+ "buyer_packet:manifest",
+ False,
+ f"buyer packet manifest is not valid JSON: {exc}",
+ )
+ ]
if not isinstance(payload, dict):
- return [_check("buyer_packet:manifest_shape", False, "buyer packet manifest must be a JSON object")]
+ return [
+ _check(
+ "buyer_packet:manifest_shape",
+ False,
+ "buyer packet manifest must be a JSON object",
+ )
+ ]
coverage = payload.get("coverage", {})
coverage_missing = [
@@ -576,10 +647,14 @@ def _validate_buyer_packet(
expected_zip_sha = payload.get("zip_sha256")
actual_zip_sha = _sha256(zip_path) if zip_exists else None
report_file = payload.get("report_file")
- report_path = Path(str(report_file)) if isinstance(report_file, str) and report_file else None
+ report_path = (
+ Path(str(report_file)) if isinstance(report_file, str) and report_file else None
+ )
if report_path is not None and not report_path.is_absolute():
report_path = manifest_path.parent / report_path
- report_exists = report_path is not None and report_path.exists() and report_path.is_file()
+ report_exists = (
+ report_path is not None and report_path.exists() and report_path.is_file()
+ )
expected_report_sha = payload.get("report_sha256")
actual_report_sha = _sha256(report_path) if report_exists else None
return [
@@ -598,7 +673,8 @@ def _validate_buyer_packet(
),
_check(
"buyer_packet:artifact_count",
- isinstance(payload.get("artifact_count"), int) and payload["artifact_count"] > 0,
+ isinstance(payload.get("artifact_count"), int)
+ and payload["artifact_count"] > 0,
"buyer packet records included artifact count",
actual=payload.get("artifact_count"),
),
@@ -616,7 +692,9 @@ def _validate_buyer_packet(
),
_check(
"buyer_packet:zip_sha256",
- zip_exists and isinstance(expected_zip_sha, str) and expected_zip_sha == actual_zip_sha,
+ zip_exists
+ and isinstance(expected_zip_sha, str)
+ and expected_zip_sha == actual_zip_sha,
"buyer packet zip SHA256 matches manifest",
expected=expected_zip_sha,
actual=actual_zip_sha,
@@ -629,7 +707,9 @@ def _validate_buyer_packet(
),
_check(
"buyer_packet:html_report_sha256",
- report_exists and isinstance(expected_report_sha, str) and expected_report_sha == actual_report_sha,
+ report_exists
+ and isinstance(expected_report_sha, str)
+ and expected_report_sha == actual_report_sha,
"buyer evidence HTML report SHA256 matches manifest",
expected=expected_report_sha,
actual=actual_report_sha,
@@ -651,21 +731,47 @@ def _validate_benchmark_report(
)
]
if not manifest_path.exists():
- return [_check("benchmark_report:manifest", False, f"missing benchmark report: {manifest_path}")]
+ return [
+ _check(
+ "benchmark_report:manifest",
+ False,
+ f"missing benchmark report: {manifest_path}",
+ )
+ ]
try:
payload = _read_json(manifest_path)
except Exception as exc:
- return [_check("benchmark_report:manifest", False, f"benchmark report is not valid JSON: {exc}")]
+ return [
+ _check(
+ "benchmark_report:manifest",
+ False,
+ f"benchmark report is not valid JSON: {exc}",
+ )
+ ]
if not isinstance(payload, dict):
- return [_check("benchmark_report:manifest_shape", False, "benchmark report must be a JSON object")]
+ return [
+ _check(
+ "benchmark_report:manifest_shape",
+ False,
+ "benchmark report must be a JSON object",
+ )
+ ]
scenario = payload.get("scenario_coverage", {})
- missing_backends = scenario.get("missing_backends") if isinstance(scenario, dict) else None
+ missing_backends = (
+ scenario.get("missing_backends") if isinstance(scenario, dict) else None
+ )
artifacts = payload.get("artifact_coverage", {})
- missing_artifacts = artifacts.get("missing") if isinstance(artifacts, dict) else None
- missing_paths = artifacts.get("missing_paths") if isinstance(artifacts, dict) else None
+ missing_artifacts = (
+ artifacts.get("missing") if isinstance(artifacts, dict) else None
+ )
+ missing_paths = (
+ artifacts.get("missing_paths") if isinstance(artifacts, dict) else None
+ )
html_file = payload.get("html_report_file")
- html_path = Path(str(html_file)) if isinstance(html_file, str) and html_file else None
+ html_path = (
+ Path(str(html_file)) if isinstance(html_file, str) and html_file else None
+ )
if html_path is not None and not html_path.is_absolute():
html_path = manifest_path.parent / html_path
html_exists = html_path is not None and html_path.exists() and html_path.is_file()
@@ -706,7 +812,9 @@ def _validate_benchmark_report(
),
_check(
"benchmark_report:html_report_sha256",
- html_exists and isinstance(expected_html_sha, str) and expected_html_sha == actual_html_sha,
+ html_exists
+ and isinstance(expected_html_sha, str)
+ and expected_html_sha == actual_html_sha,
"benchmark HTML report SHA256 matches manifest",
expected=expected_html_sha,
actual=actual_html_sha,
@@ -729,13 +837,31 @@ def _validate_release_evidence_index(
)
]
if not manifest_path.exists():
- return [_check("release_evidence_index:manifest", False, f"missing release evidence index: {manifest_path}")]
+ return [
+ _check(
+ "release_evidence_index:manifest",
+ False,
+ f"missing release evidence index: {manifest_path}",
+ )
+ ]
try:
payload = _read_json(manifest_path)
except Exception as exc:
- return [_check("release_evidence_index:manifest", False, f"release evidence index is not valid JSON: {exc}")]
+ return [
+ _check(
+ "release_evidence_index:manifest",
+ False,
+ f"release evidence index is not valid JSON: {exc}",
+ )
+ ]
if not isinstance(payload, dict):
- return [_check("release_evidence_index:manifest_shape", False, "release evidence index must be a JSON object")]
+ return [
+ _check(
+ "release_evidence_index:manifest_shape",
+ False,
+ "release evidence index must be a JSON object",
+ )
+ ]
coverage = payload.get("coverage", {})
coverage_missing = [
@@ -747,8 +873,14 @@ def _validate_release_evidence_index(
artifacts = dist.get("artifacts") if isinstance(dist, dict) else None
dist_artifacts_ok = (
isinstance(artifacts, list)
- and any(isinstance(entry, dict) and entry.get("kind") == "wheel" for entry in artifacts)
- and any(isinstance(entry, dict) and entry.get("kind") == "sdist" for entry in artifacts)
+ and any(
+ isinstance(entry, dict) and entry.get("kind") == "wheel"
+ for entry in artifacts
+ )
+ and any(
+ isinstance(entry, dict) and entry.get("kind") == "sdist"
+ for entry in artifacts
+ )
and all(
isinstance(entry, dict)
and isinstance(entry.get("sha256"), str)
@@ -759,7 +891,9 @@ def _validate_release_evidence_index(
)
)
html_file = payload.get("html_report_file")
- html_path = Path(str(html_file)) if isinstance(html_file, str) and html_file else None
+ html_path = (
+ Path(str(html_file)) if isinstance(html_file, str) and html_file else None
+ )
if html_path is not None and not html_path.is_absolute():
html_path = manifest_path.parent / html_path
html_exists = html_path is not None and html_path.exists() and html_path.is_file()
@@ -806,7 +940,9 @@ def _validate_release_evidence_index(
),
_check(
"release_evidence_index:html_report_sha256",
- html_exists and isinstance(expected_html_sha, str) and expected_html_sha == actual_html_sha,
+ html_exists
+ and isinstance(expected_html_sha, str)
+ and expected_html_sha == actual_html_sha,
"release evidence HTML report SHA256 matches manifest",
expected=expected_html_sha,
actual=actual_html_sha,
@@ -859,11 +995,15 @@ def _validate_procurement_due_diligence(
ok_categories = {
check.get("category")
for check in checks
- if isinstance(check, dict) and check.get("ok") is True and isinstance(check.get("category"), str)
+ if isinstance(check, dict)
+ and check.get("ok") is True
+ and isinstance(check.get("category"), str)
}
failed_checks = payload.get("failed_checks")
html_file = payload.get("html_report_file")
- html_path = Path(str(html_file)) if isinstance(html_file, str) and html_file else None
+ html_path = (
+ Path(str(html_file)) if isinstance(html_file, str) and html_file else None
+ )
if html_path is not None and not html_path.is_absolute():
html_path = manifest_path.parent / html_path
html_exists = html_path is not None and html_path.exists() and html_path.is_file()
@@ -893,7 +1033,9 @@ def _validate_procurement_due_diligence(
"procurement_due_diligence:category_coverage",
REQUIRED_PROCUREMENT_DUE_DILIGENCE_CATEGORIES.issubset(ok_categories),
"procurement due-diligence covers package, policy, commercial release, and GitHub evidence",
- missing=sorted(REQUIRED_PROCUREMENT_DUE_DILIGENCE_CATEGORIES - ok_categories),
+ missing=sorted(
+ REQUIRED_PROCUREMENT_DUE_DILIGENCE_CATEGORIES - ok_categories
+ ),
),
_check(
"procurement_due_diligence:html_report",
@@ -903,7 +1045,9 @@ def _validate_procurement_due_diligence(
),
_check(
"procurement_due_diligence:html_report_sha256",
- html_exists and isinstance(expected_html_sha, str) and expected_html_sha == actual_html_sha,
+ html_exists
+ and isinstance(expected_html_sha, str)
+ and expected_html_sha == actual_html_sha,
"procurement due-diligence HTML report SHA256 matches manifest",
expected=expected_html_sha,
actual=actual_html_sha,
@@ -956,13 +1100,22 @@ def _validate_pr_queue_governance(
ok_categories = {
check.get("category")
for check in checks
- if isinstance(check, dict) and check.get("ok") is True and isinstance(check.get("category"), str)
+ if isinstance(check, dict)
+ and check.get("ok") is True
+ and isinstance(check.get("category"), str)
}
failed_checks = payload.get("failed_checks")
risk_counts = payload.get("risk_counts")
- required_risk_keys = {"changes_requested", "stale", "release_scope_conflict", "review_or_check_delay"}
+ required_risk_keys = {
+ "changes_requested",
+ "stale",
+ "release_scope_conflict",
+ "review_or_check_delay",
+ }
html_file = payload.get("html_report_file")
- html_path = Path(str(html_file)) if isinstance(html_file, str) and html_file else None
+ html_path = (
+ Path(str(html_file)) if isinstance(html_file, str) and html_file else None
+ )
if html_path is not None and not html_path.is_absolute():
html_path = manifest_path.parent / html_path
html_exists = html_path is not None and html_path.exists() and html_path.is_file()
@@ -996,7 +1149,8 @@ def _validate_pr_queue_governance(
),
_check(
"pr_queue_governance:open_pr_count",
- isinstance(payload.get("open_pr_count"), int) and payload["open_pr_count"] >= 0,
+ isinstance(payload.get("open_pr_count"), int)
+ and payload["open_pr_count"] >= 0,
"PR queue governance records open PR count",
actual=payload.get("open_pr_count"),
),
@@ -1004,7 +1158,10 @@ def _validate_pr_queue_governance(
"pr_queue_governance:risk_counts",
isinstance(risk_counts, dict) and required_risk_keys.issubset(risk_counts),
"PR queue governance records required risk count buckets",
- missing=sorted(required_risk_keys - set(risk_counts if isinstance(risk_counts, dict) else [])),
+ missing=sorted(
+ required_risk_keys
+ - set(risk_counts if isinstance(risk_counts, dict) else [])
+ ),
),
_check(
"pr_queue_governance:html_report",
@@ -1014,7 +1171,9 @@ def _validate_pr_queue_governance(
),
_check(
"pr_queue_governance:html_report_sha256",
- html_exists and isinstance(expected_html_sha, str) and expected_html_sha == actual_html_sha,
+ html_exists
+ and isinstance(expected_html_sha, str)
+ and expected_html_sha == actual_html_sha,
"PR queue governance HTML report SHA256 matches manifest",
expected=expected_html_sha,
actual=actual_html_sha,
@@ -1037,27 +1196,53 @@ def _validate_figma_evidence_sync(
)
]
if not manifest_path.exists():
- return [_check("figma_evidence_sync:manifest", False, f"missing Figma evidence sync manifest: {manifest_path}")]
+ return [
+ _check(
+ "figma_evidence_sync:manifest",
+ False,
+ f"missing Figma evidence sync manifest: {manifest_path}",
+ )
+ ]
try:
payload = _read_json(manifest_path)
except Exception as exc:
- return [_check("figma_evidence_sync:manifest", False, f"Figma evidence sync manifest is not valid JSON: {exc}")]
+ return [
+ _check(
+ "figma_evidence_sync:manifest",
+ False,
+ f"Figma evidence sync manifest is not valid JSON: {exc}",
+ )
+ ]
if not isinstance(payload, dict):
- return [_check("figma_evidence_sync:manifest_shape", False, "Figma evidence sync manifest must be a JSON object")]
+ return [
+ _check(
+ "figma_evidence_sync:manifest_shape",
+ False,
+ "Figma evidence sync manifest must be a JSON object",
+ )
+ ]
checks = payload.get("checks", [])
ok_categories = {
check.get("category")
for check in checks
- if isinstance(check, dict) and check.get("ok") is True and isinstance(check.get("category"), str)
+ if isinstance(check, dict)
+ and check.get("ok") is True
+ and isinstance(check.get("category"), str)
}
failed_checks = payload.get("failed_checks")
frame_coverage = payload.get("frame_coverage", {})
- frame_missing = frame_coverage.get("missing") if isinstance(frame_coverage, dict) else None
+ frame_missing = (
+ frame_coverage.get("missing") if isinstance(frame_coverage, dict) else None
+ )
token_coverage = payload.get("required_token_coverage", {})
- token_missing = token_coverage.get("missing") if isinstance(token_coverage, dict) else None
+ token_missing = (
+ token_coverage.get("missing") if isinstance(token_coverage, dict) else None
+ )
html_file = payload.get("html_report_file")
- html_path = Path(str(html_file)) if isinstance(html_file, str) and html_file else None
+ html_path = (
+ Path(str(html_file)) if isinstance(html_file, str) and html_file else None
+ )
if html_path is not None and not html_path.is_absolute():
html_path = manifest_path.parent / html_path
html_exists = html_path is not None and html_path.exists() and html_path.is_file()
@@ -1115,7 +1300,9 @@ def _validate_figma_evidence_sync(
),
_check(
"figma_evidence_sync:html_report_sha256",
- html_exists and isinstance(expected_html_sha, str) and expected_html_sha == actual_html_sha,
+ html_exists
+ and isinstance(expected_html_sha, str)
+ and expected_html_sha == actual_html_sha,
"Figma evidence sync HTML report SHA256 matches manifest",
expected=expected_html_sha,
actual=actual_html_sha,
@@ -1123,13 +1310,19 @@ def _validate_figma_evidence_sync(
]
-def _validate_imports(repo_root: Path, *, require_rust: bool) -> list[dict[str, object]]:
+def _validate_imports(
+ repo_root: Path, *, require_rust: bool
+) -> list[dict[str, object]]:
project_version = _project_version(repo_root)
checks: list[dict[str, object]] = []
try:
package = importlib.import_module("fast_mlsirm")
- except Exception as exc: # pragma: no cover - exception detail is surfaced in manifest.
- return [_check("import:fast_mlsirm", False, f"failed to import fast_mlsirm: {exc}")]
+ except (
+ Exception
+ ) as exc: # pragma: no cover - exception detail is surfaced in manifest.
+ return [
+ _check("import:fast_mlsirm", False, f"failed to import fast_mlsirm: {exc}")
+ ]
imported_version = getattr(package, "__version__", "")
checks.append(
@@ -1145,8 +1338,16 @@ def _validate_imports(repo_root: Path, *, require_rust: bool) -> list[dict[str,
if require_rust:
try:
core = importlib.import_module("fast_mlsirm._core")
- except Exception as exc: # pragma: no cover - exception detail is surfaced in manifest.
- checks.append(_check("import:rust_core", False, f"failed to import fast_mlsirm._core: {exc}"))
+ except (
+ Exception
+ ) as exc: # pragma: no cover - exception detail is surfaced in manifest.
+ checks.append(
+ _check(
+ "import:rust_core",
+ False,
+ f"failed to import fast_mlsirm._core: {exc}",
+ )
+ )
else:
checks.append(
_check(
@@ -1165,9 +1366,13 @@ def run_sales_readiness(args: argparse.Namespace) -> dict[str, object]:
benchmark_report = getattr(args, "benchmark_report", None)
require_benchmark_report = getattr(args, "require_benchmark_report", False)
release_evidence_index = getattr(args, "release_evidence_index", None)
- require_release_evidence_index = getattr(args, "require_release_evidence_index", False)
+ require_release_evidence_index = getattr(
+ args, "require_release_evidence_index", False
+ )
procurement_due_diligence = getattr(args, "procurement_due_diligence", None)
- require_procurement_due_diligence = getattr(args, "require_procurement_due_diligence", False)
+ require_procurement_due_diligence = getattr(
+ args, "require_procurement_due_diligence", False
+ )
pr_queue_governance = getattr(args, "pr_queue_governance", None)
require_pr_queue_governance = getattr(args, "require_pr_queue_governance", False)
figma_evidence_sync = getattr(args, "figma_evidence_sync", None)
@@ -1176,7 +1381,11 @@ def run_sales_readiness(args: argparse.Namespace) -> dict[str, object]:
checks.extend(_validate_required_files(repo_root))
checks.extend(_validate_doc_tokens(repo_root))
if args.require_20b_product:
- checks.extend(_validate_20b_product_evidence(repo_root, contract_value_krw=args.contract_value_krw))
+ checks.extend(
+ _validate_20b_product_evidence(
+ repo_root, contract_value_krw=args.contract_value_krw
+ )
+ )
checks.extend(
_validate_acceptance_summary(
Path(args.acceptance).resolve(),
@@ -1188,7 +1397,9 @@ def run_sales_readiness(args: argparse.Namespace) -> dict[str, object]:
if buyer_packet_manifest or require_buyer_packet:
checks.extend(
_validate_buyer_packet(
- Path(buyer_packet_manifest).resolve() if buyer_packet_manifest else None,
+ Path(buyer_packet_manifest).resolve()
+ if buyer_packet_manifest
+ else None,
required=require_buyer_packet,
contract_value_krw=args.contract_value_krw,
)
@@ -1203,7 +1414,9 @@ def run_sales_readiness(args: argparse.Namespace) -> dict[str, object]:
if release_evidence_index or require_release_evidence_index:
checks.extend(
_validate_release_evidence_index(
- Path(release_evidence_index).resolve() if release_evidence_index else None,
+ Path(release_evidence_index).resolve()
+ if release_evidence_index
+ else None,
required=require_release_evidence_index,
contract_value_krw=args.contract_value_krw,
)
@@ -1211,7 +1424,9 @@ def run_sales_readiness(args: argparse.Namespace) -> dict[str, object]:
if procurement_due_diligence or require_procurement_due_diligence:
checks.extend(
_validate_procurement_due_diligence(
- Path(procurement_due_diligence).resolve() if procurement_due_diligence else None,
+ Path(procurement_due_diligence).resolve()
+ if procurement_due_diligence
+ else None,
required=require_procurement_due_diligence,
contract_value_krw=args.contract_value_krw,
)
@@ -1255,60 +1470,105 @@ def run_sales_readiness(args: argparse.Namespace) -> dict[str, object]:
out_path = Path(args.out).resolve()
out_path.parent.mkdir(parents=True, exist_ok=True)
- out_path.write_text(json.dumps(manifest, indent=2, sort_keys=True), encoding="utf-8")
+ out_path.write_text(
+ json.dumps(manifest, indent=2, sort_keys=True), encoding="utf-8"
+ )
return manifest
def build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(description="Verify enterprise sales-readiness evidence.")
- parser.add_argument("--repo-root", default=".", help="Repository root containing product evidence files.")
- parser.add_argument("--acceptance", required=True, help="Path to release acceptance_summary.json.")
- parser.add_argument("--out", default="sales_readiness_manifest.json", help="Manifest output path.")
- parser.add_argument("--dist", help="Optional dist directory containing built wheel and sdist artifacts.")
- parser.add_argument("--require-rust", action="store_true", help="Require explicit Rust backend evidence.")
+ parser = argparse.ArgumentParser(
+ description="Verify enterprise sales-readiness evidence."
+ )
+ parser.add_argument(
+ "--repo-root",
+ default=".",
+ help="Repository root containing product evidence files.",
+ )
+ parser.add_argument(
+ "--acceptance", required=True, help="Path to release acceptance_summary.json."
+ )
+ parser.add_argument(
+ "--out", default="sales_readiness_manifest.json", help="Manifest output path."
+ )
+ parser.add_argument(
+ "--dist",
+ help="Optional dist directory containing built wheel and sdist artifacts.",
+ )
+ parser.add_argument(
+ "--require-rust",
+ action="store_true",
+ help="Require explicit Rust backend evidence.",
+ )
parser.add_argument(
"--require-20b-product",
action="store_true",
help="Require Product Design, Figma, ROI, benchmark, and demo evidence for KRW 2B review.",
)
- parser.add_argument("--check-import", action="store_true", help="Import installed package and optional Rust core.")
- parser.add_argument("--buyer-packet-manifest", help="Optional buyer_evidence_manifest.json to validate.")
+ parser.add_argument(
+ "--check-import",
+ action="store_true",
+ help="Import installed package and optional Rust core.",
+ )
+ parser.add_argument(
+ "--buyer-packet-manifest",
+ help="Optional buyer_evidence_manifest.json to validate.",
+ )
parser.add_argument(
"--require-buyer-packet",
action="store_true",
help="Fail unless --buyer-packet-manifest points to a complete buyer evidence packet.",
)
- parser.add_argument("--benchmark-report", help="Optional benchmark_report.json to validate.")
+ parser.add_argument(
+ "--benchmark-report", help="Optional benchmark_report.json to validate."
+ )
parser.add_argument(
"--require-benchmark-report",
action="store_true",
help="Fail unless --benchmark-report points to a complete automated benchmark report.",
)
- parser.add_argument("--release-evidence-index", help="Optional release_evidence_index.json to validate.")
+ parser.add_argument(
+ "--release-evidence-index",
+ help="Optional release_evidence_index.json to validate.",
+ )
parser.add_argument(
"--require-release-evidence-index",
action="store_true",
help="Fail unless --release-evidence-index points to a complete release evidence index.",
)
- parser.add_argument("--procurement-due-diligence", help="Optional procurement_due_diligence_manifest.json to validate.")
+ parser.add_argument(
+ "--procurement-due-diligence",
+ help="Optional procurement_due_diligence_manifest.json to validate.",
+ )
parser.add_argument(
"--require-procurement-due-diligence",
action="store_true",
help="Fail unless --procurement-due-diligence points to complete procurement due-diligence evidence.",
)
- parser.add_argument("--pr-queue-governance", help="Optional pr_queue_governance_manifest.json to validate.")
+ parser.add_argument(
+ "--pr-queue-governance",
+ help="Optional pr_queue_governance_manifest.json to validate.",
+ )
parser.add_argument(
"--require-pr-queue-governance",
action="store_true",
help="Fail unless --pr-queue-governance points to complete PR queue governance evidence.",
)
- parser.add_argument("--figma-evidence-sync", help="Optional figma_evidence_sync_manifest.json to validate.")
+ parser.add_argument(
+ "--figma-evidence-sync",
+ help="Optional figma_evidence_sync_manifest.json to validate.",
+ )
parser.add_argument(
"--require-figma-evidence-sync",
action="store_true",
help="Fail unless --figma-evidence-sync points to complete Figma evidence sync evidence.",
)
- parser.add_argument("--contract-value-krw", type=int, default=2_000_000_000, help="Target contract value for this gate.")
+ parser.add_argument(
+ "--contract-value-krw",
+ type=int,
+ default=2_000_000_000,
+ help="Target contract value for this gate.",
+ )
parser.add_argument(
"--max-acceptance-seconds",
type=float,
@@ -1326,7 +1586,13 @@ def main(argv: list[str] | None = None) -> int:
except Exception as exc:
print(json.dumps({"status": "failed", "error": str(exc)}, ensure_ascii=False))
return 1
- print(json.dumps({"status": manifest["status"], "out": str(Path(args.out).resolve())}, indent=2, sort_keys=True))
+ print(
+ json.dumps(
+ {"status": manifest["status"], "out": str(Path(args.out).resolve())},
+ indent=2,
+ sort_keys=True,
+ )
+ )
return 0 if manifest["status"] == "ok" else 1
diff --git a/tests/test_bounded_json_scripts.py b/tests/test_bounded_json_scripts.py
new file mode 100644
index 000000000..85d96f56c
--- /dev/null
+++ b/tests/test_bounded_json_scripts.py
@@ -0,0 +1,241 @@
+"""Security, invariance, and delegation tests for bounded JSON readers."""
+
+from __future__ import annotations
+
+import importlib
+import json
+import os
+import sys
+from pathlib import Path
+
+import pytest
+
+_REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(_REPOSITORY_ROOT))
+_bounded_json = importlib.import_module("scripts._bounded_json")
+read_json_object = _bounded_json.read_json_object
+
+_SCRIPT_MODULES = (
+ "scripts.build_benchmark_report",
+ "scripts.build_buyer_packet",
+ "scripts.build_commercial_release",
+ "scripts.build_figma_evidence_sync",
+ "scripts.build_pr_queue_governance",
+ "scripts.build_procurement_due_diligence",
+ "scripts.build_release_evidence_index",
+ "scripts.sales_readiness",
+)
+
+
+def _write(path: Path, content: bytes) -> Path:
+ """Write exact bytes and return ``path``."""
+ path.write_bytes(content)
+ return path
+
+
+def test_exact_size_depth_strings_escapes_and_unicode(tmp_path: Path) -> None:
+ """Exact limits accept valid objects without counting string delimiters."""
+ content = json.dumps(
+ {
+ "text": "[{}] \\ slash",
+ "escaped_quote": 'quote: " and delimiters: {[]}',
+ "nested": {"items": ["한글"]},
+ },
+ ensure_ascii=False,
+ ).encode("utf-8")
+ path = _write(tmp_path / "valid.json", content)
+ assert read_json_object(
+ path,
+ max_bytes=len(content),
+ max_depth=3,
+ ) == json.loads(content)
+
+
+def test_limit_plus_one_is_rejected(tmp_path: Path) -> None:
+ """One byte above the configured inclusive byte limit fails closed."""
+ path = _write(tmp_path / "oversized.json", b'{"a":1} ')
+ with pytest.raises(ValueError, match="maximum allowed size 7 bytes"):
+ read_json_object(path, max_bytes=7)
+
+
+def test_depth_boundary_and_excess(tmp_path: Path) -> None:
+ """The depth boundary is inclusive and the next level is rejected."""
+ boundary = _write(tmp_path / "boundary.json", b'{"a":{"b":0}}')
+ excessive = _write(tmp_path / "excessive.json", b'{"a":{"b":[]}}')
+ assert read_json_object(boundary, max_depth=2) == {"a": {"b": 0}}
+ with pytest.raises(ValueError, match="maximum allowed depth 2"):
+ read_json_object(excessive, max_depth=2)
+
+
+@pytest.mark.parametrize(
+ ("keyword", "value"),
+ (
+ ("max_bytes", 0),
+ ("max_bytes", True),
+ ("max_bytes", "7"),
+ ("max_depth", -1),
+ ("max_depth", True),
+ ("max_depth", 1.5),
+ ),
+)
+def test_limits_require_positive_non_boolean_integers(
+ tmp_path: Path,
+ keyword: str,
+ value: object,
+) -> None:
+ """Invalid limit configuration fails before JSON decoding."""
+ path = _write(tmp_path / "input.json", b"{}")
+ with pytest.raises(ValueError, match=f"{keyword} must be a positive integer"):
+ read_json_object(path, **{keyword: value})
+
+
+def test_invalid_utf8_malformed_json_and_decoder_recursion(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Encoding, syntax, and recursion failures remain deterministic."""
+ invalid_utf8 = _write(
+ tmp_path / "invalid-utf8.json", b'{"value":"' + bytes([0xFF]) + b'"}'
+ )
+ malformed = _write(tmp_path / "malformed.json", b'}{"value":1}')
+ with pytest.raises(ValueError, match="not valid UTF-8"):
+ read_json_object(invalid_utf8)
+ with pytest.raises(ValueError, match="not valid JSON"):
+ read_json_object(malformed)
+
+ valid = _write(tmp_path / "valid-object.json", b"{}")
+
+ def raise_recursion(_: str) -> object:
+ raise RecursionError("decoder stack exhausted")
+
+ monkeypatch.setattr(_bounded_json.json, "loads", raise_recursion)
+ with pytest.raises(ValueError, match="decoder recursion capacity"):
+ read_json_object(valid)
+
+
+@pytest.mark.parametrize("module_name", _SCRIPT_MODULES)
+def test_every_wrapper_rejects_non_object_json(
+ module_name: str,
+ tmp_path: Path,
+) -> None:
+ """Each script preserves its object-root contract through delegation."""
+ module = importlib.import_module(module_name)
+ path = _write(tmp_path / f"{module_name.rsplit('.', 1)[-1]}.json", b"[]")
+ with pytest.raises(RuntimeError, match="must be an object"):
+ module._read_json(path)
+
+
+@pytest.mark.parametrize("module_name", _SCRIPT_MODULES)
+def test_every_wrapper_delegates_to_shared_reader(
+ module_name: str,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Every governed reader delegates without duplicating parsing logic."""
+ module = importlib.import_module(module_name)
+ requested = tmp_path / "artifact.json"
+ marker = {"bounded": True}
+ observed: list[Path] = []
+
+ def fake_reader(path: Path) -> dict[str, bool]:
+ observed.append(path)
+ return marker
+
+ monkeypatch.setattr(module, "read_json_object", fake_reader)
+ assert module._read_json(requested) is marker
+ assert observed == [requested]
+
+
+@pytest.mark.skipif(not hasattr(os, "O_NOFOLLOW"), reason="O_NOFOLLOW unavailable")
+def test_symbolic_link_is_rejected(tmp_path: Path) -> None:
+ """A symbolic-link leaf is never followed on supporting platforms."""
+ target = _write(tmp_path / "target.json", b"{}")
+ link = tmp_path / "input.json"
+ link.symlink_to(target)
+ with pytest.raises(ValueError, match="stable regular file"):
+ read_json_object(link)
+
+
+def test_directory_is_rejected(tmp_path: Path) -> None:
+ """A directory descriptor is rejected as nonregular input."""
+ with pytest.raises(ValueError, match="stable regular file"):
+ read_json_object(tmp_path)
+
+
+@pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="FIFO unavailable")
+def test_fifo_is_rejected_without_blocking(tmp_path: Path) -> None:
+ """A FIFO is opened nonblocking and rejected before any content read."""
+ fifo = tmp_path / "input.pipe"
+ os.mkfifo(fifo)
+ with pytest.raises(ValueError, match="stable regular file"):
+ read_json_object(fifo)
+
+
+def test_descriptor_path_replacement_is_rejected(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Replacing the path after descriptor open is detected deterministically."""
+ path = _write(tmp_path / "input.json", b"{}")
+ replacement = _write(tmp_path / "replacement.json", b'{"replacement":true}')
+ real_read = _bounded_json.os.read
+ replaced = False
+
+ def replacing_read(file_descriptor: int, byte_count: int) -> bytes:
+ nonlocal replaced
+ chunk = real_read(file_descriptor, byte_count)
+ if not replaced:
+ replaced = True
+ path.unlink()
+ replacement.replace(path)
+ return chunk
+
+ monkeypatch.setattr(_bounded_json.os, "read", replacing_read)
+ with pytest.raises(ValueError, match="path changed"):
+ read_json_object(path)
+
+
+def test_missing_path_and_identity_lookup_fail_closed(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Open and post-open identity failures use content-free errors."""
+ with pytest.raises(ValueError, match="stable regular file"):
+ read_json_object(tmp_path / "missing.json")
+
+ path = _write(tmp_path / "input.json", b"{}")
+ real_lstat = _bounded_json.os.lstat
+ calls = 0
+
+ def failing_lstat(value: Path) -> os.stat_result:
+ nonlocal calls
+ calls += 1
+ if calls == 2:
+ raise FileNotFoundError
+ return real_lstat(value)
+
+ monkeypatch.setattr(_bounded_json.os, "lstat", failing_lstat)
+ with pytest.raises(ValueError, match="path changed"):
+ read_json_object(path)
+
+
+def test_initial_identity_mismatch_and_nonregular_identity_fail_closed(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Identity mismatch and a nonregular lstat result are rejected."""
+ path = _write(tmp_path / "input.json", b"{}")
+ other = _write(tmp_path / "other.json", b"{}")
+ other_status = os.lstat(other)
+ monkeypatch.setattr(_bounded_json.os, "lstat", lambda _: other_status)
+ with pytest.raises(ValueError, match="path changed"):
+ read_json_object(path)
+
+ class NonRegularStatus:
+ st_mode = 0
+ st_dev = other_status.st_dev
+ st_ino = other_status.st_ino
+
+ monkeypatch.setattr(_bounded_json.os, "lstat", lambda _: NonRegularStatus())
+ with pytest.raises(ValueError, match="stable regular file"):
+ read_json_object(path)
diff --git a/tests/test_figma_evidence_sync.py b/tests/test_figma_evidence_sync.py
index df5ba65c7..7397defcf 100644
--- a/tests/test_figma_evidence_sync.py
+++ b/tests/test_figma_evidence_sync.py
@@ -133,3 +133,32 @@ def test_figma_evidence_sync_fails_when_code_connect_enabled(tmp_path):
assert manifest["status"] == "failed"
failed_names = {check["name"] for check in manifest["failed_checks"]}
assert "figma:code_connect_disabled" in failed_names
+
+
+def test_main_reports_repo_root_relative_output(tmp_path, monkeypatch, capsys):
+ """Report a relative output path from the repository root, not the process CWD."""
+ module = _load_sync()
+ repo_root = tmp_path / "repo"
+ _write_packet(repo_root / "packet.json")
+ working_directory = tmp_path / "working-directory"
+ working_directory.mkdir()
+ monkeypatch.chdir(working_directory)
+
+ exit_code = module.main(
+ [
+ "--repo-root",
+ str(repo_root),
+ "--packet",
+ "packet.json",
+ "--out",
+ "relative-output",
+ ]
+ )
+
+ output = json.loads(capsys.readouterr().out)
+ expected_out = (repo_root / "relative-output").resolve()
+ manifest_path = Path(output["manifest"])
+ assert exit_code == 0
+ assert output["out"] == str(expected_out)
+ assert manifest_path == expected_out / "figma_evidence_sync_manifest.json"
+ assert manifest_path.exists()