LionsHead Analytics Group

Engagements

What the work actually looks like.

A curated selection of recent engagements. Each entry is a system in production — or recently in production — at a real engagement. Code excerpts are sanitized; architecture is real. Additional case studies available under engagement.

Multi-System · Real-Time · Priority Routing

Voicemail-to-Slack Notification Pipeline

Customer Service Operations · Active-Client Prioritization · Principal Architect

  • Python
  • Gmail API + OAuth
  • CRM cross-reference
  • Slack Block Kit + audio uploads
  • Self-healing backfill
  • Atomic JSON state writes
  • Asterisk PBX integration
  • Multi-subsystem cycle resilience

Problem

The firm's CRM-integrated dialer had no native voicemail surface. Voicemails dropped into a generic Asterisk PBX inbox as email attachments, where they sat unread for hours — sometimes days. Worst case: a missed call from an active policy holder calling about coverage rolling into a no-policy day-old summary, costing the firm a renewal and a relationship. The customer service floor needed live-time visibility into every voicemail AND a way to instantly know which callers were existing clients vs. cold leads.

Architectural Solution

A polling pipeline that reaps PBX-generated voicemail emails from Gmail (OAuth-scoped read-only), extracts the caller's phone number, cross-references the CRM to find the matching lead, then queries policy state to determine priority. Active-policy callers trigger live Slack alerts with the actual voicemail audio auto-uploaded as a threaded reply — the recording plays inline in the channel, no inbox-diving, no link-clicking, no app-switching required. No-policy callers are silenced during business hours and rolled into a single morning digest the next day; long-form messages in the digest still surface their audio as standalone posts so meaningful voicemails aren't lost, while hang-ups under 10 seconds (duration parsed directly from RIFF/WAVE headers, including PCM, μ-law, and A-law encodings) are auto-suppressed. A self-healing auto-backfill pass runs at the end of every cycle: it scans recent channel history, identifies any alert thread missing its audio attachment, and re-uploads the recording from Gmail — so a transient Slack upload failure never costs the team a voicemail. A separate CLI flag (`--backfill --backfill-days N`) lets ops manually catch up larger windows after extended outages. Two delivery modes selectable by config: webhook-only for simpler text-only deployments, or bot-token mode for full audio attachment + threaded replies. Every external system is wrapped in retry logic with exponential backoff, and the three cycle subsystems (live alerts, morning summary, auto-backfill) run in independent try blocks so one failing doesn't take down the others.

Tangible Result

Customer service team gets actionable voicemail visibility in near-real-time. Priority callers' audio recordings play directly inside Slack — agents listen to the voicemail in the same window where they're already working, then call back the same hour rather than the next morning. The morning digest replaces what used to be a manual inbox-triage ritual: one Slack thread, sorted, deduped, hang-ups silently suppressed, long-form messages surfaced individually with their audio. The self-healing pass means alert threads end up with their recording attached even when an upstream service hiccups, and the manual backfill mode lets ops recover from any extended outage in a single command. The CRM didn't gain a voicemail feature — but operationally, it's like it did.

Where it scales

Polling cadence (15 min default), Gmail page size (500 per call, 20-page ceiling), and business-window logic (Monday auto-pulls weekend gaps) are all configuration. Both Gmail and CRM API calls are wrapped in retry-with-jitter; transient failures don't drop voicemails and aren't marked processed until they succeed. Atomic JSON writes on the processed-IDs ledger guarantee state is never corrupted by a mid-write process kill. The self-healing backfill pass auto-detects missing OAuth scopes and degrades quietly (warns once per session instead of spamming), so deployment misconfigurations are visible but don't drown the logs.

Where it mutates

Slack delivery has two modes selectable by env var: webhook-only (text alerts, simpler deployments) or bot-token mode (audio attachments + threaded replies, full-fidelity delivery). The CRM phone-column lookup is a list — adding a new field to the search is a one-line change. Hang-up threshold, summary post time, active-policy criteria, and backfill window size are all top-of-file constants editable in seconds. CLI flags toggle one-shot backfill mode for ad-hoc recovery without redeployment.

voicemail_pipeline.py

