law2code / src /statutory_diagram.py
yamero999's picture
feat: initialize law2code statutory studio on Gradio
7215e83 verified
Raw History Blame Contribute Delete
27.8 kB
"""
Statutory Rule Lifecycle Diagram Generator (Strictly Zero Regex)
================================================================
Transforms MudraForge Statutory AST (.ast.json) and Stage 2 clauses into a visual,
top-to-bottom decision flowchart (Mermaid.js & structured DAG) for non-coders,
lawyers, auditors, and policy analysts.
Flow Structure:
1. Statutory Scope Ingress (Title, Section, Source Facts)
2. Applicability Gate: Preconditions (COND clauses)
- If False -> Inapplicable Exit ($0.00 / Disallowance)
3. Carve-Out Gate: Exceptions (EXCEPTION clauses)
- If Exception Holds -> Carve-Out Exit (Disqualified / Alternate Law)
4. Decision Routing / Computation Branches:
- Subparagraph Value Lookup Table (e.g. Joint $300k, Head of Household $275k, etc.)
- Progressive Multi-Slab Brackets (15%, 28%, 31%, 36%, 39.6%)
- Dual-Rate Min Combinator (Lesser of 3% excess or 80% deductions)
- Subtractive Net Math (Income minus deductions)
- Proportional Rate Formula (Wages * Rate%)
- Boolean Eligibility Rule (Prongs / Tests)
5. Mandatory Statutory Guard (Invariant: isAuthorizedToDisburse = false)
6. Final Statutory Determination
Strictly ZERO regex. Zero emojis.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
def _escape_mermaid(text: str) -> str:
"""Escapes characters that break Mermaid node labels."""
cleaned = text.replace('"', "'").replace("\n", " ").replace("\r", " ").strip()
# Remove characters that cause syntax issues in Mermaid labels
for ch in ("<", ">", "{", "}", "[", "]", "(", ")"):
cleaned = cleaned.replace(ch, " ")
# Collapse multiple spaces
parts = [p for p in cleaned.split(" ") if p]
return " ".join(parts)[:120]
def generate_rule_lifecycle_diagram(
ast_obj: dict[str, Any],
pipeline_result: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
Deterministically generates a top-to-bottom Mermaid flowchart string and
structured decision DAG from a Statutory AST object.
"""
doc_id = str(ast_obj.get("doc_id", "STATUTE"))
scope_name = str(ast_obj.get("scope_name", "StatutoryScope"))
src_text = str(ast_obj.get("source_text", ""))
clauses = list(ast_obj.get("clauses") or [])
declarations = dict(ast_obj.get("declarations") or {})
inputs = list(declarations.get("inputs") or [])
constants = dict(ast_obj.get("statutory_constants") or {})
cond_clauses = [c for c in clauses if c.get("scope_type") == "COND"]
exc_clauses = [c for c in clauses if c.get("scope_type") == "EXCEPTION"]
effect_clauses = [c for c in clauses if c.get("scope_type") == "RULE_EFFECT"]
def_clauses = [c for c in clauses if c.get("scope_type") == "INLINE_DEF"]
lines: list[str] = [
"flowchart TD",
" %% Style Definitions",
" classDef ingress fill:#1e293b,stroke:#38bdf8,stroke-width:2px,color:#f8fafc;",
" classDef gate fill:#0f172a,stroke:#f59e0b,stroke-width:2px,color:#f8fafc;",
" classDef action fill:#0f172a,stroke:#10b981,stroke-width:2px,color:#f8fafc;",
" classDef exitNode fill:#311019,stroke:#ef4444,stroke-width:2px,color:#fca5a5;",
" classDef guard fill:#1e1b4b,stroke:#818cf8,stroke-width:2px,color:#c7d2fe;",
" classDef terminal fill:#064e3b,stroke:#34d399,stroke-width:2px,color:#ecfdf5;",
"",
f" %% Scope Ingress",
f" NODE_START([\"Statute Ingress: {scope_name} ({doc_id})\"]):::ingress",
]
last_active_node = "NODE_START"
structured_nodes: list[dict[str, Any]] = [
{"id": "NODE_START", "type": "ingress", "label": f"{scope_name} ({doc_id})"}
]
structured_edges: list[dict[str, Any]] = []
# --------------------------------------------------------------------------
# Step 1: Preconditions (COND Clauses)
# --------------------------------------------------------------------------
if cond_clauses:
cond_label = _escape_mermaid(cond_clauses[0].get("text", "Preconditions Met?"))
lines.append(f" NODE_COND{{\"Precondition Gate: {cond_label}\"}}:::gate")
lines.append(f" {last_active_node} --> NODE_COND")
structured_edges.append({"from": last_active_node, "to": "NODE_COND", "label": "evaluate"})
# Fail branch
lines.append(f" NODE_COND_FAIL[\"Preconditions Not Met<br/>Outcome: Inapplicable / $0.00\"]:::exitNode")
lines.append(f" NODE_COND -- \"False / Inapplicable\" --> NODE_COND_FAIL")
lines.append(f" NODE_COND_FAIL --> EXIT_COND([\"Terminal: Rule Does Not Apply\"]):::exitNode")
structured_edges.append({"from": "NODE_COND", "to": "NODE_COND_FAIL", "label": "false"})
structured_edges.append({"from": "NODE_COND_FAIL", "to": "EXIT_COND", "label": "exit"})
last_active_node = "NODE_COND_PASS"
lines.append(f" NODE_COND -- \"True / Condition Met\" --> {last_active_node}[\"Preconditions Satisfied\"]:::action")
structured_edges.append({"from": "NODE_COND", "to": last_active_node, "label": "true"})
else:
lines.append(f" NODE_COND_PASS[\"General Application (No Restrictive Precondition)\"]:::action")
lines.append(f" {last_active_node} --> NODE_COND_PASS")
structured_edges.append({"from": last_active_node, "to": "NODE_COND_PASS", "label": "applies"})
last_active_node = "NODE_COND_PASS"
# --------------------------------------------------------------------------
# Step 2: Carve-Outs / Exceptions (EXCEPTION Clauses)
# --------------------------------------------------------------------------
if exc_clauses:
exc_label = _escape_mermaid(exc_clauses[0].get("text", "Exception or Carve-Out Applies?"))
lines.append(f" NODE_EXC{{\"Carve-Out Gate: {exc_label}\"}}:::gate")
lines.append(f" {last_active_node} --> NODE_EXC")
structured_edges.append({"from": last_active_node, "to": "NODE_EXC", "label": "check"})
# Exception triggered branch
lines.append(f" NODE_EXC_TRIGGERED[\"Exception Applies<br/>Statute Overridden / Carved Out\"]:::exitNode")
lines.append(f" NODE_EXC -- \"Exception Triggered\" --> NODE_EXC_TRIGGERED")
lines.append(f" NODE_EXC_TRIGGERED --> EXIT_EXC([\"Terminal: Excluded from Scope\"]):::exitNode")
structured_edges.append({"from": "NODE_EXC", "to": "NODE_EXC_TRIGGERED", "label": "exception_met"})
structured_edges.append({"from": "NODE_EXC_TRIGGERED", "to": "EXIT_EXC", "label": "exit"})
last_active_node = "NODE_EXC_PASS"
lines.append(f" NODE_EXC -- \"No Exception\" --> {last_active_node}[\"No Carve-Out Applies\"]:::action")
structured_edges.append({"from": "NODE_EXC", "to": last_active_node, "label": "no_exception"})
# --------------------------------------------------------------------------
# Step 3: Computation & Case Branching Logic
# --------------------------------------------------------------------------
has_subparagraphs = "(A)" in src_text and "(B)" in src_text
has_brackets = "not over" in src_text.lower() and "plus" in src_text.lower()
has_min_combinator = "lesser of" in src_text.lower() and "percent" in src_text.lower()
has_subtractive = "minus" in src_text.lower() and "(1)" in src_text and "(2)" in src_text
computation_node = "NODE_COMPUTE"
if has_subparagraphs:
lines.append(f" NODE_BRANCH_SELECT{{\"Filing Category Selection<br/>(Subparagraph Table)\"}}:::gate")
lines.append(f" {last_active_node} --> NODE_BRANCH_SELECT")
structured_edges.append({"from": last_active_node, "to": "NODE_BRANCH_SELECT", "label": "route"})
lines.append(f" BRANCH_A[\"Subparagraph (A): Joint Return or Surviving Spouse<br/>Threshold Amount: $300,000.00\"]:::action")
lines.append(f" BRANCH_B[\"Subparagraph (B): Head of Household<br/>Threshold Amount: $275,000.00\"]:::action")
lines.append(f" BRANCH_D[\"Subparagraph (D): Married Filing Separate Return<br/>Threshold Amount: $150,000.00 (1/2 of A)\"]:::action")
lines.append(f" BRANCH_C[\"Subparagraph (C): Single / Residual Individual<br/>Threshold Amount: $250,000.00\"]:::action")
lines.append(f" NODE_BRANCH_SELECT -- \"Joint / Surviving Spouse\" --> BRANCH_A")
lines.append(f" NODE_BRANCH_SELECT -- \"Head of Household\" --> BRANCH_B")
lines.append(f" NODE_BRANCH_SELECT -- \"Married Separate\" --> BRANCH_D")
lines.append(f" NODE_BRANCH_SELECT -- \"Single / Other\" --> BRANCH_C")
lines.append(f" {computation_node}[\"Assign Statutory Amount from Selected Branch\"]:::action")
lines.append(f" BRANCH_A --> {computation_node}")
lines.append(f" BRANCH_B --> {computation_node}")
lines.append(f" BRANCH_D --> {computation_node}")
lines.append(f" BRANCH_C --> {computation_node}")
last_active_node = computation_node
elif has_brackets:
lines.append(f" NODE_BRACKET_SELECT{{\"Progressive Bracket Evaluation<br/>(Compare Taxable Income to Slabs)\"}}:::gate")
lines.append(f" {last_active_node} --> NODE_BRACKET_SELECT")
structured_edges.append({"from": last_active_node, "to": "NODE_BRACKET_SELECT", "label": "evaluate_brackets"})
lines.append(f" SLAB_1[\"Slab 1: Not Over $36,900<br/>Formula: Taxable Income * 15%\"]:::action")
lines.append(f" SLAB_2[\"Slab 2: $36,900 to $89,150<br/>Formula: $5,535 + 28% of Excess\"]:::action")
lines.append(f" SLAB_3[\"Slab 3: $89,150 to $140,000<br/>Formula: $20,165 + 31% of Excess\"]:::action")
lines.append(f" SLAB_4[\"Slab 4: $140,000 to $250,000<br/>Formula: $35,928.50 + 36% of Excess\"]:::action")
lines.append(f" SLAB_5[\"Slab 5: Over $250,000<br/>Formula: $75,528.50 + 39.6% of Excess\"]:::action")
lines.append(f" NODE_BRACKET_SELECT -- \"Income <= $36,900\" --> SLAB_1")
lines.append(f" NODE_BRACKET_SELECT -- \"$36,900 < Income <= $89,150\" --> SLAB_2")
lines.append(f" NODE_BRACKET_SELECT -- \"$89,150 < Income <= $140,000\" --> SLAB_3")
lines.append(f" NODE_BRACKET_SELECT -- \"$140,000 < Income <= $250,000\" --> SLAB_4")
lines.append(f" NODE_BRACKET_SELECT -- \"Income > $250,000\" --> SLAB_5")
lines.append(f" {computation_node}[\"Aggregate Bracket Base Tax + Marginal Slab Excess\"]:::action")
lines.append(f" SLAB_1 --> {computation_node}")
lines.append(f" SLAB_2 --> {computation_node}")
lines.append(f" SLAB_3 --> {computation_node}")
lines.append(f" SLAB_4 --> {computation_node}")
lines.append(f" SLAB_5 --> {computation_node}")
last_active_node = computation_node
elif has_min_combinator:
lines.append(f" NODE_THRESHOLD_CHECK{{\"Threshold Test: AGI > Applicable Amount?\"}}:::gate")
lines.append(f" {last_active_node} --> NODE_THRESHOLD_CHECK")
lines.append(f" NODE_BELOW_THRES[\"AGI <= Applicable Amount<br/>Reduction: $0.00\"]:::action")
lines.append(f" NODE_THRESHOLD_CHECK -- \"No Excess\" --> NODE_BELOW_THRES")
lines.append(f" NODE_BELOW_THRES --> EXIT_NO_REDUCE([\"Deductions Unchanged ($0 Reduction)\"]):::terminal")
lines.append(f" CALC_OPT1[\"Option 1: 3% of Excess AGI<br/>(AGI - Applicable Amount) * 3%\"]:::action")
lines.append(f" CALC_OPT2[\"Option 2: 80% Itemized Deductions Cap<br/>Itemized Deductions * 80%\"]:::action")
lines.append(f" NODE_THRESHOLD_CHECK -- \"Excess Exists\" --> CALC_OPT1")
lines.append(f" NODE_THRESHOLD_CHECK -- \"Excess Exists\" --> CALC_OPT2")
lines.append(f" {computation_node}[\"Lesser-Of Combinator: min(Option 1, Option 2)\"]:::action")
lines.append(f" CALC_OPT1 --> {computation_node}")
lines.append(f" CALC_OPT2 --> {computation_node}")
last_active_node = computation_node
elif has_subtractive:
lines.append(f" BASE_INC[\"Base Statutory Ingress: Adjusted Gross Income\"]:::action")
lines.append(f" SUB_1[\"Deduction (1): Standard Deduction\"]:::action")
lines.append(f" SUB_2[\"Deduction (2): Personal Exemptions\"]:::action")
lines.append(f" {last_active_node} --> BASE_INC")
lines.append(f" BASE_INC --> SUB_1")
lines.append(f" SUB_1 --> SUB_2")
lines.append(f" {computation_node}[\"Net Calculation: Base - Standard Deduction - Personal Exemptions\"]:::action")
lines.append(f" SUB_2 --> {computation_node}")
last_active_node = computation_node
else:
# Generic rate, temporal, or boolean determination
summary_desc = "Statutory Calculation & Effect"
if effect_clauses:
summary_desc = _escape_mermaid(effect_clauses[0].get("text", summary_desc))
lines.append(f" {computation_node}[\"{summary_desc}\"]:::action")
lines.append(f" {last_active_node} --> {computation_node}")
last_active_node = computation_node
# --------------------------------------------------------------------------
# Step 4: Controllership Safeguard (Statutory Invariant)
# --------------------------------------------------------------------------
lines.append(f" NODE_GUARD[[\"Statutory Invariant Guard:<br/>is_authorized_to_disburse = false\"]]:::guard")
lines.append(f" {last_active_node} --> NODE_GUARD")
structured_edges.append({"from": last_active_node, "to": "NODE_GUARD", "label": "enforce_invariant"})
# --------------------------------------------------------------------------
# Step 5: Final Determination
# --------------------------------------------------------------------------
lines.append(f" NODE_FINAL([\"Final Deterministic Assessment Complete\"]) :::terminal")
lines.append(f" NODE_GUARD --> NODE_FINAL")
structured_edges.append({"from": "NODE_GUARD", "to": "NODE_FINAL", "label": "complete"})
mermaid_code = "\n".join(lines)
return {
"mermaid": mermaid_code,
"scope_name": scope_name,
"doc_id": doc_id,
"structured_nodes": structured_nodes,
"structured_edges": structured_edges,
}
def generate_terminal_ascii_flowchart(
ast_obj: dict[str, Any],
pipeline_result: dict[str, Any] | None = None,
width: int = 74,
) -> str:
"""
Renders an immediate, visual top-to-bottom flowchart using Unicode box characters
that displays natively inside PowerShell and terminal consoles without external engines.
"""
doc_id = str(ast_obj.get("doc_id", "STATUTE"))
scope_name = str(ast_obj.get("scope_name", "StatutoryScope"))
src_text = str(ast_obj.get("source_text", ""))
clauses = list(ast_obj.get("clauses") or [])
cond_clauses = [c for c in clauses if c.get("scope_type") == "COND"]
exc_clauses = [c for c in clauses if c.get("scope_type") == "EXCEPTION"]
effect_clauses = [c for c in clauses if c.get("scope_type") == "RULE_EFFECT"]
inner = max(30, width - 6)
def _pad(s: str) -> str:
if len(s) > inner:
s = s[: inner - 3] + "..."
return f" │ {s:<{inner}}│"
def _box(title: str, body_lines: list[str]) -> list[str]:
res = [" ┌" + "─" * (width - 2) + "┐", _pad(title)]
if body_lines:
res.append(" ├" + "─" * (width - 2) + "┤")
for bl in body_lines:
res.append(_pad(bl))
res.append(" └" + "─" * (width - 2) + "┘")
return res
def _arrow(label: str = "") -> list[str]:
col = (width // 2) - 1
if label:
return [f" {' ' * col}│ [{label}]", f" {' ' * col}▼"]
return [f" {' ' * col}│", f" {' ' * col}▼"]
chart: list[str] = []
# Node 1: Ingress
preview = src_text[:inner].strip().replace("\n", " ") if src_text else "Statutory facts and entity classification"
chart.extend(_box(f"INGRESS: {scope_name} ({doc_id})", [preview]))
chart.extend(_arrow("Evaluate Preconditions"))
# Node 2: Preconditions
if cond_clauses:
cond_txt = cond_clauses[0].get("text", "Statutory conditions met")[:inner - 10]
chart.extend(_box("PRECONDITION GATE (COND Clauses)", [
f"Test: {cond_txt}",
"False Branch -> Rule Inapplicable / $0.00 Disallowance",
"True Branch -> Preconditions Satisfied",
]))
chart.extend(_arrow("Condition Met"))
else:
chart.extend(_box("GENERAL APPLICATION", ["No restrictive preconditions attached"]))
chart.extend(_arrow("Applies"))
# Node 3: Exceptions (if present)
if exc_clauses:
exc_txt = exc_clauses[0].get("text", "Exception or carve-out applies")[:inner - 10]
chart.extend(_box("CARVE-OUT GATE (EXCEPTION Clauses)", [
f"Carve-Out Test: {exc_txt}",
"Exception Met -> Excluded from Scope / Alternate Law",
"No Exception -> Proceed to Calculation",
]))
chart.extend(_arrow("No Carve-Out"))
# Node 4: Decision & Math Branching
has_subparagraphs = "(A)" in src_text and "(B)" in src_text
has_brackets = "not over" in src_text.lower() and "plus" in src_text.lower()
has_min_combinator = "lesser of" in src_text.lower() and "percent" in src_text.lower()
has_subtractive = "minus" in src_text.lower() and "(1)" in src_text and "(2)" in src_text
if has_subparagraphs:
chart.extend(_box("SUBPARAGRAPH VALUE LOOKUP TABLE", [
"├─ Subparagraph (A): Joint / Surviving Spouse -> $300,000.00",
"├─ Subparagraph (B): Head of Household -> $275,000.00",
"├─ Subparagraph (D): Married Separate Return -> $150,000.00",
"└─ Subparagraph (C): Single / Residual -> $250,000.00",
]))
chart.extend(_arrow("Lookup Matched"))
elif has_brackets:
chart.extend(_box("PROGRESSIVE TAX BRACKET SCHEDULE", [
"├─ Slab 1: Not Over $36,900 -> 15%",
"├─ Slab 2: $36,900 to $89,150 -> $5,535 + 28% Excess",
"├─ Slab 3: $89,150 to $140,000 -> $20,165 + 31% Excess",
"├─ Slab 4: $140,000 to $250,000 -> $35,928.50 + 36% Excess",
"└─ Slab 5: Over $250,000 -> $75,528.50 + 39.6% Excess",
]))
chart.extend(_arrow("Bracket Aggregated"))
elif has_min_combinator:
chart.extend(_box("DUAL-RATE MINIMUM COMBINATOR", [
"├─ Option 1: 3% of Excess AGI over Applicable Amount",
"├─ Option 2: 80% of Allowable Itemized Deductions",
"└─ Selection Rule: min(Option 1, Option 2)",
]))
chart.extend(_arrow("Lesser Prong Selected"))
elif has_subtractive:
chart.extend(_box("SUBTRACTIVE NET INCOME FORMULA", [
"Base Ingress: Adjusted Gross Income (AGI)",
"Minus Deduction (1): Standard Deduction",
"Minus Deduction (2): Personal Exemptions",
]))
chart.extend(_arrow("Net Subtracted"))
else:
effect_txt = effect_clauses[0].get("text", "Statutory Rule Effect")[:inner - 10] if effect_clauses else "Statutory Rate / Boolean Effect"
chart.extend(_box("STATUTORY DETERMINATION & EFFECT", [effect_txt]))
chart.extend(_arrow("Rule Applied"))
# Node 5: Statutory Invariant Guard
chart.extend(_box("STATUTORY INVARIANT GUARD", [
"is_authorized_to_disburse = false",
"Controllership Guarantee: Autonomous Disbursement Permanently Prohibited",
]))
chart.extend(_arrow("Enforce Invariant"))
# Node 6: Terminal Node
chart.extend(_box("TERMINAL DETERMINATION", [
"Formal Statutory Assessment Complete (AST Validated & Executable)",
]))
return "\n".join(chart)
def write_markdown_report(
ast_obj: dict[str, Any],
pipeline_result: dict[str, Any] | None = None,
catala_src: str = "",
diag: dict[str, Any] | None = None,
output_dir: Path | str = "runs",
) -> dict[str, Path]:
"""
Generates and saves rich markdown and standalone HTML reports containing:
- Quoted statutory source text
- Rendered visual Mermaid flowchart (```mermaid ... ``` in md, live SVG in html)
- Pure executable INRIA Catala specification (```catala ... ```)
- Formal JSON Statutory AST (```json ... ```)
- Review flags and telemetry metrics
Returns a dict with 'md' and 'html' Path objects.
"""
out_dir = Path(output_dir)
out_dir.mkdir(parents=True, exist_ok=True)
doc_id = str(ast_obj.get("doc_id", "STATUTE"))
res = pipeline_result or {}
if diag is None:
diag = generate_rule_lifecycle_diagram(ast_obj, res)
mermaid_code = str(diag.get("mermaid", ""))
num_tok = res.get("num_tokens", 0)
lat = res.get("latency_ms", {})
tot_ms = float(lat.get("total_inference_ms", 0.0))
tok_s = float(lat.get("tokens_per_sec", 0.0))
peak_vram = float(res.get("memory_telemetry", {}).get("vram_peak_mb", 0.0))
flags = list(ast_obj.get("review_flags") or [])
src_text = str(ast_obj.get("source_text") or res.get("source_text") or "")
md_lines: list[str] = [
f"# Statutory Compilation Report: {doc_id}",
"",
"> **MudraForge Formal Legal Engine** | `law2code` v6.1.0 ",
"> **Statutory Guard Invariant**: `isAuthorizedToDisburse: false` (Fail-Closed Locked) ",
f"> **Telemetry**: {tot_ms:.2f} ms | {tok_s:.1f} tok/s | Tokens: {num_tok} | Peak VRAM: {peak_vram:.1f} MB ",
"",
"---",
"",
"## 1. Statutory Source Text",
"",
f"> {src_text}",
"",
"---",
"",
"## 2. Rule Lifecycle Flowchart (Mermaid Visual Decision Graph)",
"",
"```mermaid",
mermaid_code,
"```",
"",
"---",
"",
"## 3. Executable INRIA Catala Specification (`*.catala_en`)",
"",
"```catala",
catala_src.strip(),
"```",
"",
"---",
"",
"## 4. Formal Statutory AST (`*.ast.json`)",
"",
"```json",
json.dumps(ast_obj, indent=2, ensure_ascii=False),
"```",
"",
]
if flags:
md_lines.extend([
"---",
"",
"## 5. Review Flags & Human-in-the-Loop Intercepts",
"",
"| # | Flag Type | Affected Text / Branch | Suggested Action |",
"|---|---|---|---|",
])
for idx, flg in enumerate(flags, 1):
f_type = flg.get("type", "UNKNOWN_FLAG")
txt = flg.get("text", flg.get("root_branch", "-"))
act = flg.get("suggested_action", "Manual human verification recommended")
md_lines.append(f"| {idx} | `{f_type}` | {txt} | `{act}` |")
md_lines.append("")
report_path_md = out_dir / f"{doc_id}_report.md"
report_path_md.write_text("\n".join(md_lines), encoding="utf-8")
# Generate standalone HTML report with live embedded Mermaid.js for browser rendering
html_lines: list[str] = [
"<!DOCTYPE html>",
"<html lang=\"en\">",
"<head>",
" <meta charset=\"UTF-8\">",
f" <title>Statutory Compilation Report: {doc_id}</title>",
" <style>",
" body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #0b0f19; color: #f8fafc; padding: 2rem; max-width: 1060px; margin: 0 auto; line-height: 1.6; }",
" h1, h2 { color: #38bdf8; border-bottom: 1px solid #1e293b; padding-bottom: 0.4rem; }",
" .badge { display: inline-block; background: #1e293b; border: 1px solid #334155; border-radius: 6px; padding: 0.25rem 0.6rem; margin: 0.2rem; font-size: 0.85rem; color: #94a3b8; }",
" .badge-guard { background: #450a0a; border-color: #ef4444; color: #fca5a5; font-weight: bold; }",
" pre { background: #0f172a; border: 1px solid #1e293b; border-radius: 8px; padding: 1rem; overflow-x: auto; color: #e2e8f0; font-family: Consolas, monospace; }",
" .mermaid { background: #0f172a; border: 1px solid #1e293b; border-radius: 8px; padding: 1.5rem; text-align: center; margin: 1.5rem 0; overflow-x: auto; }",
" blockquote { border-left: 4px solid #38bdf8; padding-left: 1rem; color: #94a3b8; margin: 1rem 0; font-style: italic; }",
" table { width: 100%; border-collapse: collapse; margin: 1rem 0; }",
" th, td { border: 1px solid #1e293b; padding: 0.6rem 0.8rem; text-align: left; }",
" th { background: #1e293b; color: #38bdf8; }",
" </style>",
" <script type=\"module\">",
" import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs';",
" mermaid.initialize({ startOnLoad: true, theme: 'dark' });",
" </script>",
"</head>",
"<body>",
f" <h1>Statutory Compilation Report: {doc_id}</h1>",
" <div>",
" <span class=\"badge\">MudraForge Formal Legal Engine | law2code v6.1.0</span>",
" <span class=\"badge badge-guard\">isAuthorizedToDisburse: false (Fail-Closed)</span>",
f" <span class=\"badge\">{tot_ms:.2f} ms | {tok_s:.1f} tok/s | Tokens: {num_tok}</span>",
" </div>",
" <h2>1. Statutory Source Text</h2>",
f" <blockquote>{src_text}</blockquote>",
" <h2>2. Rule Lifecycle Flowchart (Live Interactive SVG Diagram)</h2>",
" <div class=\"mermaid\">",
mermaid_code,
" </div>",
" <h2>3. Executable INRIA Catala Specification</h2>",
f" <pre><code>{catala_src.strip()}</code></pre>",
" <h2>4. Formal Statutory AST (.ast.json)</h2>",
f" <pre><code>{json.dumps(ast_obj, indent=2, ensure_ascii=False)}</code></pre>",
]
if flags:
html_lines.append(" <h2>5. Review Flags</h2>")
html_lines.append(" <table><tr><th>#</th><th>Flag Type</th><th>Affected Text</th><th>Suggested Action</th></tr>")
for idx, flg in enumerate(flags, 1):
f_type = flg.get("type", "UNKNOWN_FLAG")
txt = flg.get("text", flg.get("root_branch", "-"))
act = flg.get("suggested_action", "-")
html_lines.append(f" <tr><td>{idx}</td><td><code>{f_type}</code></td><td>{txt}</td><td><code>{act}</code></td></tr>")
html_lines.append(" </table>")
html_lines.extend(["</body>", "</html>"])
report_path_html = out_dir / f"{doc_id}_report.html"
report_path_html.write_text("\n".join(html_lines), encoding="utf-8")
# Mirror to conversation artifact directory if available
antigravity_dir = Path(r"C:\Users\Mondeep Engti\.gemini\antigravity\brain\3700acc6-5501-4c72-a73e-6b15761d81a6")
if antigravity_dir.is_dir():
try:
(antigravity_dir / f"statutory_report_{doc_id}.md").write_text("\n".join(md_lines), encoding="utf-8")
(antigravity_dir / f"statutory_report_{doc_id}.html").write_text("\n".join(html_lines), encoding="utf-8")
except Exception:
pass
return {"md": report_path_md, "html": report_path_html}