M44: harden release integrity and assurance
This commit is contained in:
Executable
+126
@@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fail when checked-in API, event, MCP or n8n contracts drift from the code."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
from app.main import app
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def fail(message: str, failures: list[str]) -> None:
|
||||
failures.append(message)
|
||||
|
||||
|
||||
def check_openapi(failures: list[str]) -> None:
|
||||
committed = yaml.safe_load((ROOT / "contracts/openapi.yaml").read_text(encoding="utf-8"))
|
||||
generated = app.openapi()
|
||||
if committed != generated:
|
||||
fail(
|
||||
"contracts/openapi.yaml differs from app.openapi(); regenerate it with "
|
||||
"scripts/generate-openapi.py",
|
||||
failures,
|
||||
)
|
||||
|
||||
|
||||
def check_mcp(failures: list[str]) -> None:
|
||||
contract = json.loads((ROOT / "contracts/mcp-tools.json").read_text(encoding="utf-8"))
|
||||
contracted = {
|
||||
(tool["endpoint"]["method"].upper(), tool["endpoint"]["path"])
|
||||
for tool in contract["tools"]
|
||||
if tool.get("read_only") is True and isinstance(tool.get("endpoint"), dict)
|
||||
}
|
||||
generated = app.openapi()
|
||||
implemented = {
|
||||
(method.upper(), path)
|
||||
for path, operations in generated["paths"].items()
|
||||
if path.startswith("/api/v1/integrations/mcp/")
|
||||
for method in operations
|
||||
if method.lower() in {"get", "post", "put", "patch", "delete"}
|
||||
}
|
||||
if len(contracted) != len(contract["tools"]):
|
||||
fail("Every MCP tool must be read-only and declare its provider endpoint", failures)
|
||||
if contracted != implemented:
|
||||
fail(
|
||||
f"MCP endpoint drift: contract={sorted(contracted)!r}, code={sorted(implemented)!r}",
|
||||
failures,
|
||||
)
|
||||
if any(method not in {"GET", "POST"} for method, _path in contracted):
|
||||
fail("MCP contract exposes an unsupported mutation method", failures)
|
||||
|
||||
|
||||
def check_event_schema(failures: list[str]) -> None:
|
||||
schema = json.loads((ROOT / "contracts/events.schema.json").read_text(encoding="utf-8"))
|
||||
expected_envelope = {
|
||||
"event_id",
|
||||
"event_type",
|
||||
"occurred_at",
|
||||
"correlation_id",
|
||||
"aggregate",
|
||||
"data",
|
||||
}
|
||||
expected_data = {
|
||||
"vehicle_ref",
|
||||
"inspection_ref",
|
||||
"resulting_vehicle_status",
|
||||
"attention_reasons",
|
||||
}
|
||||
if set(schema.get("required", [])) != expected_envelope:
|
||||
fail("Event envelope required fields drifted", failures)
|
||||
data_schema = schema.get("properties", {}).get("data", {})
|
||||
if set(data_schema.get("required", [])) != expected_data:
|
||||
fail("vehicle.returned.v1 data fields drifted", failures)
|
||||
event_type = schema.get("properties", {}).get("event_type", {}).get("const")
|
||||
if event_type != "vehicle.returned.v1":
|
||||
fail("Unexpected event_type contract", failures)
|
||||
|
||||
|
||||
def check_workflows(failures: list[str]) -> None:
|
||||
workflows_dir = ROOT / "n8n/workflows"
|
||||
manifest = (workflows_dir / "MANIFEST.md").read_text(encoding="utf-8")
|
||||
expected = {
|
||||
"fleet-ops-vehicle-return.json": "mobilityops-return-processing",
|
||||
"fleet-ops-data-quality-scan.json": "mobilityops-scheduled-quality-scan",
|
||||
"fleet-ops-ragcore-procedure-sync.json": "6wbkc4d1AouGpmWT",
|
||||
"fleet-ops-error-handler.json": "Xppn2rAEqUuyiCJF",
|
||||
"fleet-ops-alert-receiver.json": "mobilityops-alert-receiver",
|
||||
}
|
||||
declared_hashes = set(re.findall(r"`([0-9a-f]{64})`", manifest))
|
||||
for filename, workflow_id in expected.items():
|
||||
path = workflows_dir / filename
|
||||
raw = path.read_bytes()
|
||||
digest = hashlib.sha256(raw).hexdigest()
|
||||
if digest not in declared_hashes:
|
||||
fail(f"{filename} checksum is missing or stale in MANIFEST.md", failures)
|
||||
definition = json.loads(raw)
|
||||
if definition.get("id") != workflow_id:
|
||||
fail(f"{filename} has unexpected workflow id", failures)
|
||||
serialized = raw.decode("utf-8")
|
||||
if "http://fleetops.itworx.tech" in serialized:
|
||||
fail(f"{filename} contains a cleartext Fleet Ops callback", failures)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
failures: list[str] = []
|
||||
check_openapi(failures)
|
||||
check_mcp(failures)
|
||||
check_event_schema(failures)
|
||||
check_workflows(failures)
|
||||
if failures:
|
||||
for failure in failures:
|
||||
print(f"ERROR: {failure}", file=sys.stderr)
|
||||
return 1
|
||||
print("OpenAPI, event, MCP and n8n contracts are synchronized.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,18 @@
|
||||
import { readdir, stat } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
const limits = { ".js": 400 * 1024, ".css": 180 * 1024 };
|
||||
const assets = join(import.meta.dirname, "..", "frontend", "dist", "assets");
|
||||
const failures = [];
|
||||
|
||||
for (const name of await readdir(assets)) {
|
||||
const extension = Object.keys(limits).find((candidate) => name.endsWith(candidate));
|
||||
if (!extension) continue;
|
||||
const bytes = (await stat(join(assets, name))).size;
|
||||
console.log(`${name}: ${(bytes / 1024).toFixed(1)} KiB / ${limits[extension] / 1024} KiB`);
|
||||
if (bytes > limits[extension]) failures.push(name);
|
||||
}
|
||||
|
||||
if (failures.length) {
|
||||
throw new Error(`Frontend asset budget exceeded: ${failures.join(", ")}`);
|
||||
}
|
||||
Executable
+26
@@ -0,0 +1,26 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prevent known large modules from growing while they are incrementally decomposed."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
LINE_LIMITS = {
|
||||
"backend/app/services/data_quality.py": 950,
|
||||
"frontend/src/pages/DataQualityIssueDetail.tsx": 850,
|
||||
}
|
||||
BYTE_LIMITS = {"frontend/src/styles.css": 84_000}
|
||||
|
||||
failures: list[str] = []
|
||||
for relative, limit in LINE_LIMITS.items():
|
||||
count = len((ROOT / relative).read_text(encoding="utf-8").splitlines())
|
||||
print(f"{relative}: {count}/{limit} lines")
|
||||
if count > limit:
|
||||
failures.append(relative)
|
||||
for relative, limit in BYTE_LIMITS.items():
|
||||
count = (ROOT / relative).stat().st_size
|
||||
print(f"{relative}: {count}/{limit} bytes")
|
||||
if count > limit:
|
||||
failures.append(relative)
|
||||
|
||||
if failures:
|
||||
raise SystemExit("Source budget exceeded; extract a focused module: " + ", ".join(failures))
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Regenerate the deterministic checked-in FastAPI OpenAPI contract."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
from app.main import app
|
||||
|
||||
target = Path(__file__).resolve().parents[1] / "contracts/openapi.yaml"
|
||||
target.write_text(
|
||||
yaml.safe_dump(app.openapi(), sort_keys=False, allow_unicode=True),
|
||||
encoding="utf-8",
|
||||
)
|
||||
print(target)
|
||||
Reference in New Issue
Block a user