# Cross-reference caller against CRM, route by active-policy status
def route_voicemail(caller_phone, message_id, audio_blob):
lead = find_lead_by_phone(caller_phone)
if not lead:
# No matching lead — defer to morning summary
return queue_for_summary(message_id, audio_blob)
 
active_policies = find_active_policies(lead["lead_id"])
if active_policies:
# Priority caller — post live with audio attached
return post_priority_alert(lead, active_policies, audio_blob)
 
# Cold lead — defer to summary, audio dropped if hang-up
return queue_for_summary(message_id, audio_blob)
 
# Retry with jitter — transient failures don't lose voicemails
def tld_get_with_retry(endpoint, payload, max_retries=4):
for attempt in range(max_retries):
try:
return requests.get(endpoint, ...)
except (RequestException, HttpError) as e:
if attempt == max_retries - 1: raise
time.sleep(BASE_DELAY * 2**attempt + random.uniform(0, 0.5))

Routing · Framework · Messenger-Agnostic

EnrollmentTraQ™: Real-Time Agent Routing Queue

Customer Service Operations · Live Transfer Coordination · Principal Architect

  • Python
  • Slack Block Kit + Socket Mode
  • Pluggable HandlerFactory pattern
  • Abstract RoutingRule interface
  • Live in-memory status store
  • Rate-limit-aware cleanup pass
  • Audit logging + dry-run mode
  • YAML config-driven

Problem

The customer service floor's "who can take this transfer?" workflow lived in shoulder taps and Slack DMs. Some agents claimed requests they weren't actually available for; others were available but invisible. Routing rules — HEAP carriers go to one writing group, partner carriers go to another, fall back to the other group when the primary pool is empty — lived in tribal knowledge and got applied inconsistently. Stale request messages cluttered the channel for weeks after the deal had already closed. The team needed real-time visibility into who was free, automatic enforcement of the routing rules, and a way to keep the channel readable as volume scaled.

Architectural Solution

A real-time agent routing engine that runs inside the team's Slack channel. The bot watches for inbound enrollment requests, parses carrier and state from the message, then routes to a live-tracked pool of available agents — pulling only those whose latest status is Ready, declared via Block Kit availability polls posted directly inside the channel. Carrier-aware pool selection applies the firm's routing rule; fallback to the secondary pool fires automatically when the primary has nobody ready. A nightly cleanup pass removes stale request messages and their entire reply thread, with full audit log, rate-limit-aware retry, and a dry-run mode for safe rollout. The architecture is the first production deployment of the LionsHead Integration Library: Source, Messenger, and Routing Rule are all pluggable via a HandlerFactory, with concrete implementations selected by YAML config. The same engine that runs on Slack today ports to Teams, Discord, Webex, or any messenger by registering one new Messenger plugin — no rewrite of the routing core.

Tangible Result

Transfers route to the first actually-available agent in seconds, not minutes-of-shouting. Misrouted requests — where an agent grabs a deal that should have gone to a different writing group — drop to near-zero, because the system explains in plain English why a given routing isn't allowed. The channel stays clean: stale requests and their bot replies vanish on a daily cadence with a full audit trail. And because the architecture is a library rather than a one-off, the next routing engine LionsHead builds (Teams, Discord, internal IVR, whichever messenger comes next) inherits all of this for free.

Where it scales

Agent roster, channel list, eligible carrier set, cleanup window, and poll cadence are all config — no code changes to grow the system. New routing dimensions (state-licensure pools, time-of-day pools, language pools) add via new RoutingRule subclasses without touching the main run loop. Multi-channel and multi-tenant deployments are supported by registering additional Source + Messenger pairs in config. The cleanup pass is rate-limit-aware with Retry-After honored and exponential backoff, so deploys at higher message volume don't break.

Where it mutates

The HandlerFactory pattern means swapping the messenger (Slack → Teams), the data source (Users.json → CRM API → Active Directory), or the routing rule (carrier-based → license-based → seniority-based) is a YAML config change, not a code rewrite. Each new engagement gets its own concrete handler set; the library core stays unchanged across deployments. DEBUG modes let you exercise the full status-tracking flow without applying group filtering, useful for rollout validation in a single channel before promoting to production.

