← Back to Research Index View Raw Source

pompous-v1-2.py

"""
pompous_v1_2.py — among other things™ + DoucheVibes Operator™ (v1.2.0)
========================================================================
Grounded strictly in the audited corpus and specifications:

  [1] "Among Other Things; Researching Function Calls" (Nov 15, 2026)
      — MegaPrompt / spec defining scope, tables, exact AmongOtherThings()
        signature, and 10 unit tests.
  [2] "Among Other Things; Function Calls" (Nov 15, 2026)
      — Verified partial SEC speech audit (Nov 12, 2026): 20 exact hits
        across 18 audited speeches (19 searched).
  [3] "Douche Vibes Operator; Pompous.py" (Nov 15, 2026)
      — v1.1.0-pompous-douchevibes-operator: closed-form operator
        L_struct = (P_val / C_fed) * (1 - delta) from Prior Art §10 + §18
        (SHA-256: 79a8d61919906449cc8baf1ef64d8982aed7ac0535e693d1eecfd72b4d3ad123),
        inverses (solve_delta, solve_Pval, solve_Cfed), batch runner, and
        quarantined linguistic proxy.
  [4] "Douche Vibes Payment Processor Schema" (Nov 15, 2026)
      — v1.2 Operational Blueprint:
        * Preserves v1.0.0 SEC baseline and v1.1.0 DoucheVibes calibration.
        * Expands _SENTIMENT_PATTERNS with finite-verb inflection forms
          (e.g., "include[s/d], but [is/are/was/were] not limited to" seen
          in Toast FY2025 Form 10-K).
        * Enforces a minimum 1,000-word document gate on estimate_delta_from_text()
          to prevent short-excerpt saturation (delta_proxy -> 1.0000).
        * Quarantines delta_proxy strictly as PROPOSED PROXY, NOT IN SOURCE.
        * Adds Track A FBO bank / payment-processor custodial stress-test
          batch runner (PROPOSED-MEASUREMENT, NOT IN SOURCE) with SHA-256
          and canonical-URL deduplication.

Copyright © Albert Lane. All Rights Reserved.
Albert Lane Proprietary Software License | https://albertlane.net
"""

from __future__ import annotations

import hashlib
import math
import re
import time
import urllib.request
from html import unescape
from typing import Any

__version__ = "1.2.0-pompous-fbo-audit"
__trademark__ = "among other things™ / DoucheVibes Operator™"

PRIOR_ART_SOURCE_SHA256 = (
    "79a8d61919906449cc8baf1ef64d8982aed7ac0535e693d1eecfd72b4d3ad123"
)

# ---------------------------------------------------------------------------
# Seed / calibration — MUST return 1. If it returns 0 or 2+, definition is wrong.
# ---------------------------------------------------------------------------

SEED_SPEECH = {
    "title": "The Economics of Attention",
    "speaker": "Joshua White, Chief Economist / Director, Division of Economic and Risk Analysis",
    "audience": "NACD Nashville Chapter",
    "date": "Nov 11, 2026",
    "url": "https://www.sec.gov/newsroom/speeches-statements/white-economics-attention-nacd-111126",
}

SEED_TEXT = (
    "In 2012, Congress passed the JOBS Act. Among other things, "
    "it created an on-ramp for emerging growth companies entering "
    "the public markets."
)

# ---------------------------------------------------------------------------
# Verified audited sample — Table 2 from [2], quoted, not paraphrased.
# 18 speeches with >=1 exact hit. Exact total = 20.
# ---------------------------------------------------------------------------

