FLAGSHIP #7 · CLAUDE EVALUATION, CALIBRATION & HARNESS ENGINEERING ✓ GitHub Actions CI Passing ↗ MIT License · Python

Claude Extraction Eval & Confidence Calibration

Three-Package Anthropic Claude Evaluation & Observability Monorepo: Sliced Brier Confidence Calibration, Cross-Field Math Gates, Timeout Envelopes & 56.8% Context Compression

Claude Haiku 4.5Brier CalibrationStructured OutputsPytestMypySentence-TransformersPythonGitHub Actions
104 / 104
Monorepo Pytest Suite
0 Mypy & 0 Ruff Errors
0.865 Brier
Hidden Slice Overconfidence
Unmasked Behind 0.291 Aggregate
56.8%
Harness Token Compression
38.7k -> 16.7k (6/6 Eval Pass)
584 Bytes
Bounded O(1) Shift State
< 5 KB Ceiling + 30m Recovery
01 · Production Engineering Scorecard

Six-Pillar Production Readiness Matrix

How this system enforces security, observability, fault isolation, unit economics, and automated verification beyond notebook prototypes.

Confidence Calibration ✓ SLICED BRIER

calibration_report.py slices Brier scores by policy_type x field, unmasking 0.865 overconfidence (conf=0.93, acc=0.00) hidden in 0.291 aggregate Brier.

Error-Classified Retry ✓ 1 CALL VS 4

retry.py distinguishes permanent missing_source errors from transient format errors, halting futile retries after 1 API call instead of 4.

Cross-Model & Math Gates ✓ 2-MODEL + MATH

Combines blind second-model reviewer (reviewer.py) with Python cross-field paystub YTD arithmetic validation (-$1,250 mismatch caught, exit 1).

Timeout Fault Isolation ✓ ENVELOPED

readers.py isolates upstream timeouts inside ReaderResult envelopes (--simulate-timeout -> exit 0), preventing partial-row vector memory corruption.

Context & Loop Discipline ✓ -56.8% TOKENS

stop_reason-driven loops (AST-tested against hardcoded range(10) caps) + Case-Facts header + byte-exact active window compress context 56.8%.

Static & CI Verification ✓ 104 PYTESTS

3 independent packages (policy-extractor, mortgage-extractor, supply-chain-risk) verified by 104 tests, mypy strict typing, and recorded fixtures.

02 · Architecture & Control Flow

System Topology & Failure-Mode Lifecycles

End-to-end execution graph paired with nominal request flow and adversarial / degraded fault-handling paths.

flowchart LR
    subgraph P1["01 · Policy Extractor (45 Tests)"]
        E1["Claude Primary Extractor"] --> R1["Blind Second-Model Reviewer"]
        R1 --> B1["Policy x Field Sliced Brier\n(Caught 0.865 Umbrella Overconfidence)"]
    end
    subgraph P2["02 · Mortgage Validator (25 Tests)"]
        E2["2-Pass Doc Classifier"] --> A2["Python Cross-Field Math Gate\n(Caught -$1,250 YTD Mismatch)"]
    end
    subgraph P3["03 · Supply-Chain Synthesis (34 Tests)"]
        E3["Timeout-Isolated ReaderResult"] --> V3["MiniLM Vector Claim Corroboration"]
    end

✓ Nominal Production Request Path

  1. policy-extractor extracts structured insurance fields with Claude Haiku 4.5, runs blind second-model review (reviewer.py), and routes via 3-signal HITL router.
  2. mortgage-extractor executes a 2-pass classifier -> nullable doc-type schema -> deterministic Python YTD earnings validator (consistent: true, exit 0).
  3. supply-chain-risk ingests multi-source reader envelopes, deduplicates claims in all-MiniLM-L6-v2 vector memory, and corroborates dated supplier risks.
  4. calibration_report.py audits confidence vs. ground truth across every policy_type x field slice to tune auto-approve vs. human-review thresholds.

✕ Adversarial, Policy & Fault-Handling Paths

  • Source document missing endorsement section (POL-2025-009) classifies as missing_source and halts immediately after 1 call—zero wasted retry spend.
  • Perturbed paystub with -$1,250.00 line-item vs. YTD mismatch fails mortgage_extractor/validator.py deterministically (exit 1).
  • --simulate-timeout on a supply-chain feed degrades gracefully (exit 0), tagging [single source only] without polluting vector claim memory.
  • Umbrella policy exclusions with high model confidence (0.93) but 0.00 accuracy are caught by sliced Brier (0.865) and routed to mandatory human review.
03 · Code-Grounded Implementation

Production-Ready Technical Features

Every capability below links directly to the verified source module, policy configuration, or CI workflow in kenseiAmit/claude-extraction-eval-observability.