handler_factory.py

# HandlerFactory — register a class, the library wires it up
# from YAML config alone. New messenger? New routing rule?
# Register and the rest of the library is unchanged.
 
SOURCE_REGISTRY = {
"usersJson": UserRosterSource,
"messageGrabber": MessageGrabber,
}
 
MESSENGER_REGISTRY = {
"slack": SlackMessenger,
# "teams": TeamsMessenger, # one plugin to add
# "discord": DiscordMessenger, # the next
}
 
RULE_REGISTRY = {
"carrierRouting": CarrierRoutingRule,
}
 
def createMessenger(cfg):
cls = MESSENGER_REGISTRY.get(cfg["type"])
if not cls:
raise ValueError(
f"Unknown messenger type {cfg['type']!r}. "
f"Known: {sorted(MESSENGER_REGISTRY)}"
)
return cls(cfg.get("credentials", {}),
cfg.get("params", {}))

Compliance · AI Scoring · Integration Library

Beta

CALIPER™: AI Call Score Compliance Export

Regulated Communications · QA Compliance Automation · Principal Architect

  • Python
  • Abstract Handler ABCs (Source/Dest/Messenger × category)
  • YAML config-driven deployments
  • Pluggable auth (API key, basic, OAuth)
  • Classified transport-layer retry
  • SQLite hash-ledger upsert contract
  • openpyxl template preservation
  • Multi-vendor AI-scoring abstraction

Problem

Regulated call centers — Medicare Advantage agencies, mortgage origination, financial advisory — are required to demonstrate that every recorded sales conversation cleared a compliance rubric: Power of Attorney handling, needs analysis, consent-to-enroll capture, scorecard threshold. The AI-scoring vendors that produce these scores (Balto, CallMiner, Observe.AI, Cresta, ASAPP, NICE Engage) each expose the data on a different API surface, in a different shape, with different auth schemes. The carrier templates that have to be populated from those scores (CMS-format scorecards, agency QA workbooks, training-and-coaching exports) all want the same columns shaped slightly differently. Building a one-off integration per vendor-and-template pair is how compliance ops drowns. Worse: when an AI scoring system updates a call's score days after the call closed — because a reviewer overrode a measure, or because the scorecard rubric itself changed — there's no clean way to know which historical exports need to be re-issued.

Architectural Solution

A four-category handler framework — Source, Destination, Messenger, and a category-specific AIScoringHandler interface — wired together by a YAML config file. One deployment = one YAML. The Source category abstracts every AI-scoring vendor behind a single fetch_calls(start, end, **filters) interface that yields canonical Call+Score payloads; concrete handlers translate each vendor's wire format. The Destination category abstracts the output template (XLSX agency workbook, BI warehouse, CSV export); concrete handlers preserve template styling, sheet names, and cell formatting on a per-row basis. A classified transport layer wraps every external call: TransientError, RateLimitError, AuthError, ClientError, ValidationError — each with its own retry policy, Retry-After header honored, exponential backoff with jitter on transient failures. A SQLite-backed state ledger sits at the seam between source and destination; it stores each call's content hash and implements an upsert contract — insert / unchanged / updated — so late-arriving score revisions automatically trigger a re-export without manual reconciliation. Auth is itself pluggable (API key, basic, OAuth) so the same handler ports across an entire vendor category without an auth rewrite.

Tangible Result

A scoring + compliance pipeline that runs unattended overnight and lands a fully-formatted carrier-template export in the right folder by morning. Late score revisions from the AI vendor flow through the ledger and re-export on the next cycle with zero human intervention. Onboarding a new AI scoring vendor or a new compliance template is one handler module and one config block — not a rewrite. The framework itself is the deliverable: every subsequent compliance-automation engagement LionsHead takes on inherits the transport, the ledger, the auth modules, and the abstract category interfaces for free.

Where it scales

Per-vendor handlers are isolated — adding the seventh AI scoring vendor doesn't touch the six already deployed. The state ledger is keyed by call_id with a stable hash contract, so multi-day windows replay deterministically. Transport-layer retries are config-tunable per deployment (max_retries, backoff_base, default_timeout) and the rate-limit branch honors any Retry-After the upstream supplies. Multiple deployments can share a Python install — each one is just a separate YAML file pointing at its own credentials reference.