AUDITED_SPEECHES = [
    {
        "date": "Nov 11, 2026",
        "speaker": "Joshua White, Chief Economist / DERA",
        "title": "The Economics of Attention",
        "exact": 1,
        "sentiment_only": 0,
        "first_quote": "In 2012, Congress passed the JOBS Act. Among other things, it created an on-ramp…",
        "context_type": "Legislative summary",
        "tier": "A",
    },
    {
        "date": "Oct 13, 2021",
        "speaker": "Gurbir Grewal, Director, Enforcement",
        "title": "Remarks at SEC Speaks 2021",
        "exact": 2,
        "sentiment_only": 0,
        "first_quote": "Enhancing it will require, among other things, robust enforcement… ; Sanjay and I want to empower them by, among other things, adjusting…",
        "context_type": "Enforcement / risk summary",
        "tier": "A/B",
    },
    {
        "date": "Dec 7, 2023",
        "speaker": "Gary Gensler, Chair",
        "title": "They Are Merely the Agents",
        "exact": 1,
        "sentiment_only": 0,
        "first_quote": "Among other things, the rules require exchanges to propose and implement listing standards…",
        "context_type": "Rulemaking summary",
        "tier": "A/B",
    },
    {
        "date": "Oct 9, 2025",
        "speaker": "Paul S. Atkins, Chair",
        "title": "Keynote, 25th Annual A.A. Sommer Lecture",
        "exact": 1,
        "sentiment_only": 0,
        "first_quote": "Among other things, Regulation S-K was a much-needed rationalization…",
        "context_type": "Economic / policy framing",
        "tier": "A/B",
    },
    {
        "date": "July 22, 2009",
        "speaker": "Mary L. Schapiro, Chair",
        "title": "Statement at SEC Open Meeting",
        "exact": 1,
        "sentiment_only": 0,
        "first_quote": "including, among other things, campaign contributions made to influence the selection…",
        "context_type": "Rulemaking summary",
        "tier": "A/B",
        "note": "Inclusive-variant. Counted once despite HTML + PDF copies.",
    },
    {
        "date": "Feb 13, 2026",
        "speaker": "Jim Moloney, Director, CorpFin",
        "title": "Coming Attractions From the Division of Corporation Finance",
        "exact": 1,
        "sentiment_only": 1,
        "first_quote": "This statement describes, among other things, my remarks… ; sentiment: data, including but not limited to the cost of compliance…",
        "context_type": "Rulemaking summary",
        "tier": "A/B",
    },
    {
        "date": "Dec 4, 2018",
        "speaker": "Steven Peiken",
        "title": "The Salutary Effects of International Cooperation",
        "exact": 1,
        "sentiment_only": 0,
        "first_quote": "Among other things, we need to address the impact of… GDPR…",
        "context_type": "Enforcement / risk summary",
        "tier": "A/B",
    },
    {
        "date": "May 19, 2005",
        "speaker": "William Donaldson, Chair",
        "title": "Remarks before Council on Foreign Relations",
        "exact": 1,
        "sentiment_only": 0,
        "first_quote": "Among other things, registration of advisers… will require hedge fund managers to adopt basic compliance controls…",
        "context_type": "Economic / policy framing",
        "tier": "A/B",
    },
    {
        "date": "May 9, 2006",
        "speaker": "Roel Campos, Commissioner",
        "title": "Remarks at Harvard Kennedy School",
        "exact": 2,
        "sentiment_only": 0,
        "first_quote": "shareholder activists often point to, among other things, numerous examples… ; a bill that would, among other things, require shareholder approval…",
        "context_type": "Economic / policy framing",
        "tier": "A/B",
        "note": "Tied highest single-speech exact count (2) with Grewal.",
    },
    {
        "date": "Dec 4, 2017",
        "speaker": "Speaker, 2017 AICPA Conference",
        "title": "Remarks before 2017 AICPA Conference",
        "exact": 1,
        "sentiment_only": 0,
        "first_quote": "The MG is seeking stakeholder views… including, among other things:",
        "context_type": "Rulemaking summary",
        "tier": "A/B",
        "note": "Inclusive-variant. First of two Dec 4, 2017 AICPA rows in source.",
    },
    {
        "date": "Dec 4, 2017",
        "speaker": "Speaker, 2017 AICPA Conference",
        "title": "Remarks before 2017 AICPA Conference",
        "exact": 1,
        "sentiment_only": 0,
        "first_quote": "to, among other things, devise and maintain a system of internal accounting controls…",
        "context_type": "Rulemaking summary",
        "tier": "A/B",
        "note": "Second of two Dec 4, 2017 AICPA rows in source.",
    },
    {
        "date": "July 10, 2013",
        "speaker": "Luis A. Aguilar, Commissioner",
        "title": "Facilitating General Solicitation at the Expense of Investors",
        "exact": 1,
        "sentiment_only": 0,
        "first_quote": "Today, among other things, the Commission considers amendments to Rule 506…",
        "context_type": "Legislative summary",
        "tier": "A/B",
        "note": "Counted once despite HTML + PDF copies.",
    },
    {
        "date": "Apr 11, 2013",
        "speaker": "Lona Nallengara, Testimony",
        "title": "JOBS Act Implementation Update",
        "exact": 1,
        "sentiment_only": 0,
        "first_quote": "by, among other things, permitting certain… companies to submit draft registration statements…",
        "context_type": "Legislative summary",
        "tier": "A/B",
    },
    {
        "date": "May 14, 2025",
        "speaker": "Keith Cassidy, Acting Director, Examinations",
        "title": "Regulation S-P – Back to the Future",
        "exact": 1,
        "sentiment_only": 0,
        "first_quote": "The standards established by Regulation S-P require, among other things, covered institutions to…",
        "context_type": "Rulemaking summary",
        "tier": "A/B",
    },
    {
        "date": "Feb 9, 2022",
        "speaker": "Hester M. Peirce, Commissioner",
        "title": "Statement on Private Fund Advisers Proposal",
        "exact": 1,
        "sentiment_only": 0,
        "first_quote": "Among other things, registered private fund advisers would have to provide… detailed, standardized, quarterly information…",
        "context_type": "Rulemaking summary",
        "tier": "A/B",
    },
    {
        "date": "Oct 27, 1978",
        "speaker": "Roberta Karmel, Commissioner",
        "title": "Management Fraud — What Are The Standards?",
        "exact": 1,
        "sentiment_only": 0,
        "first_quote": "the Commission proposed disclosures regarding, among other things, management integrity…",
        "context_type": "Economic / policy framing",
        "tier": "A/B",
        "note": "Earliest hit in audited sample.",
    },
    {
        "date": "Oct 7, 1993",
        "speaker": "Commissioner Roberts",
        "title": "Failure to Supervise Revisited",
        "exact": 1,
        "sentiment_only": 0,
        "first_quote": "which may have resulted from, among other things, the Huff decision",
        "context_type": "Other",
        "tier": "A/B",
    },
    {
        "date": "Mar 26, 1991",
        "speaker": "Richard Y. Roberts, Commissioner",
        "title": "Improving Our Debt Markets",
        "exact": 1,
        "sentiment_only": 0,
        "first_quote": "Congress found that, among other things, it was ‘in the public interest’ — search snippet, SEC.gov PDF",
        "context_type": "Legislative summary",
        "tier": "A/B",
    },
]

SENTIMENT_ONLY_SPEECH = {
    "date": "Nov 4, 2026",
    "speaker": "Mark T. Uyeda",
    "title": "Statement on Small Entity Definitions",
    "exact": 0,
    "sentiment_only": 1,
    "first_quote": "Among others, the amendments increas…",
    "note": "Sentiment-only, not in exact total.",
}

FOOTNOTE_ONLY_FLAGGED = {
    "date": "May 19, 2025",
    "speaker": "Caroline Crenshaw",
    "title": "A Reckless Game of Regulatory Jenga",
    "exact": 0,
    "note": "Footnote-only: footnote citing Marketing Compliance FAQ: “(among other things, allowing ads performance…)” — excluded from speaker own-use total.",
}

VERIFIED_TOTALS = {
    "exact_among_other_things_in_audited_speeches": 20,
    "inclusive_variant_including_among_other_things_subset": 4,
    "sentiment_only_equivalents_separate_not_in_exact_total": 2,
    "quoted_only_excluded_from_speaker_total": 0,
    "footnote_only_flagged_excluded": 1,
    "total_speeches_searched_or_snippet_audited": 19,
    "total_speeches_with_ge_1_exact_hit": 18,
    "search_date": "Nov 12, 2026",
    "coverage": "Partial audited sample, NOT all-time. Tier A = 6 speeches opened in full (7 hits). Tier B = 12 speeches corroborated by snippets (13 hits).",
}

VERIFIED_BY_CONTEXT_TYPE = {
    "Legislative summary": 4,
    "Rulemaking summary": 7,
    "Enforcement / risk summary": 3,
    "Economic / policy framing": 4,
    "Other": 2,
}

VERIFICATION_CHECKLIST = {
    "double_count_html_pdf": "No. Deduped by canonical speech + SHA-256 in v1.2. Schapiro and Aguilar each counted once despite HTML + PDF copies.",
    "footnotes_counted": "No. 1 footnote-only hit flagged (Crenshaw 2025) and excluded.",
    "disclaimer_boilerplate_counted": "No. Standard 'views are my own' disclaimers contain no hit in audited pages.",
    "earliest_hit": "Oct 27, 1978 — Karmel",
    "latest_hit": "Nov 11, 2026 (seed) — White",
    "highest_single_speech": "Grewal (2) and Campos (2), tied. Both hits quoted in Table 2.",
    "seed_is_1": True,
    "estimated_recall": "Unknown for all-time. v1.2 adds finite-verb inflection matching while preserving v1.0.0 SEC baseline via flag.",
}