04 · Engineering Trade-Offs (ADRs)

Why This Architecture Over Naive Prototypes?

Key architectural decisions balancing determinism, latency, cost, privacy, and operational maintainability.

Architectural Decision Naive Prototype Anti-Pattern Production Engineering Choice & Outcome
Sliced (policy_type x field) Brier vs. Aggregate Confidence Threshold Auto-approving any extraction with confidence >= 0.90 based on a healthy 0.291 global Brier score. Per-slice Brier evaluation exposes umbrella / exclusions (conf=0.93, acc=0.00, Brier=0.865) and forces targeted HITL escalation.
Error-Classified Retry (missing_source Halt) vs. Blind Exponential Backoff Retrying every failed extraction 4 times with higher temperature—quadrupling latency and inducing hallucinated values when source text is absent. Immediate 1-call halt on missing_source vs. targeted schema repair on format errors.
ReaderResult Timeout Envelope vs. Uncaught Gather Exceptions Failing an entire multi-source risk report or writing half-parsed rows into vector memory when one upstream feed times out. Isolated timeout envelopes degrade cleanly (exit 0), preserve clean vector state, and surface explicit [single source only] provenance.
Structured # Case Facts Header + Verbatim Active Window Summarizing the entire conversation history uniformly, losing exact active payment error codes and structured status enums (eval_control Q6 regression). 204-token top # Case Facts + summarized resolved threads + byte-exact active thread (56.8% reduction, 6/6 eval pass).
05 · Verified Execution Evidence

Empirical Telemetry, Dashboards & Runtime Traces

Recorded execution traces, benchmark sweeps, and raw repository JSON artifacts.

06 · Reproduction & Verification Gates

Local Quick Start & Continuous Integration

GitHub Actions (ci.yml) runs pytest across all 3 packages (45 + 25 + 34 = 104 passed), mypy strict type checking (0 errors), ruff linting, and perturbation scripts.

Clone, Seed & Run Verification Suite
(cd packages/policy-extractor && pytest)
(cd packages/mortgage-extractor && pytest)
(cd packages/supply-chain-risk && pytest)
python evaluation/calibration_report.py
01 · Executive Value Brief

Commercial Thesis & P&L Impact

Insurance, mortgage, and supply-chain teams deploy LLM extraction to automate back-office document processing, only to get burned by 'confident hallucinations': an aggregate 0.291 Brier score looks safe for straight-through processing, yet hides catastrophic pockets like umbrella policy exclusions (93% model confidence, 0% accuracy) or -$1,250 paystub YTD mismatches. This 3-package monorepo makes high-speed automation financially safe—combining sliced calibration, blind 2-model review, deterministic math gates, 1-call missing-source halts, and 56.8% context compression.

✓ 100% Grounded in Verified Repository Benchmarks ·
02 · Commercial Risk vs. Production Unlock

Why Prototype Pilots Stall — And How This Architecture Unblocks Launch

Translating engineering guardrails, determinism, and cost controls into executive deployment readiness.

✕ Why Aggregate-Tested Document AI Causes Financial & Ops Losses

  • Global confidence thresholds (conf >= 0.90) auto-approve catastrophic edge slices (umbrella / exclusions: conf=0.93, acc=0.00).
  • Uniform exponential backoff retries missing document sections 4x—quadrupling API cost/latency and pressuring the LLM to invent fields.
  • Single-pass non-nullable schemas hallucinate values on W-2 vs. paystub variants, and miss -$1,250 cross-field arithmetic tampering.
  • Long-horizon agent harnesses either bloat past 38.7k tokens/turn or summarize away active error codes needed for resolution.

✓ Commercial Outcomes Delivered by This Architecture

  • Safe straight-through processing (STP): well-calibrated fields auto-clear while high-Brier/disagreement slices route to targeted human review.
  • 75% fewer wasted retry calls on incomplete customer uploads (missing_source halts in 1 call; format errors self-heal).
  • Zero arithmetic mortgage leakage: Python cross-field YTD validation (validator.py) halts inconsistent paystubs deterministically.
  • 56.8% lower multi-turn harness token cost + 100% report uptime under upstream supply-chain feed timeouts (ReaderResult).
03 · 1:1 Feature-to-Value Traceability

Production Feature → Business Value Mapping

Every production engineering feature in kenseiAmit/claude-extraction-eval-observability mapped directly to the commercial risk it eliminates and the measurable value it delivers.

