Automated client reporting came out of the 159-repo audit of the agency’s own tools, and it is the clearest example of a rule that runs through this work: deterministic metrics first, prose second.
Why monthly reporting breaks at the seams
A monthly client report is a join across systems that were never designed to agree. Analytics counts sessions in one timezone, the ad platform reports conversions on its own attribution window, the store counts orders by settlement date, and the email platform counts revenue from a cookie.
The manual process fails in four places: someone exports five files, someone reconciles them in a spreadsheet, someone writes commentary, and someone emails the PDF. Each step can change a number without an audit trail.
The platform makes those joins explicit, repeatable and reviewable.
The architecture in one pipeline
The system is a TypeScript monorepo: a Next.js admin console, a worker on pg-boss, PostgreSQL, and shared packages for connectors, metrics, analysis, reports, PDF and email. The worker owns the pipeline; the web app owns configuration, review and delivery.
report.run
├── connector.pull.ga4
├── connector.pull.google_ads
├── connector.pull.shopify
├── connector.pull.wordpress
└── connector.pull.klaviyo
↓
report.normalize catalogued metrics + MoM/YoY + QA gates
↓
report.analyze draft → schema validation → fact validation → review
↓ (human approval)
report.publish immutable snapshot + PDF + checksum
↓
report.email attachment or share link + webhook reconciliation
The queue is durable, so a worker restart does not lose a run. A reaper marks jobs that stopped making progress, and a dead-letter queue keeps the terminal payload. A throttled queue handles the 14-month backfill with cursor state, so an interrupted load can resume (pg-boss).
Every provider response is written to a raw snapshot before normalization. A report can therefore be recomputed from stored facts without calling a provider again, which makes replay possible and a provider outage survivable.
Five connectors and graceful degradation
The shared contract matters more than the individual APIs: a connector may only emit metrics in the dictionary, and it must return a structured outcome rather than an exception that kills the run.
| Connector | Interface | What is hard about it |
|---|---|---|
| GA4 | Data API, service account | Property permissions, dimension limits, quota per property |
| Google Ads | GAQL over REST, MCC OAuth | The right login-customer-id on every call |
| Shopify | Admin GraphQL and ShopifyQL | Scopes, versioning, silent empty results without approvals |
| Klaviyo | REST with a pinned revision | Per-account rate limits and a reporting budget |
| WordPress | Signed REST from a plugin | Customer-hosted PHP, plugin mix, replay protection |
Google Ads fails at the account layer before the query layer. Calls through a manager account need the manager’s customer ID in the login-customer-id header (Google Ads call structure). One shared header can fail an entire agency’s account list, so the connector tries each accessible account and skips failures.
The failure policy is deliberate: a failed connector marks its sections unavailable and raises a finding. It never reports zero, because zero is a real number and a missing number is not. Publishing with a failed connector needs a reviewer override in the audit log.
The WordPress plugin is the only connector on infrastructure the agency does not control. It records form submissions and WooCommerce orders in its own table, then exposes a signed REST endpoint. Each request carries a key id, timestamp, nonce and an HMAC over method, path, sorted query, timestamp, nonce and body hash. Clock skew is limited to five minutes, and stored nonces reject a replay.
Why the language model never writes the numbers
The model is a writer, not a calculator. It receives computed facts and writes commentary. It cannot introduce a metric, change a number or infer a value that is not in the fact table.
The fact table is built from the metric dictionary. A connector can only emit a catalogued metric, and values are stored unrounded, then rounded only for presentation. That sounds pedantic until a client adds two displayed numbers and gets a different total from the one on the page.
Comparisons run as SQL window functions over the stored facts, not as fresh provider queries (PostgreSQL window functions). Month-over-month and year-over-year use the same snapshot as the current period.
Time is handled once per client. Month boundaries are half-open [start, end) and resolved in the client’s IANA timezone, then stamped on the run. A re-run reuses the stamped boundaries. A provider reporting in another timezone becomes a finding, not a silent normalization.
Before drafting, deterministic QA gates check reconciliation, completeness and consistency. A failed gate blocks PDF generation, publication and email. The gates catch the errors a language model would happily write around.
Versioned prompts, strict schemas and a fact validator
Narrative generation is a constrained writing task. The prompt version is pinned, the output schema is strict JSON, and the model is selected by policy rather than by an environment variable someone can change without a record.
The request asks for structured sections, not free text. A JSON Schema validates the shape first (JSON Schema 2020-12). A section with the wrong field or a missing citation fails before a human sees it.
The fact validator earns the trust. It rejects a draft when a number does not match the facts, the text makes an unsupported causal claim, a forbidden word appears, or a required section is missing. On a hard failure the worker feeds the findings back and retries up to three times, then fails the run rather than publishing a draft that ignored its corrections.
Every section lands in a review queue with four states: draft, edited, approved, rejected. No unapproved narrative can be published or emailed. The reviewer approves the interpretation, not the arithmetic.
Client context is an input: manual notes, imported change events and prior reports. A PDF with a text layer is extracted; a scanned PDF needs OCR first. Context improves commentary; it never becomes a source of numbers.
Replay: testing a prompt without sending a report
A replay CLI re-runs the analysis step against a stored report run: the same facts, the same client context, a candidate prompt or model, and no provider calls. The output is compared with the approved version and the validator’s verdict.
This is the only safe way to change a prompt. Editing a prompt and waiting for next month’s reports means discovering a regression in front of a client. Replay asks whether the draft still passes validation, keeps the same numbers, and reads better or worse than the approved text.
It also makes model changes honest. A new model has to pass the same validators on the same facts before it is considered for scheduled runs. The question is not which model writes more fluently; it is which model survives the constraints.
Send safety, share links and immutable publication
Delivery is the part with no undo. The platform treats publication and email as separate, audited events.
Publishing snapshots the report. Later corrections are restatements with a reason and a change log, never in-place edits. A client who downloaded a report last week can still be shown exactly what they received.
The PDF is rendered by Chromium through Playwright with selectable text, then checksummed (Playwright PDF). Rendering goes through the public origin so the HTML and PDF cannot diverge, and a signed print token lets a reviewer use the same path.
Email goes through Postmark with a PDF attachment below a byte ceiling and an automatic link-only fallback above it (7,000,000 bytes by default, from the project README). The delivery webhook has no signature, because Postmark does not sign payloads (Postmark webhooks), so it uses Basic authentication and an IP allowlist.
Share links are tokenised: the database stores a hash of the token, never the token, with an expiry, a revocation timestamp and an optional email gate. Views are logged with a hashed viewer IP, which gives a delivery signal without storing personal data.
Two rules keep retries from becoming duplicates. The run key is shared across the queue, database, email provider and WordPress nonce, and each side effect checks its own record before firing. RFC 9110 defines idempotent methods as those where repeated requests have the same effect as one (RFC 9110). Email is not idempotent, so the platform makes it idempotent at the application layer.
Manual report versus the platform
| Attribute | Manual monthly report | This platform |
|---|---|---|
| Numbers | Exported and pasted by a person | Computed from stored facts |
| Comparisons | Rebuilt each month | SQL windows over one snapshot |
| Narrative | Written from memory | Drafted from facts, validated, reviewed |
| Failure mode | A wrong number ships silently | A failed gate blocks publication |
| Recoverability | Re-export and redo | Replay from raw snapshots |
| Delivery evidence | Sent folder | Send records, link views, audit log |
| Correction | Re-issue the PDF | Restatement with a change log |
Which should you choose? Use the manual process while the report is a one-off and the audience already trusts the numbers. Move to a platform when the same report is produced every month, when more than one person assembles it, or when a client has asked why two reports disagree. The cost sits in the connectors and the review workflow, not in the language model.
What broke and what we changed
The build record lists failures that produced confident, wrong output rather than an error. Four changed the design.
Backfill imported nothing. It advanced checkpoints and reported success without calling a connector or writing a fact. A checkpoint now depends on a raw snapshot existing, not on the job finishing.
The fix then rejected every empty month. A guard that failed any bucket with no facts broke a quiet month inside a 14-month range. An empty month with a snapshot is valid; one without a snapshot fails loudly.
Published reports were not immutable. Section visibility was read from live connector configuration, so toggling a connector rewrote a report a client already had. Publication now snapshots the view model, and every correction is a restatement.
Features existed but were unreachable. Manual triggering, regeneration and share-link management were implemented in the API but never mounted in the UI. The lesson was to test the path a reviewer takes, not the function the developer called.
The improvement plan ran as 20 parallel agent workstreams split by package boundary, merged foundation-first (from the project’s inventory record). Every branch was checked with real command output, because an agent’s report is a claim, not evidence.
The status record from 3 September 2026 is part of the story: deployed, health checks passing, one client onboarded, zero production reports (from the project status record). The remaining checklist was credentials and one real run, not more code.
Related
- Auditing 159 repos to find the products inside an agency — where this platform sat in the product shortlist.
- LLMs write prose, never the numbers — the same split applied to a different reporting system.
- Agents report success while shipping defects — the review checklist used on the 20 workstreams.
- API integrations and data pipelines — the connector work behind the fact table.
- Mass agent orchestration — how the workstreams ran.
Frequently asked questions
How do automated client reports keep the numbers accurate?
By computing every number in code from stored provider data and giving the language model no ability to change it. Each metric has a definition, comparisons use the same snapshot, and QA gates block publication when reconciliation fails. The model writes commentary; a validator checks it against the facts.
Can an LLM write the narrative in a client report?
Yes, if the task is constrained. The model receives computed facts and a schema, not database access. Its output is validated for number agreement, unsupported claims and missing sections before a human sees it. The reviewer approves the interpretation, not the arithmetic.
What is a fact validator in an LLM pipeline?
A fact validator is a deterministic check that compares a generated statement with the facts behind it. It rejects numbers that do not match, claims the data cannot support and sections that are missing. It is not a second model judging the first; it is code checking output against the record.
How do you test a prompt change without sending a bad report?
Replay a stored run through the new prompt with no provider calls, then compare the draft with the approved version and the validator's verdict. The facts and context are identical, so a difference comes from the prompt or model rather than new data. A change ships only after it passes the same validators.
Does the platform send reports automatically?
It publishes and emails on a schedule only after a human approves every narrative section. The schedule creates the run; approval gates delivery. That ordering is deliberate, because an automated send cannot be taken back. Idempotency makes a retry safe, but it does not make an unapproved report acceptable.
Sources
- Google Analytics Data API v1beta
- Google Ads API: Getting started with GAQL
- Google Ads API: Call structure and `login-customer-id`
- Shopify Admin GraphQL API
- Klaviyo API reference
- Postmark webhooks
- JSON Schema 2020-12 core specification
- PostgreSQL window functions
- Playwright: page.pdf()
- pg-boss documentation
- RFC 9110: Idempotent methods