# ---------------------------------------------------------------------------
# Normalization — whitespace, curly quotes, line breaks, PDF hyphenation
# ---------------------------------------------------------------------------

def _normalize_for_matching(text: str) -> str:
    """Normalize text for deterministic matching and offset preservation."""
    if text is None:
        return ""
    t = str(text)
    t = t.replace("\u201c", '"').replace("\u201d", '"').replace("\u201e", '"')
    t = t.replace("\u2018", "'").replace("\u2019", "'").replace("\u201a", "'")
    t = t.replace("\u00ab", '"').replace("\u00bb", '"')
    t = t.replace("\u00a0", " ").replace("\u2009", " ").replace("\u200a", " ")
    t = re.sub(r"(\w)-\r?\n\s*", r"\1", t)
    t = re.sub(r"(\w)-\s*\n\s*", r"\1", t)
    t = re.sub(r"\s+", " ", t)
    return t.strip()


def _word_count(normalized_text: str) -> int:
    if not normalized_text:
        return 0
    return len(re.findall(r"\b\w+(?:['’-]\w+)*\b", normalized_text))


# ---------------------------------------------------------------------------
# Track B: AmongOtherThings() v1.0.0 baseline + v1.2 finite-verb inflection upgrade
# ---------------------------------------------------------------------------

_EXACT_RE = re.compile(r"\bamong[\s,;:\-]*other[\s,;:\-]*things\b", re.IGNORECASE)

# v1.0.0 SEC speech baseline sentiment patterns (preserved intact)
_SENTIMENT_PATTERNS = [
    r"\bincluding\s*,?\s*but\s+not\s+limited\s+to\b",
    r"\bincluding\s+without\s+limitation\b",
    r"\bamong\s+others\b",
    r"\binter\s+alia\b",
    r"\band\s+other\s+things\b",
    r"\band\s+so\s+on\b",
]

# v1.2 extension: finite-verb and inflected legal disclaimer patterns
# Captures corporate 10-K / PayFac reserve clauses such as Toast FY2025 Form 10-K
# ("include, but are not limited to") and inflected variants without breaking v1.0.0.
_V12_INFLECTED_SENTIMENT_PATTERNS = [
    r"\binclud(?:e|es|ed|ing)\s*,?\s*but\s+(?:is|are|was|were)?\s*not\s+limited\s+to\b",
    r"\binclud(?:e|es|ed|ing)\s*,?\s*without\s+limitation\b",
    r"\bnot\s+limited\s+to\s+the\s+foregoing\b",
    r"\bwithout\s+limiting\s+the\s+generality\s+of\s+the\s+foregoing\b",
]

_SENT_PAT = re.compile(r"[^.!?]+[.!?]+[\"']?\s*|[^.!?]+$", re.DOTALL)


def AmongOtherThings(
    text: str,
    *,
    include_variants: bool = True,
    include_sentiment: bool = False,
    include_inflected_sentiment: bool = False,
    return_contexts: bool = True,
    context_window: int = 2,
) -> dict[str, Any]:
    """
    Count "among other things" and non-exhaustive hedging syntax in text.

    Preserves exact v1.0.0 behavior by default (include_inflected_sentiment=False).
    When include_sentiment=True and include_inflected_sentiment=True (or via
    AmongOtherThings_v12), captures finite-verb legal disclaimers such as
    "include, but are not limited to" and "includes, without limitation".
    """
    if text is None:
        text = ""
    if not isinstance(text, str):
        text = str(text)

    normalized = _normalize_for_matching(text)

    def _empty() -> dict[str, Any]:
        return {
            "exact_count": 0,
            "inclusive_variant_count": 0,
            "sentiment_only_count": 0,
            "inflected_sentiment_count": 0,
            "quoted_count": 0,
            "total_count": 0,
            "word_count": 0,
            "hits": [],
        }

    if not normalized.strip():
        return _empty()

    sentences = []
    for m in _SENT_PAT.finditer(normalized):
        s = m.group(0).strip()
        if s:
            sentences.append((m.start(), m.end(), s))
    if not sentences:
        sentences = [(0, len(normalized), normalized.strip())]

    def _idx(pos: int) -> int:
        for i, (a, b, _) in enumerate(sentences):
            if a <= pos < b:
                return i
        return len(sentences) - 1

    def _context(si: int) -> str:
        if not return_contexts:
            return sentences[si][2] if sentences else ""
        lo = max(0, si - context_window)
        hi = min(len(sentences), si + context_window + 1)
        return " ".join(s for _, _, s in sentences[lo:hi])

    def _is_quoted(start: int) -> bool:
        return normalized[:start].count('"') % 2 == 1

    hits: list[dict[str, Any]] = []
    exact_spans: list[tuple[int, int]] = []

    for m in _EXACT_RE.finditer(normalized):
        s, e = m.span()
        look = normalized[max(0, s - 30):s]
        is_incl = False
        if include_variants:
            is_incl = bool(re.search(r"including\s*,?\s*$", look, re.IGNORECASE))
        quoted = _is_quoted(s)
        if quoted:
            typ = "quoted"
        elif is_incl:
            typ = "inclusive_variant"
        else:
            typ = "exact"
        si = _idx(s)
        hits.append(
            {
                "match": m.group(0),
                "type": typ,
                "sentence": sentences[si][2] if sentences else "",
                "context": _context(si),
                "start": s,
                "end": e,
            }
        )
        exact_spans.append((s, e))

    if include_sentiment:
        patterns = list(_SENTIMENT_PATTERNS)
        v10_count = len(patterns)
        if include_inflected_sentiment:
            patterns.extend(_V12_INFLECTED_SENTIMENT_PATTERNS)

        sentiment_hits: list[dict[str, Any]] = []
        for idx_pat, pat in enumerate(patterns):
            is_v12_ext = idx_pat >= v10_count
            for m in re.finditer(pat, normalized, re.IGNORECASE):
                s, e = m.span()
                if any(s < ee and e > ss for ss, ee in exact_spans):
                    continue
                if any(s < h["end"] and e > h["start"] for h in sentiment_hits):
                    continue
                si = _idx(s)
                sentiment_hits.append(
                    {
                        "match": m.group(0),
                        "type": "sentiment_only",
                        "inflected_v12": is_v12_ext,
                        "sentence": sentences[si][2] if sentences else "",
                        "context": _context(si),
                        "start": s,
                        "end": e,
                    }
                )
        sentiment_hits.sort(key=lambda x: x["start"])
        hits.extend(sentiment_hits)
        hits.sort(key=lambda x: x["start"])

    exact = sum(1 for h in hits if h["type"] in ("exact", "inclusive_variant"))
    incl = sum(1 for h in hits if h["type"] == "inclusive_variant")
    sent_only = sum(1 for h in hits if h["type"] == "sentiment_only")
    inflected = sum(
        1 for h in hits if h["type"] == "sentiment_only" and h.get("inflected_v12")
    )
    quoted = sum(1 for h in hits if h["type"] == "quoted")
    total = exact + (sent_only if include_sentiment else 0)

    return {
        "exact_count": exact,
        "inclusive_variant_count": incl,
        "sentiment_only_count": sent_only,
        "inflected_sentiment_count": inflected,
        "quoted_count": quoted,
        "total_count": total,
        "word_count": _word_count(normalized),
        "hits": hits,
    }


