Files
canina/scripts/orchestration/market_proposals.py

78 lines
3.4 KiB
Python

"""Conservative, offline-testable approval proposal gateway for market-scout evidence.
Not scheduled or activated. Only explicitly allowlisted digital audit work is accepted.
"""
from __future__ import annotations
import hashlib
import json
import re
import uuid
from urllib.parse import urlsplit, urlunsplit
ROUTES = {
"CATALOG_AUDIT": ("CONTENT", "CAMPAIGN", "Audit cited catalog evidence"),
"SEO_AUDIT": ("SEO", "SEO", "Audit cited search evidence"),
"WEB_FEATURE_REVIEW": ("DEV", "FEATURE", "Review cited website feature gap"),
}
def validate_proposal(item: dict, report: str, report_name: str) -> dict:
"""Discard untrusted prose and construct a bounded review-only proposal."""
if not isinstance(item, dict) or not isinstance(report, str):
raise ValueError("Invalid proposal or report")
action = item.get("action_type")
route = ROUTES.get(action)
if route is None or item.get("department") != route[0]:
raise ValueError("Only paired digital routes are supported")
url = item.get("source_url")
quote = item.get("evidence_quote")
if not isinstance(url, str) or not isinstance(quote, str):
raise ValueError("A source URL and exact evidence quote are required")
parsed = urlsplit(url)
if parsed.scheme not in ("https", "http") or not parsed.hostname or parsed.username or parsed.password or len(url) > 1000:
raise ValueError("Invalid evidence URL")
canonical_url = urlunsplit((parsed.scheme.lower(), parsed.netloc.lower(), parsed.path.rstrip("/") or "/", parsed.query, ""))
if not quote.strip() or len(quote) > 500 or not any(
url in block and quote in block for block in re.split(r"\n\s*\n", report)
):
raise ValueError("Evidence and URL must occur verbatim in the same scout report block")
fingerprint = hashlib.sha256(json.dumps([canonical_url, quote.strip(), action], ensure_ascii=False, separators=(",", ":")).encode()).hexdigest()
return {
"department": route[0], "category": route[1],
"title": f"{route[2]} [{fingerprint[:12]}]",
"fingerprint": fingerprint,
"payload": {
"sourceUrl": canonical_url, "evidenceQuote": quote.strip(),
"sourceFingerprint": fingerprint, "sourceReport": str(report_name).split("/")[-1][:255],
"actionType": action, "reviewRequired": True,
},
}
def _literal(value: str) -> str:
return "'" + value.replace("'", "''") + "'"
def insert_proposal(db, proposal: dict) -> bool:
"""Atomically serialize fingerprint insertion and count only returned IDs."""
fp = proposal["fingerprint"]
if not re.fullmatch(r"[0-9a-f]{64}", fp):
raise ValueError("Invalid fingerprint")
payload = json.dumps(proposal["payload"], ensure_ascii=False)
sql = f"""BEGIN;
SELECT pg_advisory_xact_lock(hashtextextended({_literal('market-proposal:' + fp)}, 0));
INSERT INTO approval_requests (id, department, category, title, payload, status, created_at, updated_at)
SELECT gen_random_uuid(), {_literal(proposal['department'])}, {_literal(proposal['category'])},
{_literal(proposal['title'])}, {_literal(payload)}::jsonb, 'PENDING', NOW(), NOW()
WHERE NOT EXISTS (
SELECT 1 FROM approval_requests
WHERE payload->>'sourceFingerprint' = {_literal(fp)}
)
RETURNING id;
COMMIT;"""
result = db.sql(sql)
return any(re.fullmatch(r"[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}", line.strip())
for line in result.splitlines())