#!/usr/bin/env python3 r""" Forensic Statutory Stylometry & Structural Hazard Extractor Target: Delaware Draft HB — Artificial Intelligence Regulatory Sandbox & AIC Act (June 2, 2026, 36 pp.) Attestation: probabilistic_structural (Sweetbrier Nodes 0 / 1 / 2) """ import csv import hashlib import json import math import os import re from collections import Counter import fitz import numpy as np PDF_PATH = os.environ.get("DE_AIC_PDF", os.path.join(os.path.dirname(os.path.abspath(__file__)), "HB-re-Artificial-Intelligence-Regulatory-Sandbox-Company-1.pdf")) OUT_DIR = os.path.dirname(os.path.abspath(__file__)) # Top statutory & English function words for Burrows' Classic Delta & Cosine Delta FUNCTION_WORDS = [ "the", "of", "to", "or", "and", "a", "in", "by", "an", "under", "for", "is", "this", "as", "that", "not", "with", "be", "if", "any", "may", "must", "shall", "from", "on", "other", "at", "its", "has", "which", "all", "who", "no", "such", "than", "unless", "only", "into", "after", "before", "within", "without", "solely", "upon", "whether", "each", "either", "both", "during", "through", ] AI_BESPOKE_MARKERS = ( "ai agent", "artificial intelligence", "sandbox", "adequately capitalized", "minimum capital amount", "presumed to have intended", "presumed to know", "instrumentality", "without routine human supervision", "predetermined goals", "not a public record", "freedom of information", ) SHIELD_EXCULPATORY_PATTERNS = ( r"\bnot personally liable\b", r"\bnot liable\b", r"\bsolely the\b", r"\bshield\w*\b", r"\bexempt\b", r"\bnot a public record\b", r"\bconfidential\b", r"\bpresumed to (?:know|have intended)\b", r"\bwithout routine human supervision\b", r"\bdeemed to have consented\b", r"\bno duty\b", ) ACCOUNTABILITY_DUTY_PATTERNS = ( r"\bpersonally liable\b", r"\bpublicly available\b", r"\bpublic record\b", r"\bindependent audit\b", r"\binsurance\b", r"\bminimum capital of \$[0-9]", r"\bhuman supervision\b", ) def clean_page_text(raw_page: str) -> str: lines = [] for ln in raw_page.splitlines(): s = ln.strip() if not s: continue if s.startswith("DLS : MJC : AF") or s == "4801530178": continue if re.match(r"^Page\s+\d+\s+of\s+36$", s): continue if s.startswith("Draft: 06/02/2026"): continue # Strip standalone margin line numbers (1..1060) if re.match(r"^\d{1,4}$", s): continue lines.append(s) return "\n".join(lines) def tokenize_words(text: str): return re.findall(r"\b[a-z][a-z'-]*\b", text.lower()) def compute_mattr(words, window: int = 100) -> float: if not words: return 0.0 if len(words) <= window: return len(set(words)) / len(words) ratios = [ len(set(words[i:i + window])) / window for i in range(len(words) - window + 1) ] return float(sum(ratios) / len(ratios)) def compute_sentence_stats(text: str): # Protect '§ 81-101.' and 'U.S.C.' periods before splitting sentences protected = re.sub(r"(§\s*[0-9A-Za-z-]+)\.", r"\1", text) protected = protected.replace("U.S.C.", "USC").replace("et seq.", "et seq") sents = [s.strip() for s in re.split(r"[.;!?]+", protected) if len(s.strip().split()) >= 4] if not sents: return 0.0, 0.0, 0.0 lengths = [len(s.split()) for s in sents] mean_l = float(np.mean(lengths)) sd_l = float(np.std(lengths)) # Goh-Barabasi burstiness B = (sigma - mu) / (sigma + mu) in [-1, 1] burstiness = (sd_l - mean_l) / (sd_l + mean_l) if (sd_l + mean_l) > 0 else 0.0 return mean_l, sd_l, float(burstiness) def classify_stratum(sec_id: str, title: str, body: str) -> str: low = f"{title} {body}".lower() if sec_id.startswith("80"): return "Ch80_Sandbox_Template" if sec_id == "SYNOPSIS": return "Bill_Synopsis" # In Chapter 81, distinguish bespoke AI-Agent / Shield surgical sections from standard ULLCA chassis bespoke_hits = sum(1 for m in AI_BESPOKE_MARKERS if m in low) if sec_id in ("81-101", "81-102", "81-103", "81-201", "81-204", "81-205", "81-301", "81-303", "81-401", "81-405", "81-802") or bespoke_hits >= 2: return "Ch81_Bespoke_AI_Shield_Surgery" return "Ch81_ULLCA_Mechanical_Boilerplate" def main(): os.makedirs(OUT_DIR, exist_ok=True) doc = fitz.open(PDF_PATH) pdf_sha256 = hashlib.sha256(open(PDF_PATH, "rb").read()).hexdigest() cleaned_pages = [clean_page_text(p.get_text("text")) for p in doc] full_clean = "\n".join(cleaned_pages) with open(os.path.join(OUT_DIR, "de_aic_bill_clean_text.txt"), "w", encoding="utf-8") as f: f.write(full_clean) # Extract Synopsis separately if present at end syn_idx = full_clean.find("SYNOPSIS") main_body = full_clean[:syn_idx] if syn_idx != -1 else full_clean synopsis_text = full_clean[syn_idx:] if syn_idx != -1 else "" # Split into statutory sections (§ 8001 .. § 81-904) sec_pattern = re.compile(r"(?:^|\n)§\s*(80\d{2}|81-\d{3})\.\s*([^\n]+)") matches = list(sec_pattern.finditer(main_body)) sections = [] for idx, m in enumerate(matches): sec_id = m.group(1).strip() sec_title = m.group(2).strip() start = m.end() end = matches[idx + 1].start() if idx + 1 < len(matches) else len(main_body) sec_body = main_body[start:end].strip() sections.append((sec_id, sec_title, sec_body)) if synopsis_text: sections.append(("SYNOPSIS", "Legislative Synopsis", synopsis_text)) rows = [] stratum_blobs = {} for sec_id, title, body in sections: words = tokenize_words(body) wc = len(words) if wc == 0: continue stratum = classify_stratum(sec_id, title, body) stratum_blobs.setdefault(stratum, []).extend(words) counts = Counter(words) must_c = counts["must"] shall_c = counts["shall"] may_c = counts["may"] # DLS Drafting Manual compliance index: share of 'shall' among mandatory modals (shall + must) shall_contamination = shall_c / max(1, (shall_c + must_c)) shield_hits = sum(len(re.findall(p, body, flags=re.IGNORECASE)) for p in SHIELD_EXCULPATORY_PATTERNS) duty_hits = sum(len(re.findall(p, body, flags=re.IGNORECASE)) for p in ACCOUNTABILITY_DUTY_PATTERNS) mean_sl, sd_sl, burst = compute_sentence_stats(body) mattr = compute_mattr(words, window=80) rows.append({ "section_id": sec_id, "title": title, "stratum": stratum, "word_count": wc, "mattr_80": round(mattr, 4), "avg_sentence_words": round(mean_sl, 2), "sd_sentence_words": round(sd_sl, 2), "burstiness": round(burst, 4), "must_count": must_c, "shall_count": shall_c, "may_count": may_c, "shall_ratio": round(shall_contamination, 4), "shield_secrecy_hits": shield_hits, "public_accountability_hits": duty_hits, "fw_counts": {fw: counts[fw] / wc * 1000.0 for fw in FUNCTION_WORDS}, }) # Compute Burrows' Classic Delta & Cosine Delta across the 3 main statutory strata # Using chunks of ~450 words per stratum for balanced variance estimation & permutation testing rng = np.random.default_rng(20261130) chunk_size = 450 chunks = [] for strat in ("Ch80_Sandbox_Template", "Ch81_Bespoke_AI_Shield_Surgery", "Ch81_ULLCA_Mechanical_Boilerplate"): wlist = stratum_blobs.get(strat, []) for i in range(0, len(wlist) - chunk_size + 1, chunk_size): seg = wlist[i:i + chunk_size] c = Counter(seg) vec = np.array([c[fw] / chunk_size * 1000.0 for fw in FUNCTION_WORDS], dtype=float) chunks.append((strat, vec)) mat = np.vstack([v for _, v in chunks]) mu = mat.mean(axis=0) sd = np.where(mat.std(axis=0, ddof=1) > 1e-9, mat.std(axis=0, ddof=1), 1.0) z_mat = (mat - mu) / sd strat_labels = [s for s, _ in chunks] unique_strata = ["Ch80_Sandbox_Template", "Ch81_Bespoke_AI_Shield_Surgery", "Ch81_ULLCA_Mechanical_Boilerplate"] centroids = { st: z_mat[[i for i, l in enumerate(strat_labels) if l == st]].mean(axis=0) for st in unique_strata } pairwise_delta = {} for i in range(len(unique_strata)): for j in range(i + 1, len(unique_strata)): s1, s2 = unique_strata[i], unique_strata[j] c1, c2 = centroids[s1], centroids[s2] burrows = float(np.mean(np.abs(c1 - c2))) cos_sim = float(np.dot(c1, c2) / (np.linalg.norm(c1) * np.linalg.norm(c2) + 1e-12)) cos_delta = 1.0 - cos_sim pairwise_delta[f"{s1}__VS__{s2}"] = { "burrows_delta": round(burrows, 4), "cosine_delta": round(cos_delta, 4), } # Exact 10,000-shuffle permutation test: Ch81_Bespoke_AI_Shield_Surgery vs Ch81_ULLCA_Mechanical_Boilerplate idx_bespoke = [i for i, l in enumerate(strat_labels) if l == "Ch81_Bespoke_AI_Shield_Surgery"] idx_ullca = [i for i, l in enumerate(strat_labels) if l == "Ch81_ULLCA_Mechanical_Boilerplate"] sub_z = z_mat[idx_bespoke + idx_ullca] n_b = len(idx_bespoke) obs_delta = float(np.mean(np.abs(sub_z[:n_b].mean(axis=0) - sub_z[n_b:].mean(axis=0)))) exceed = 0 n_perm = 10000 for _ in range(n_perm): perm = rng.permutation(len(sub_z)) d_p = float(np.mean(np.abs(sub_z[perm[:n_b]].mean(axis=0) - sub_z[perm[n_b:]].mean(axis=0)))) if d_p >= obs_delta: exceed += 1 perm_p_bespoke_vs_ullca = (exceed + 1) / (n_perm + 1) # Also permutation test: Ch80_Sandbox_Template vs Ch81_ULLCA_Mechanical_Boilerplate idx_ch80 = [i for i, l in enumerate(strat_labels) if l == "Ch80_Sandbox_Template"] sub_z2 = z_mat[idx_ch80 + idx_ullca] n_80 = len(idx_ch80) obs_delta_80 = float(np.mean(np.abs(sub_z2[:n_80].mean(axis=0) - sub_z2[n_80:].mean(axis=0)))) exceed2 = 0 for _ in range(n_perm): perm = rng.permutation(len(sub_z2)) d_p = float(np.mean(np.abs(sub_z2[perm[:n_80]].mean(axis=0) - sub_z2[perm[n_80:]].mean(axis=0)))) if d_p >= obs_delta_80: exceed2 += 1 perm_p_ch80_vs_ullca = (exceed2 + 1) / (n_perm + 1) # Stratum-level summary aggregates stratum_summary = {} for st in unique_strata + ["Bill_Synopsis"]: srows = [r for r in rows if r["stratum"] == st] if not srows: continue tot_w = sum(r["word_count"] for r in srows) tot_must = sum(r["must_count"] for r in srows) tot_shall = sum(r["shall_count"] for r in srows) tot_may = sum(r["may_count"] for r in srows) tot_shield = sum(r["shield_secrecy_hits"] for r in srows) tot_duty = sum(r["public_accountability_hits"] for r in srows) stratum_summary[st] = { "section_count": len(srows), "total_words": tot_w, "weighted_mattr_80": round(sum(r["mattr_80"] * r["word_count"] for r in srows) / tot_w, 4), "mean_sentence_words": round(float(np.mean([r["avg_sentence_words"] for r in srows])), 2), "must_count": tot_must, "shall_count": tot_shall, "may_count": tot_may, "shall_share_of_mandatory": round(tot_shall / max(1, tot_shall + tot_must), 4), "shield_secrecy_hits": tot_shield, "public_accountability_hits": tot_duty, } # Check exact absence/presence of key structural constraints across entire 36-page bill low_full = full_clean.lower() structural_bombs = { "draft_control_header": "DLS : MJC : AF | Control #4801530178 | Draft 06/02/2026 06:40 PM", "total_pages": len(doc), "total_sections_parsed": len(rows), "total_clean_words": len(tokenize_words(full_clean)), "mentions_delaware_ch18_freedom_of_contract": ("freedom of contract" in low_full), "uses_ullca_902_esign_boilerplate": ("modifies, limits, or supersedes the electronic signatures" in low_full), "mentions_liability_insurance_requirement": ("liability insurance" in low_full or "malpractice insurance" in low_full), "mentions_cap_on_aics_per_member_or_agent": bool(re.search(r"may not (?:manage|form|organize) more than", low_full)), "flat_annual_tax_usd": 1000 if "$1,000" in full_clean else None, "foia_exemption_sec_8011": ("not a public record" in low_full or "§ 10002 of title 29" in low_full), "software_presumed_intent_sec_81_103f": ("presumed to have intended" in low_full), "anti_piercing_instrumentality_shield_sec_81_303c": ("instrumentality" in low_full), "human_acting_at_ai_direction_shield_sec_81_303c": ("at the direction of the aic" in low_full), "draft_typo_fees_owned_sec_81_802g": ("fees owned to the secretary of state" in low_full), } # Write CSV of all 70+ sections csv_path = os.path.join(OUT_DIR, "de_aic_sections_stylometry.csv") csv_fields = [ "section_id", "title", "stratum", "word_count", "mattr_80", "avg_sentence_words", "sd_sentence_words", "burstiness", "must_count", "shall_count", "may_count", "shall_ratio", "shield_secrecy_hits", "public_accountability_hits", ] with open(csv_path, "w", newline="", encoding="utf-8") as cf: w = csv.DictWriter(cf, fieldnames=csv_fields) w.writeheader() for r in rows: w.writerow({k: r[k] for k in csv_fields}) top_shield_sections = sorted(rows, key=lambda x: (x["shield_secrecy_hits"], x["word_count"]), reverse=True)[:10] top_shall_seams = [r for r in rows if r["shall_count"] > 0] report = { "attestation": "probabilistic_structural", "source_pdf": os.path.basename(PDF_PATH), "source_pdf_sha256": pdf_sha256, "structural_bombs": structural_bombs, "stratum_summary": stratum_summary, "stylometric_distances": pairwise_delta, "permutation_tests_10k": { "bespoke_ai_shield_vs_ullca_boilerplate": { "observed_burrows_delta": round(obs_delta, 4), "p_value": round(perm_p_bespoke_vs_ullca, 5), "chunks_compared": f"{n_b} vs {len(idx_ullca)} (450-word blocks)", }, "ch80_sandbox_vs_ullca_boilerplate": { "observed_burrows_delta": round(obs_delta_80, 4), "p_value": round(perm_p_ch80_vs_ullca, 5), "chunks_compared": f"{n_80} vs {len(idx_ullca)} (450-word blocks)", }, }, "shall_vs_must_splice_sections": [ {"section": r["section_id"], "title": r["title"], "stratum": r["stratum"], "shall": r["shall_count"], "must": r["must_count"]} for r in top_shall_seams ], "top_shield_and_secrecy_sections": [ {"section": r["section_id"], "title": r["title"], "stratum": r["stratum"], "shield_hits": r["shield_secrecy_hits"], "duty_hits": r["public_accountability_hits"]} for r in top_shield_sections if r["shield_secrecy_hits"] > 0 ], } json_path = os.path.join(OUT_DIR, "stylometric_findings.json") with open(json_path, "w", encoding="utf-8") as jf: json.dump(report, jf, indent=2) print("STYLOMETRY_OK | PDF_SHA256:", pdf_sha256[:16]) print(json.dumps(report, indent=2)) if __name__ == "__main__": main()