def AmongOtherThings_v12(
    text: str,
    *,
    include_variants: bool = True,
    include_sentiment: bool = True,
    include_inflected_sentiment: bool = True,
    return_contexts: bool = True,
    context_window: int = 2,
) -> dict[str, Any]:
    """Convenience v1.2 wrapper enabling finite-verb legal disclaimer matching."""
    return AmongOtherThings(
        text,
        include_variants=include_variants,
        include_sentiment=include_sentiment,
        include_inflected_sentiment=include_inflected_sentiment,
        return_contexts=return_contexts,
        context_window=context_window,
    )


# ---------------------------------------------------------------------------
# Corpus helper — canonical URL + SHA-256 content deduplication (v1.2)
# ---------------------------------------------------------------------------

def _canonical_url(url: str) -> str:
    return url.split("?")[0].rstrip("/").lower()


def _sha256_text(text: str) -> str:
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


def AmongOtherThings_corpus(
    urls: list[str],
    delay: float = 1.0,
    *,
    use_v12_patterns: bool = False,
    dedupe_sha256: bool = True,
) -> dict[str, Any]:
    """Fetch URLs, dedupe by canonical URL and SHA-256 content digest, and run parser."""
    if not urls:
        return {
            "speeches_searched": 0,
            "total_exact": 0,
            "rows": [],
            "errors": [],
            "deduped_skipped": 0,
            "sha256_deduped_skipped": 0,
        }
    seen_urls: set[str] = set()
    seen_hashes: set[str] = set()
    rows: list[dict[str, Any]] = []
    errors: list[dict[str, str]] = []
    url_skipped = 0
    hash_skipped = 0

    for url in urls:
        canon = _canonical_url(url)
        if canon in seen_urls:
            url_skipped += 1
            continue
        seen_urls.add(canon)
        try:
            req = urllib.request.Request(
                url,
                headers={
                    "User-Agent": "Mozilla/5.0 research (pompous_v1_2.py / audit)"
                },
            )
            with urllib.request.urlopen(req, timeout=20) as r:
                raw = r.read().decode("utf-8", errors="ignore")
            txt = unescape(re.sub(r"<[^>]+>", " ", raw))
            txt = re.sub(r"\s+", " ", txt).strip()
            digest = _sha256_text(txt)
            if dedupe_sha256 and digest in seen_hashes:
                hash_skipped += 1
                continue
            seen_hashes.add(digest)

            if use_v12_patterns:
                res = AmongOtherThings_v12(txt)
            else:
                res = AmongOtherThings(txt)

            rows.append(
                {
                    "url": url,
                    "canonical_url": canon,
                    "sha256": digest,
                    "word_count": res["word_count"],
                    "exact_count": res["exact_count"],
                    "inclusive_variant_count": res["inclusive_variant_count"],
                    "sentiment_only_count": res["sentiment_only_count"],
                    "inflected_sentiment_count": res["inflected_sentiment_count"],
                    "quoted_count": res["quoted_count"],
                    "total_count": res["total_count"],
                    "hits": res["hits"],
                }
            )
        except Exception as ex:  # noqa: BLE001
            errors.append({"url": url, "error": str(ex)})
        time.sleep(delay)

    return {
        "speeches_searched": len(rows),
        "total_exact": sum(r["exact_count"] for r in rows),
        "rows": rows,
        "errors": errors,
        "deduped_skipped": url_skipped,
        "sha256_deduped_skipped": hash_skipped,
    }


# ---------------------------------------------------------------------------
# Track A: DoucheVibes Operator™ (v1.1.0 preserved + v1.2 FBO accounting audits)
# Source: Prior Art §10 + §18, L_struct = (P_val / C_fed) * (1 - delta)
# ---------------------------------------------------------------------------

def _validate_real_number(val: Any, name: str) -> float:
    if isinstance(val, bool) or not isinstance(val, (int, float)):
        raise ValueError(f"{name} must be a real numeric value, got {type(val).__name__}")
    fval = float(val)
    if not math.isfinite(fval):
        raise ValueError(f"{name} must be finite, got {val!r}")
    return fval


def douche_vibes_operator(Pval: float, Cfed: float, delta: float) -> dict[str, Any]:
    """
    Closed-form Douche Vibe Operator from Prior Art §10 + §18:
      L_struct = (P_val / C_fed) * (1 - delta)

    C_fed is strictly a divisor, never a subtrahend.
    """
    p = _validate_real_number(Pval, "Pval")
    c = _validate_real_number(Cfed, "Cfed")
    d = _validate_real_number(delta, "delta")

    if c == 0.0:
        raise ValueError("Cfed cannot be 0: federal funding is a divisor, not subtrahend.")
    if c < 0.0:
        raise ValueError(f"Cfed must be positive (> 0), got {c}.")
    if d < 0.0 or d > 1.0:
        raise ValueError(f"delta must lie within [0, 1], got {d}.")

    solvency_remaining = 1.0 - d
    l_struct = (p / c) * solvency_remaining

    warnings: list[str] = []
    if d == 1.0:
        warnings.append("CRITICAL: delta == 1.0 (100% vibe decay; Lstruct collapses to 0).")
    elif d >= 0.9:
        warnings.append(f"HIGH RISK: delta={d:.4f} >= 0.9 (severe structural decay).")
    if c >= 10.0:
        warnings.append(
            f"HEURISTIC WARNING: Cfed={c:.4f} >= 10 (large federal/leverage divisor compressing liquidity)."
        )
    if p == 0.0:
        warnings.append("ZERO PRODUCTION: Pval == 0.0 yields Lstruct == 0.0.")
    if l_struct < 0.0:
        warnings.append(f"NEGATIVE LIQUIDITY: Lstruct={l_struct:.4f} < 0.")

    if l_struct == 0.0 and p > 0.0:
        interp = "Total vibe collapse: nominal claims hollowed to zero spendable liquidity."
    elif d >= 0.5:
        interp = "Severe decay: over half of Cfed-adjusted output is illusory vibes."
    elif c > 1.0:
        interp = "Divisor compression active: leverage/backstop scaling reduces spendable liquidity."
    else:
        interp = "Nominal structural liquidity intact."

    return {
        "Lstruct": l_struct,
        "Pval": p,
        "Cfed": c,
        "delta": d,
        "solvency_remaining": solvency_remaining,
        "vibe_share": d,
        "warnings": warnings,
        "interpretation": interp,
        "source_sha256": PRIOR_ART_SOURCE_SHA256,
    }


