#CoDuck analytics and PostHog migration
Draft only. No production writes, import, provider shutdown, merge or release is authorized by these PRs.
#Plain-language plan
CoDuck collects its own page visits and existing product actions into its database. Admin Analytics reads website totals, visitor countries, referrers, campaigns and click geometry from that database. Account creation, active users, builds, confirmed Stripe revenue, churn and feature adoption retain their existing canonical database sources: historical browser events do not become payments or completed builds.
The first release adds collection while keeping the existing opted-in PostHog pipeline available for comparison. US internal first-party measurement is independent of that optional provider choice. We import history only before the eventual production first-party cutover instant. After comparing complete counts and real production arrival, Liam can approve a separate removal PR. These draft PRs do not disable PostHog.
#Measurement contract
- Own CoDuck marketing and product routes only; no customer-published sites, admin, support, embedded previews, password/reset/verification/token routes.
- Server timestamps and country from the existing trusted-proxy/local GeoIP path. Never trust a browser country or the first XFF hop. Unknown geography pauses browser collection.
- US general-audience internal analytics: 180-day browser ID, rolling 30-minute inactivity session, request country, sanitized route template, referrer domain and bounded UTM fields. No sale/sharing, advertising profiles, sensitive inference, precise location or cross-site identifiers. Optional third-party analytics/replay remain opt-in. No extra US analytics opt-out control.
- Elsewhere: identifier-free hourly public-route/country counts. Identified browser/product events require an affirmative analytics choice; GPC/DNT suppress this optional mode. EU/EEA, UK and Swiss visitors can exclude identifier-free counts through the existing low-key Privacy settings pop-up. Unknown geo never defaults to US. Country alone does not settle every applicable law: sensitive/child-directed services, changed purposes/markets and advertising need a separate policy review.
- If browser storage is blocked, use identifier-free counts rather than minting a fresh visitor on every event.
- First-party IDs are HMAC pseudonyms using a stable
BRAND_ANALYTICS_ID_SECRET(32+ characters; separate from auth signing keys, generated through the normal approved configuration path). Keep this key stable across import/reruns. ExistingJWT_SECRETis a compatibility fallback only; configure the dedicated key before production release. - No raw IP/UA, URL query/hash, title, email, typed fields, prompts, filenames, project IDs/source, DOM/text or click IDs in the ledger. Click IDs are advertising identifiers and deliberately outside this internal analytics scope. Preserve original private exports separately until approved retention/deletion, rather than copying arbitrary sensitive properties into app tables.
- Visitor = observed browser pseudonym, not a person. Imported PostHog browser/session namespaces remain distinct from native IDs; unique counts spanning cutover may count a browser in both namespaces. No unverified person merge. Imported rows never attach arbitrary provider distinct IDs as CoDuck account IDs.
- Pageviews include identifier-free counts. Those counts cannot supply unique visitors, sessions, referrers or campaigns. UI coverage explains the measured subset. No IP/UA fingerprint substitute. Country visitor counts include only identified observations; unknown stays unplotted.
- Native event UUID is idempotent. Export event identity is UUID + event name + distinct ID + UTC day, matching documented PostHog duplicate semantics. Import IDs are hashes and never overwrite native rows.
- Browser product actions describe observations/intents. Revenue and build outcomes use the existing server ledgers. Automatic text/error capture is excluded. First-viewport clicks are rounded to a 40-cell grid, with no recorded element labels.
#Storage, indexes and retention
BrandAnalyticsEvent has environment/name/time, time, visitor/time and account/time indexes. BrandPageCount uses an environment/hour/path/country primary key. Both are pruned in bounded 5,000-row transactions after 400 days by the existing primary-only daily retention worker. This supports all 366-day report selections. Counts are not a lifetime archive. Source posthog remains explicit and report queries filter the server-owned environment.
Deploy the additive migration through the normal approved API release first, configure the stable identity key and correct environment, then release the client. No schema operation occurs merely by running dry-run. Existing canonical SignalEvent/business records and tenant analytics retain their existing separate retention contracts.
#History import: approval and commands
Liam approves a scoped read credential for PostHog US project 650844, supplied via the existing secret manager/host environment (name/location only in chat). A capture key cannot export. Query/Events reads use
query:read; native file exports needbatch_export:writeto create andbatch_export:readto download, so that route needs explicit export-job approval as well. Never paste a key in chat or command arguments, never echo environment files.Obtain complete JSON Lines exports from PostHog's supported file export or approved Events API. Include UUID, event, timestamp, distinct_id, properties. Export every file and week, not a truncated UI page; include a source count manifest per UTC day/event/environment and source file hashes. Store files privately, mode0600, outside Git. Do not run a partial
/query LIMITas a complete export.Record the exact approved first-party production rollout time as
--before(exclusive). Export data before that time; later provider events are excluded to avoid dual-write double-counting. Rerun a late-arrival overlap after 48h and again before shutdown, using the same cutoff and key. Missing environment, foreign hosts, snapshots and malformed data are separately counted; never silently label preview/unknown as production. Preserve the original export for audit. Historical automatic clicks/heatmap geometry and session replay are not reconstructed by this event importer.Inject
BRAND_ANALYTICS_ID_SECRETprivately. Default dry-run has no DB connection and no network request:npx ts-node scripts/import-posthog.ts --input /private/export.ndjson \ --before <approved-cutover-UTC> --environment production --report /private/dry-run.jsonnpx ts-node scripts/import-posthog.ts --input /private/export.ndjson \ --before <approved-cutover-UTC> --environment production --report /private/dry-run.jsonReview total rows = eligible unique rows + duplicates + invalid rows + excluded rows. Review reason counts and every day/event count against the independently obtained source counts. Zero invalid rows is required before apply. Reports contain only counts, allowlisted event names and hashes (unknown event names are hashed too); never source IDs, properties or credentials. Files over two million rows must be split into bounded source windows. Dry-run duplicate counts are per file; DB reconciliation covers cross-file reruns.
Liam separately approves the exact target, count manifest, exclusions and write run. Inject
MIGRATION_DATABASE_URLprivately, never through an argument. The importer requires the reviewed dry-run manifest, matching file SHA, cutoff, environment and explicit database name:npx ts-node scripts/import-posthog.ts --input /private/export.ndjson \ --before <approved-cutover-UTC> --environment production \ --apply --target <approved-coduck-database> --manifest /private/dry-run.json \ --report /private/applied.jsonnpx ts-node scripts/import-posthog.ts --input /private/export.ndjson \ --before <approved-cutover-UTC> --environment production \ --apply --target <approved-coduck-database> --manifest /private/dry-run.json \ --report /private/applied.jsonEach batch is a transaction with
ON CONFLICT DO NOTHING, then verifies every eligible source ID exists in the target. Reports distinguish inserted vs already present. Failures exit nonzero without printing SQL errors/URIs/source rows; committed batches survive and the same command resumes safely. Comparepresent == eligible, all day/event buckets, min/max timestamps, visitor/session counts and selected Admin ranges against source. Use a disposable synthetic DB before any production import.
#Removal gate and rollback
Keep PostHog capture, project and historical export intact until all source windows/files reconcile, late-arrival passes settle, native production traffic is observed, regional negative journeys pass and Liam approves removal. Then a separate PR removes posthog-js, initializer, wrapper/provider hooks, billing delivery outbox destinations, environment variables/workflow requirements, external admin links and obsolete disclosures; retain first-party captures and canonical Stripe records. Make privacy/subprocessor/DPA disclosures match the actual transition and surviving historical provider data. Rotate/revoke the export credential after verification. Provider deletion/shutdown/cancellation is a separate explicit approval, never automatic.
Before release, rollback means keep these drafts unmerged. After a future release, rollback disables native browser ingestion/report selection through a reviewed code change; never delete the ledger or import records to hide discrepancies. Reverting clients must not re-send a migrated window as live data.
#Sources and legal scope
Implementation assumptions are deliberately narrower than a worldwide legal certification. US internal analytics without sale/sharing is distinct from advertising; California describes sale/sharing opt-outs and GPC in CCPA guidance. The UK statistical exception prohibits monitoring individual visitors and requires a simple free objection route (ICO). CNIL conditions exempt measurement on limited purposes, notice, objection and separation from customer files (CNIL). Thus strict-region defaults do not create browser IDs or account journeys. Source data/duplicate semantics: PostHog events.