Where it mutates

Source vendor (Balto → CallMiner → Observe.AI), destination template (carrier A workbook → carrier B workbook → BI warehouse), messenger (Slack alert → email → PagerDuty), and auth scheme (API key → OAuth → basic) are all selected by YAML. The Caliper config schema documents every section; the loader validates against the supported-handlers registry at startup, so a misconfigured deployment fails fast with a readable error rather than silently producing the wrong export. New AI-scoring vendors register a single class under handlers/ai_scoring/ — the rest of the library is unchanged.

handlers/base.py

# Caliper · Handlers · Root Interfaces
# LionsHead Integration Library Spec, sections 2.2 and 4.2
# Three root categories. Concrete category interfaces
# (AIScoringHandler, CRMHandler, SpreadsheetHandler) inherit
# from these and add their own per-category methods.
 
class Handler(ABC):
@abstractmethod
def authenticate(self, credentials):
"""Establish auth state (no network unless required)."""
raise NotImplementedError
 
class SourceHandler(Handler):
@abstractmethod
def fetch(self, params):
# yields canonical abstract payloads
# pagination/retry/translation are the handler's job
raise NotImplementedError
 
class DestinationHandler(Handler):
@abstractmethod
def write(self, records, params):
# returns whatever the destination chooses to expose
# — a file path, row count, upload receipt, etc.
raise NotImplementedError
 
class MessengerHandler(Handler):
@abstractmethod
def notify_success(self, result):
raise NotImplementedError
@abstractmethod
def notify_failure(self, error):
raise NotImplementedError

CRM · Slack · Real-Time

Live Sales Feed Integration

Sales Operations · Real-Time Coordination · Principal Architect

  • Python
  • requests
  • Slack Block Kit
  • JSON state store
  • Idempotent polling

Problem

Sales were closing in the CRM but the floor was learning about them in stand-ups the next morning. Recognition and competitive momentum lag — the cultural cost of latency. The team needed every closed sale to land in the right Slack channel within seconds, with full context, without flooding on backfill.

Architectural Solution

A CRM-egress polling loop with a deduplicated event store. The first run bootstraps — marks the day's existing sales as seen so the channel doesn't get hit with backfill — then each subsequent cycle diffs against a self-pruning seen-set on disk. New policies are formatted as Slack Block Kit payloads (agent / fronter / carrier / commission / vendor / running daily count) and posted in chronological order. The seen-set rotates against today's visible window, so the file never grows unbounded.

Tangible Result

The sales floor sees closes as they happen. Daily totals are visible in the same channel that announces individual sales — recognition and momentum compound in real time. Zero duplicates across restarts, zero backfill floods.

Where it scales

Poll interval is a single constant. Batch size scales with the CRM's per-call ceiling, and the seen-set is bounded by today's visible window. Restarts are idempotent — the system can move hosts without re-announcing yesterday's sales.

Where it mutates

The Slack payload builder is a pure function over the egress row — adjust the layout, add fields, or split per-channel routing without touching the polling loop. Carrier-specific or fronter-specific rendering is a one-line branch.

live_sales_feed.py

# Block Kit payload — pure function over the CRM row
def build_slack_payload(sale, daily_total):
return {
"blocks": [
{"type": "header", "text": {
"type": "plain_text", "text": "New Sale"}},
{"type": "section", "fields": [
mk("Agent", sale.agent_name),
mk("Carrier", sale.carrier_name),
mk("Commission", money(sale.commission)),
mk("Vendor", sale.lead_vendor_name),
]},
{"type": "context", "elements": [
mk(f"Today Sales Count: *{daily_total}*"),
]},
],
}
 
# Self-pruning seen-set — bounded by today's visible window
seen_ids = prune_seen_ids(seen_ids, current_sales)

Reconciliation · Predictive Modeling · Multi-Layer Match

RTR™: Ready to Reconcile