def solve_delta(Pval: float, Cfed: float, Lstruct: float) -> dict[str, Any]:
    """Inverse: delta = 1 - (Lstruct * Cfed / Pval). Flags out_of_range if outside [0, 1]."""
    p = _validate_real_number(Pval, "Pval")
    c = _validate_real_number(Cfed, "Cfed")
    ls = _validate_real_number(Lstruct, "Lstruct")

    if p == 0.0:
        raise ValueError("Pval cannot be 0 when solving for delta (division by zero).")
    if c <= 0.0:
        raise ValueError(f"Cfed must be > 0, got {c}.")

    delta = 1.0 - (ls * c / p)
    out_of_range = delta < 0.0 or delta > 1.0
    warnings: list[str] = []
    if out_of_range:
        warnings.append(
            f"OUT OF RANGE: implied delta={delta:.4f} falls outside [0, 1] "
            f"(Lstruct*Cfed={ls*c:.4f} vs Pval={p:.4f})."
        )
    elif delta >= 0.9:
        warnings.append(f"HIGH RISK: solved delta={delta:.4f} >= 0.9.")

    return {
        "delta": delta,
        "Pval": p,
        "Cfed": c,
        "Lstruct": ls,
        "out_of_range": out_of_range,
        "warnings": warnings,
    }


def solve_Pval(Lstruct: float, Cfed: float, delta: float) -> dict[str, Any]:
    """Inverse: Pval = Lstruct * Cfed / (1 - delta). Errors on delta == 1."""
    ls = _validate_real_number(Lstruct, "Lstruct")
    c = _validate_real_number(Cfed, "Cfed")
    d = _validate_real_number(delta, "delta")

    if c <= 0.0:
        raise ValueError(f"Cfed must be > 0, got {c}.")
    if d < 0.0 or d > 1.0:
        raise ValueError(f"delta must lie within [0, 1], got {d}.")
    if d == 1.0:
        raise ValueError("Cannot solve Pval when delta == 1.0 (division by zero).")

    pval = ls * c / (1.0 - d)
    return {"Pval": pval, "Lstruct": ls, "Cfed": c, "delta": d}


def solve_Cfed(Pval: float, Lstruct: float, delta: float) -> dict[str, Any]:
    """Inverse: Cfed = Pval * (1 - delta) / Lstruct. Errors on Lstruct == 0."""
    p = _validate_real_number(Pval, "Pval")
    ls = _validate_real_number(Lstruct, "Lstruct")
    d = _validate_real_number(delta, "delta")

    if d < 0.0 or d > 1.0:
        raise ValueError(f"delta must lie within [0, 1], got {d}.")
    if ls == 0.0:
        raise ValueError("Cannot solve Cfed when Lstruct == 0.0 (division by zero).")

    cfed = p * (1.0 - d) / ls
    return {"Cfed": cfed, "Pval": p, "Lstruct": ls, "delta": d}


def douche_vibes_batch(rows: list[dict[str, Any]]) -> dict[str, Any]:
    """
    Evaluate douche_vibes_operator across a batch of dicts:
      [{label?, Pval, Cfed, delta}, ...]
    Sorts valid results by delta descending, Lstruct ascending.
    Isolates per-row ValueError/TypeError failures into errors[].
    """
    results: list[dict[str, Any]] = []
    errors: list[dict[str, Any]] = []

    for idx, row in enumerate(rows):
        label = row.get("label", f"row_{idx}") if isinstance(row, dict) else f"row_{idx}"
        try:
            if not isinstance(row, dict):
                raise ValueError("Row must be a dict.")
            res = douche_vibes_operator(row["Pval"], row["Cfed"], row["delta"])
            entry = {"label": label, "row_index": idx, **res}
            results.append(entry)
        except Exception as ex:  # noqa: BLE001
            errors.append({"label": label, "row_index": idx, "error": str(ex)})

    results.sort(key=lambda r: (-r["delta"], r["Lstruct"]))

    if results:
        deltas = [r["delta"] for r in results]
        lstructs = [r["Lstruct"] for r in results]
        summary = {
            "count_valid": len(results),
            "count_errors": len(errors),
            "mean_delta": sum(deltas) / len(deltas),
            "max_delta": max(deltas),
            "min_Lstruct": min(lstructs),
            "max_Lstruct": max(lstructs),
            "count_delta_ge_0_9": sum(1 for d in deltas if d >= 0.9),
            "count_Lstruct_zero": sum(1 for ls in lstructs if ls == 0.0),
            "most_vibe_decayed": results[0]["label"],
        }
    else:
        summary = {
            "count_valid": 0,
            "count_errors": len(errors),
            "mean_delta": None,
            "max_delta": None,
            "min_Lstruct": None,
            "max_Lstruct": None,
            "count_delta_ge_0_9": 0,
            "count_Lstruct_zero": 0,
            "most_vibe_decayed": None,
        }

    return {"results": results, "errors": errors, "summary": summary}


# ---------------------------------------------------------------------------
# Quarantined Linguistic Proxy — PROPOSED PROXY, NOT IN SOURCE
# v1.2 enforces a 1,000-word minimum document gate by default.
# ---------------------------------------------------------------------------

MIN_PROXY_WORD_GATE = 1000