Production Engineering Feature (Source) Business Risk / Bottleneck Eliminated Value Lever Quantified Business Outcome
policy_type × field Sliced Brier Calibration & Blind 2-Model Review
Auto-approving misread insurance policy exclusions (0.865 Brier) hidden behind a healthy 0.291 global average. Underwriting Loss Prevention Intercepts conf=0.93 / acc=0.00 overconfident pockets via 3-signal HITL routing while keeping clean slices automated.
Taxonomy-Driven Retry Controller (missing_source vs format)
Paying 4x LLM API cost & latency retrying documents that physically lack an endorsement page—and inducing hallucinated answers. API FinOps & Turnaround SLA 75% retry call reduction (1 call vs 4) on permanent omissions while preserving automated recovery on JSON format slips.
Two-Pass Nullable Schema & Python Mortgage YTD Validator
Altered or misextracted borrower paystubs (-$1,250.00 line-item vs. YTD discrepancy) slipping into loan underwriting. Fraud & Credit QA Eliminates forced-schema hallucinations via doc-type nullable contracts and blocks 100% of YTD arithmetic mismatches.
ReaderResult Timeout Envelopes & Date-Guarded Corroboration
One slow news feed crashing executive supply-chain briefings OR unverified single-source rumors triggering false ESCALATE alerts. Supply-Chain Continuity Graceful timeout isolation (exit 0, clean vector memory) + mandatory multi-source corroboration before supplier escalation.
stop_reason Loops, 56.8% Context Compression & 584B State
Multi-turn ops agents ballooning token bills (38.7k tokens) or losing exact payment error codes during context compaction. Agentic Unit Economics 56.8% context token cut (38.7k -> 16.7k) with 6/6 eval accuracy + O(1) (< 5 KB) 30-minute shift recovery.
104-Test Recorded-Fixture Monorepo (0 Mypy / Ruff Errors)
Slow, flaky, token-burning CI pipelines stalling engineering releases across multiple document-AI products. Engineering Velocity 104/104 deterministic sub-second CI assertions across 3 packages at $0 CI API spend.
04 · End-to-End Value Delivery Chain

Engineering Control → Operational Mechanism → Business Outcome

How architectural invariants convert directly into FinOps margin, SLA speed, and regulatory protection.

flowchart LR
  subgraph Controls["Calibration, QA & Harness Controls"]
    E1["Sliced Brier + Blind 2nd-Model Review"]
    E2["Error-Taxonomy Retry (missing_source Halt)"]
    E3["2-Pass Nullable Schema + Python YTD Math"]
    E4["# Case Facts Compaction + Timeout Envelopes"]
  end
  subgraph Mech["Operational Mechanism"]
    M1["Flags 0.865 Brier Pockets Despite 0.291 Global"]
    M2["Stops in 1 Call vs 4 on Absent Doc Sections"]
    M3["Catches -$1,250 Paystub Mismatch Deterministically"]
    M4["38.7k -> 16.7k Tokens + Clean Degraded Mode"]
  end
  subgraph ROI["Commercial Underwriting & FinOps Value"]
    V1["Safe Straight-Through Processing (No Silent Losses)"]
    V2["75% Retry Spend Cut + Zero Forced Hallucination"]
    V3["Automated Mortgage Income Integrity"]
    V4["56.8% Lower Harness Token Cost + 100% Uptime"]
  end
  E1 --> M1 --> V1
  E2 --> M2 --> V2
  E3 --> M3 --> V3
  E4 --> M4 --> V4
05 · Interactive Scale & Unit-Economics Model

Document Processing FinOps & Underwriting Safety Simulator

Models annual wasted retry calls eliminated (1 vs 4 on incomplete uploads) and high-confidence underwriting traps routed safely to HITL.

30000
2,000 packets/mo 250,000 packets/mo
15
5 % 35 %
Baseline vs. Production Comparison
Benchmark Formula Basis: Grounded in repo benchmarks: retry.py saves 3 futile API calls per missing_source document (1 call vs 4); harness engineering compresses multi-turn context 56.8% (38.7k -> 16.7k); sliced Brier (0.865) + Python YTD math gates intercept ~4% high-severity silent discrepancies.
06 · Cross-Functional Buyer Alignment

Why Every Enterprise Stakeholder Signs Off

How this single architecture aligns Engineering, Finance, Security, Legal/Compliance, and Business Operations.

Chief Underwriting Officer 0.865 Pocket Risk Caught

Prevents overconfident umbrella-exclusion hallucinations and -$1,250 paystub discrepancies from auto-clearing into bound risk.

VP Document Operations Targeted 3-Signal HITL

Focuses human underwriters strictly on miscalibrated or model-disputed fields instead of reviewing every clean document.

Head of AI Platform / FinOps -75% Retries · -56.8% Context

Eliminates blind retry storms on incomplete customer uploads and cuts long-running agent context token bills more than in half.

VP Supply Chain Risk Timeout-Safe Corroboration

Briefings never crash when a single feed times out, and supplier escalations require multi-source date-verified evidence.