Payment Reconciliation · Predictive Financial Operations · Principal Architect

  • Python
  • Multi-layer identity matching
  • Predictive rate matrix
  • xlsx + CSV ingestion
  • Idempotent JSON ledger
  • Audit-metric layer

Problem

Pay statements arrived biweekly, but verifying them against the firm's book of record was a manual reconciliation nightmare. Three different identity surfaces had to be reconciled — enrollment IDs, member-ID + effective-date pairs, and agent-NPN + submit-date pairs — and no single one of them was reliably present on every row. Worse, status changes mid-cycle meant a policy paid as Active on the Advance statement could come back Trashed on the Recon, triggering an unexpected clawback the firm couldn't anticipate or audit cleanly.

Architectural Solution

A three-layer identity-matching engine that cascades through the available join keys in confidence order: enrollment ID first (deterministic when present), then member-ID + effective-date (probabilistic but high-confidence), then NPN + submit-date (last-resort, audit-flagged for review). Matched policies accumulate in a per-effective-date ledger via idempotent upsert so multiple statements per cycle merge cleanly without re-scanning history. A status-based rate matrix predicts Recon outcomes by category — Active full payment, Active remainder, Trashed flat-fee, Clawback, Zero — turning what was a reactive cleanup into a forward-looking projection. Audit metrics layered on top flag every datapoint that doesn't reconcile: Possible Audit, No Carrier Match, CRM Date Mismatch. The output is a "System Rigor Replay" report showing match-layer breakdown alongside projected-vs-realized payment.

Tangible Result

Pay-statement reconciliation moved from days of manual cross-referencing to minutes of automated review. Recon predictions land inside a single-digit-percent error band on closed periods. Audit-flagged policies surface BEFORE the statement closes, giving leadership the window to correct or contest. The clawback surprise that defined the old workflow is now a predicted line item, not an event.

Where it scales

Per-effective-date ledgers grow horizontally — each new period writes its own file, none re-scan prior history. The match cascade absorbs new identity sources by adding a layer, not refactoring the core loop. xlsx and CSV statement formats are both supported; queue-based ingestion handles arbitrary batch sizes without changing the runtime.

Where it mutates

Rate matrix coefficients, per-effective-date balance overrides, and pay-statement column mappings all live in JSON config files (PaymentRules.json, RateRules.json, UserRules.json, pay_statement_columns.json). Onboarding a new carrier's statement format is a config change, not a code change. Carrier eligibility, agent group rules, and TPV fee schedules are leadership-editable.

rtr_match_cascade.py

# Three-layer identity match — cascade in confidence order
# Each layer fills gaps the previous one left behind
def match_statement_row(row, policy_book):
 
# Layer 1: enrollment ID — deterministic when present
if enrollment_id := normalize(row.get("enrollment_id")):
if hit := policy_book.find_by_enrollment(enrollment_id):
return hit, "layer_1_enrollment"
 
# Layer 2: member ID + effective date — high-confidence join
mbi = normalize_mbi(row.get("member_id"))
eff = parse_date(row.get("effective_date"))
if mbi and eff:
if hit := policy_book.find_by_mbi_eff(mbi, eff):
return hit, "layer_2_mbi_eff"
 
# Layer 3: agent NPN + submit date — last resort, audit-flagged
npn = row.get("agent_npn")
sub = parse_date(row.get("submit_date"))
if npn and sub:
if hit := policy_book.find_by_npn_sub(npn, sub):
return hit, "layer_3_npn_sub_audit"
 
return None, "unmatched"

Disclosure

What you're not seeing here.

A curated selection

The case studies above are a deliberate sample of recent work — additional engagements, deeper architectures, and adjacent tooling exist in the private archive. Client names, system endpoints, credentials, schema-level identifiers, and any logic that could be reverse-engineered are intentionally omitted.

View the full project archive

Available under engagement

Live demos, full architecture briefs, and verifiable production metrics are available during a Discovery & Architecture Blueprint engagement. Request access via the contact form and we'll send the materials under NDA.

Request the dossier

Engage

Recognize your firm in one of these?

Most clients do — the patterns repeat across Securities, financial operations, and the firms whose revenue depends on data integrity. The Blueprint is the qualifying engagement.