def estimate_delta_from_text(
    text: str,
    *,
    min_words: int = MIN_PROXY_WORD_GATE,
    enforce_word_gate: bool = True,
    include_inflected_sentiment: bool = True,
) -> dict[str, Any]:
    """
    PROPOSED PROXY, NOT IN SOURCE — NEVER feed automatically into douche_vibes_operator().

    Maps AmongOtherThings() total hedging density per 1,000 words divided by 10.0,
    capped at 1.0. Because short excerpts (<100 words) saturate to 1.0000 on a single
    hit, v1.2 enforces a default 1,000-word minimum document gate (returning
    delta_proxy=None and gated=True when word_count < min_words).
    """
    parsed = AmongOtherThings(
        text,
        include_variants=True,
        include_sentiment=True,
        include_inflected_sentiment=include_inflected_sentiment,
        return_contexts=False,
    )
    wc = parsed["word_count"]
    total_hits = parsed["total_count"]
    density_per_1000 = (total_hits / wc * 1000.0) if wc > 0 else 0.0
    gated = enforce_word_gate and wc < min_words

    if gated:
        delta_proxy = None
        note = (
            f"GATED (word_count={wc} < min_words={min_words}): "
            "Refusing to compute delta_proxy on sub-threshold text to avoid window-length saturation."
        )
    else:
        delta_proxy = min(1.0, density_per_1000 / 10.0) if wc > 0 else 0.0
        note = (
            "UNVALIDATED GOVERNANCE FLAG ONLY. Source does NOT equate AmongOtherThings() "
            "lexical density with financial delta."
        )

    return {
        "classification": "PROPOSED PROXY, NOT IN SOURCE",
        "gated": gated,
        "min_words_required": min_words if enforce_word_gate else 0,
        "word_count": wc,
        "exact_count": parsed["exact_count"],
        "sentiment_only_count": parsed["sentiment_only_count"],
        "inflected_sentiment_count": parsed["inflected_sentiment_count"],
        "total_hits": total_hits,
        "hedging_density_per_1000": round(density_per_1000, 4),
        "delta_proxy": round(delta_proxy, 4) if delta_proxy is not None else None,
        "warning": note,
    }


# ---------------------------------------------------------------------------
# v1.2 FBO Bank & Payment-Processor Stress-Test Batch Runner
# Classification: PROPOSED-MEASUREMENT, NOT IN SOURCE (Track A accounting)
# ---------------------------------------------------------------------------

DOCUMENTED_FBO_PROCESSOR_SCENARIOS: list[dict[str, Any]] = [
    {
        "label": "Synapse FBO Ledger Gap (Jun 7, 2024 Trustee Report)",
        "entity": "Synapse Financial Technologies / Partner Banks",
        "data_vintage": "2024-06-07",
        "mode": "solve_delta",
        "Pval": 265.00,
        "Cfed": 1.00,
        "Lstruct": 180.00,
        "unit": "$M",
        "source_note": "Chapter 11 Trustee initial findings: $265M owed vs $180M held ($85M gap).",
    },
    {
        "label": "Synapse FBO Gap + Synthetic Cfed Stress (Cfed=1.25)",
        "entity": "Synapse Financial Technologies (Stress 1.25x)",
        "data_vintage": "2024-06-07",
        "mode": "solve_delta",
        "Pval": 265.00,
        "Cfed": 1.25,
        "Lstruct": 180.00,
        "unit": "$M",
        "source_note": "Synthetic implicit federal-backstop divisor stress below 265/180 ceiling.",
    },
    {
        "label": "Synapse FBO Gap + Synthetic Cfed Ceiling Breach (Cfed=1.50)",
        "entity": "Synapse Financial Technologies (Stress 1.50x)",
        "data_vintage": "2024-06-07",
        "mode": "solve_delta",
        "Pval": 265.00,
        "Cfed": 1.50,
        "Lstruct": 180.00,
        "unit": "$M",
        "source_note": "Exceeds Cfed ceiling 265/180=1.4722 -> flags out_of_range=True.",
    },
    {
        "label": "Synapse FBO Freeze (Oct 22, 2024 11th Status Report)",
        "entity": "Synapse / Evolve & Lineage Partner Banks",
        "data_vintage": "2024-10-22",
        "mode": "solve_delta",
        "Pval": 219.08,
        "Cfed": 1.00,
        "Lstruct": 165.60,
        "unit": "$M",
        "source_note": "$219.08M held at trustee appt vs $165.60M distributed (~$53.48M frozen).",
    },
    {
        "label": "PayPal Holdings Custodial Line Pair (Sep 30, 2026 Q3 Release)",
        "entity": "PayPal Holdings, Inc. (PYPL)",
        "data_vintage": "2026-09-30",
        "mode": "solve_delta",
        "Pval": 40924.00,
        "Cfed": 1.00,
        "Lstruct": 38424.00,
        "unit": "$M",
        "source_note": "Funds payable ($40,924M) vs funds receivable ($38,424M); omits full Form 10-Q current assets.",
    },
    {
        "label": "PayPal Holdings Net Corporate Liquidity (Sep 30, 2026 Leverage Test)",
        "entity": "PayPal Holdings, Inc. (PYPL)",
        "data_vintage": "2026-09-30",
        "mode": "operator",
        "Pval": 15100.00,
        "Cfed": 1.894,
        "delta": 0.10,
        "unit": "$M",
        "source_note": "Cash+Inv=$15.1B, Cfed=1+13.5/15.1=1.894, illustrative delta=0.10.",
    },
]


def audit_fbo_custodial_batch(
    records: list[dict[str, Any]],
    *,
    disclosure_texts: dict[str, str] | None = None,
) -> dict[str, Any]:
    """
    v1.2 FBO Bank & Payment-Processor Stress-Test Batch Runner.

    Track A (Accounting, PROPOSED-MEASUREMENT, NOT IN SOURCE):
      - mode == "solve_delta": requires Pval (ledger owed), Cfed, Lstruct (attested bank cash).
      - mode == "operator": requires Pval, Cfed, delta -> computes Lstruct.
    Track B (Quarantined Governance Flag, PROPOSED PROXY, NOT IN SOURCE):
      - If disclosure_texts maps record label/entity -> normalized filing/contract text,
        computes hedged discretion metrics via AmongOtherThings_v12 + 1,000-word gate,
        strictly quarantined from Track A solvency outputs.
    """
    disclosure_texts = disclosure_texts or {}
    audited_rows: list[dict[str, Any]] = []
    errors: list[dict[str, Any]] = []

    for idx, rec in enumerate(records):
        label = rec.get("label", f"fbo_row_{idx}") if isinstance(rec, dict) else f"fbo_row_{idx}"
        try:
            if not isinstance(rec, dict):
                raise ValueError("Record must be a dict.")
            mode = rec.get("mode", "solve_delta" if "Lstruct" in rec and "delta" not in rec else "operator")
            if mode == "solve_delta":
                res = solve_delta(rec["Pval"], rec["Cfed"], rec["Lstruct"])
                row_out = {
                    "label": label,
                    "entity": rec.get("entity", label),
                    "data_vintage": rec.get("data_vintage", "unspecified"),
                    "mode": "solve_delta",
                    "classification": "PROPOSED-MEASUREMENT, NOT IN SOURCE",
                    "Pval": res["Pval"],
                    "Cfed": res["Cfed"],
                    "Lstruct": res["Lstruct"],
                    "delta": round(res["delta"], 6),
                    "out_of_range": res["out_of_range"],
                    "warnings": list(res["warnings"]),
                    "unit": rec.get("unit", "$M"),
                    "source_note": rec.get("source_note", ""),
                }
            elif mode == "operator":
                res = douche_vibes_operator(rec["Pval"], rec["Cfed"], rec["delta"])
                row_out = {
                    "label": label,
                    "entity": rec.get("entity", label),
                    "data_vintage": rec.get("data_vintage", "unspecified"),
                    "mode": "operator",
                    "classification": "PROPOSED-MEASUREMENT, NOT IN SOURCE",
                    "Pval": res["Pval"],
                    "Cfed": res["Cfed"],
                    "Lstruct": round(res["Lstruct"], 6),
                    "delta": res["delta"],
                    "out_of_range": False,
                    "warnings": list(res["warnings"]),
                    "unit": rec.get("unit", "$M"),
                    "source_note": rec.get("source_note", ""),
                }
            else:
                raise ValueError(f"Unsupported audit mode: {mode!r}")

            # Optional Track B governance flag — quarantined, never alters Track A math
            text_blob = disclosure_texts.get(label) or disclosure_texts.get(row_out["entity"])
            if text_blob is not None:
                row_out["track_b_governance_flag"] = estimate_delta_from_text(
                    text_blob, enforce_word_gate=True, include_inflected_sentiment=True
                )

            audited_rows.append(row_out)
        except Exception as ex:  # noqa: BLE001
            errors.append({"label": label, "row_index": idx, "error": str(ex)})

    # Rank highest custodial decay / boundary breaches first
    audited_rows.sort(
        key=lambda r: (
            not r["out_of_range"],
            -r["delta"],
            r["Lstruct"],
        )
    )

    valid_deltas = [r["delta"] for r in audited_rows if not r["out_of_range"]]
    summary = {
        "total_records": len(records),
        "valid_audited": len(audited_rows),
        "errors_count": len(errors),
        "out_of_range_count": sum(1 for r in audited_rows if r["out_of_range"]),
        "high_decay_ge_0_25_count": sum(1 for r in audited_rows if r["delta"] >= 0.25),
        "critical_decay_ge_0_90_count": sum(1 for r in audited_rows if r["delta"] >= 0.90),
        "mean_in_range_delta": round(sum(valid_deltas) / len(valid_deltas), 6) if valid_deltas else None,
        "max_delta": round(max(r["delta"] for r in audited_rows), 6) if audited_rows else None,
        "epistemic_guardrail": (
            "Track A balance-sheet metrics are PROPOSED-MEASUREMENT, NOT IN SOURCE. "
            "Track B delta_proxy is quarantined as PROPOSED PROXY, NOT IN SOURCE."
        ),
    }

    return {"results": audited_rows, "errors": errors, "summary": summary}


# ---------------------------------------------------------------------------
# Tables 1-5 — derived from AUDITED_SPEECHES + VERIFIED_* constants above.
# ---------------------------------------------------------------------------

def verified_totals() -> dict[str, Any]:
    return dict(VERIFIED_TOTALS)


def by_speech() -> list[dict[str, Any]]:
    return [dict(r) for r in AUDITED_SPEECHES]


def by_year() -> list[dict[str, Any]]:
    from collections import defaultdict

    agg: dict[int, dict[str, int]] = defaultdict(lambda: {"speeches_with_hit": 0, "exact": 0})
    for r in AUDITED_SPEECHES:
        year = int(str(r["date"]).strip().split()[-1])
        agg[year]["speeches_with_hit"] += 1
        agg[year]["exact"] += r["exact"]
    return [
        {"year": y, "speeches_with_hit": v["speeches_with_hit"], "exact_count": v["exact"]}
        for y, v in sorted(agg.items())
    ]


def by_speaker() -> list[dict[str, Any]]:
    return [
        {
            "speaker": r["speaker"],
            "speeches": 1,
            "exact_count": r["exact"],
            "example_quote": r["first_quote"],
        }
        for r in AUDITED_SPEECHES
    ]


def by_context_type() -> dict[str, int]:
    return dict(VERIFIED_BY_CONTEXT_TYPE)


def what_this_means() -> list[str]:
    return [
        "Rhetorical work: It signals 'this list is illustrative, not exhaustive' while letting the speaker sound comprehensive.",
        "Used more for: In this audited sample, rulemaking summaries (7) > legislative summaries (4) = economic/policy framing (4) > enforcement/risk (3).",
        "How to read a sentence that starts with it: Treat what follows as ONE item from a larger set, not the whole set.",
    ]


# ---------------------------------------------------------------------------
# Unit tests: v1.0.0 (10 + extras) + v1.1.0 (DoucheVibes) + v1.2 (FBO / Gate / Inflection)
# ---------------------------------------------------------------------------

def run_unit_tests() -> None:
    """Run all v1.0.0, v1.1.0, and v1.2 unit tests. Raises AssertionError on failure."""
    # --- v1.0.0 AmongOtherThings 10 required tests + extras ---
    assert AmongOtherThings(SEED_TEXT)["exact_count"] == 1, "1 seed"
    assert AmongOtherThings("Among other things, the rules require...")["exact_count"] == 1, "2 comma"
    assert AmongOtherThings("AMONG OTHER THINGS the rule...")["exact_count"] == 1, "3 uppercase"
    assert AmongOtherThings("Among other things, A. Among other things, B.")["exact_count"] == 2, "4 two"

    r5 = AmongOtherThings("including, among other things, campaign contributions")
    assert r5["exact_count"] == 1 and r5["hits"][0]["type"] == "inclusive_variant", "5 inclusive"
    assert r5["inclusive_variant_count"] == 1, "5 inclusive count"

    assert AmongOtherThings("among others", include_sentiment=False)["total_count"] == 0, "6a off"
    r6 = AmongOtherThings("among others", include_sentiment=True)
    assert r6["sentiment_only_count"] == 1 and r6["total_count"] == 1, "6b on"

    r7 = AmongOtherThings("including, but not limited to", include_sentiment=True)
    assert r7["sentiment_only_count"] == 1, "7 including but not limited to"

    r8 = AmongOtherThings('He said "among other things"')
    assert r8["hits"][0]["type"] == "quoted", "8 quoted"
    assert r8["total_count"] == 0 and r8["quoted_count"] == 1, "8 excluded"

    assert AmongOtherThings("")["total_count"] == 0, "9 empty"
    assert AmongOtherThings("other things happened")["total_count"] == 0, "10 other things alone"
    assert AmongOtherThings(None)["total_count"] == 0, "extra None"
    assert AmongOtherThings(123)["total_count"] == 0, "extra non-str"
    assert AmongOtherThings("a-\nmong other things, it applies")["exact_count"] == 1, "extra hyphen"
    assert AmongOtherThings("among other\nthings, it applies")["exact_count"] == 1, "extra newline"
    assert AmongOtherThings("He said \u201chello\u201d. Among other things, the rule")["exact_count"] == 1, "extra curly"
    assert AmongOtherThings("He said \u201camong other things\u201d")["hits"][0]["type"] == "quoted", "extra curly quoted"

    # --- v1.1.0 DoucheVibes Operator calibration & guards ---
    assert math.isclose(douche_vibes_operator(100, 2, 0.25)["Lstruct"], 37.5), "v1.1 demo 37.5"
    assert math.isclose(douche_vibes_operator(100, 2, 0.0)["Lstruct"], 50.0), "v1.1 delta=0 -> 50.0"
    assert math.isclose(douche_vibes_operator(100, 2, 1.0)["Lstruct"], 0.0), "v1.1 delta=1 -> 0.0"
    assert math.isclose(douche_vibes_operator(100, 100, 0.1)["Lstruct"], 0.9), "v1.1 Cfed=100 -> 0.9"
    assert math.isclose(douche_vibes_operator(100, 4, 0.35)["Lstruct"], 16.25), "v1.1 board 16.25"

    for bad_args in [(100, 0, 0.1), (100, -1, 0.1), (100, 2, -0.01), (100, 2, 1.01), (True, 2, 0.1)]:
        try:
            douche_vibes_operator(*bad_args)  # type: ignore[arg-type]
            raise AssertionError(f"Expected ValueError for {bad_args}")
        except ValueError:
            pass

    sd_oor = solve_delta(100, 2, 100)
    assert sd_oor["out_of_range"] is True and sd_oor["delta"] < 0.0, "solve_delta out_of_range"
    assert math.isclose(solve_Pval(35.0, 4, 0.3)["Pval"], 200.0), "solve_Pval round-trip"
    assert math.isclose(solve_Cfed(200.0, 35.0, 0.3)["Cfed"], 4.0), "solve_Cfed round-trip"

    batch_out = douche_vibes_batch([
        {"label": "low", "Pval": 100, "Cfed": 2, "delta": 0.1},
        {"label": "high", "Pval": 100, "Cfed": 2, "delta": 0.95},
        {"label": "bad", "Pval": 100, "Cfed": 0, "delta": 0.1},
    ])
    assert batch_out["summary"]["most_vibe_decayed"] == "high", "batch sort"
    assert batch_out["summary"]["count_errors"] == 1, "batch error isolation"
    assert batch_out["summary"]["count_delta_ge_0_9"] == 1, "batch threshold count"

    # --- v1.2 Finite-verb inflection upgrade, 1,000-word gate, and FBO batch runner ---
    toast_snippet = (
        "Forward-looking statements in this report include, but are not limited to, "
        "expectations regarding merchant payment volume, settlement reserve adequacy, "
        "and platform transaction margins."
    )
    # v1.0.0 baseline preserves zero hit on finite-verb inflection; v1.2 captures it
    assert AmongOtherThings(toast_snippet, include_sentiment=True)["sentiment_only_count"] == 0, "v1.0 preserved"
    r_v12 = AmongOtherThings_v12(toast_snippet)
    assert r_v12["sentiment_only_count"] == 1 and r_v12["inflected_sentiment_count"] == 1, "v1.2 finite-verb match"

    # 1,000-word gate blocks short-text saturation
    gated_res = estimate_delta_from_text(SEED_TEXT, enforce_word_gate=True)
    assert gated_res["gated"] is True and gated_res["delta_proxy"] is None, "v1.2 1000-word gate active"
    assert gated_res["classification"] == "PROPOSED PROXY, NOT IN SOURCE", "proxy label intact"

    # Ungated reproduction confirms legacy saturation on 23-word seed
    ungated_res = estimate_delta_from_text(SEED_TEXT, enforce_word_gate=False)
    assert ungated_res["gated"] is False and ungated_res["delta_proxy"] == 1.0, "ungated seed saturation"

    # Long text (>=1,000 words) passes gate cleanly
    long_doc = ("Merchant agreements govern reserve timing and risk controls. " * 130) + toast_snippet
    long_res = estimate_delta_from_text(long_doc, enforce_word_gate=True)
    assert long_res["gated"] is False and long_res["word_count"] >= 1000, "long doc passes 1000-word gate"
    assert 0.0 < long_res["delta_proxy"] < 0.15, "long doc avoids saturation"

    # FBO stress-test batch runner verification against documented corpus figures
    fbo_res = audit_fbo_custodial_batch(
        DOCUMENTED_FBO_PROCESSOR_SCENARIOS,
        disclosure_texts={"PayPal Holdings Net Corporate Liquidity (Sep 30, 2026 Leverage Test)": long_doc},
    )
    assert fbo_res["summary"]["valid_audited"] == 6, "all 6 FBO scenarios audited"
    assert fbo_res["summary"]["out_of_range_count"] == 1, "Cfed=1.50 ceiling breach flagged"
    synapse_base = next(
        r for r in fbo_res["results"] if "Jun 7, 2024 Trustee Report" in r["label"]
    )
    assert math.isclose(synapse_base["delta"], 0.320755, abs_tol=1e-4), "Synapse delta=0.3208"
    pypl_liq = next(
        r for r in fbo_res["results"] if "Net Corporate Liquidity" in r["label"]
    )
    assert math.isclose(pypl_liq["Lstruct"], 7175.290391, abs_tol=1e-2), "PayPal Lstruct=$7,175.29M"
    assert pypl_liq["track_b_governance_flag"]["gated"] is False, "PayPal Track B flag attached"

    print(
        "All tests passed: 10 v1.0.0 tests (+ extras) + v1.1.0 DoucheVibes Operator tests "
        "+ v1.2 finite-verb inflection, 1,000-word gate, and FBO stress-test batch runner."
    )


def main() -> None:
    print(f"pompous_v1_2.py — {__trademark__} (v{__version__})")
    print("=" * 72)
    run_unit_tests()
    print()
    print("Executing FBO Bank & Payment-Processor Stress-Test Batch (Track A):")
    fbo = audit_fbo_custodial_batch(DOCUMENTED_FBO_PROCESSOR_SCENARIOS)
    for row in fbo["results"]:
        flag = " [OUT_OF_RANGE]" if row["out_of_range"] else ""
        print(
            f"  - {row['label']}: Pval={row['Pval']} {row['unit']}, "
            f"Cfed={row['Cfed']}, delta={row['delta']:.4f}, "
            f"Lstruct={row['Lstruct']:.2f} {row['unit']}{flag}"
        )
    print()
    print("Batch Summary:", fbo["summary"])


if __name__ == "__main__":
    main()