| 1 | #!/usr/bin/env node |
| 2 | import { readFileSync } from "node:fs"; |
| 3 | import { pathToFileURL } from "node:url"; |
| 4 | import { FUNNEL_COUNTER_FIELDS } from "../src/schema.ts"; |
| 5 | import { querySql } from "./report-active-installs.mjs"; |
| 6 | |
| 7 | const DAY_MS = 86_400_000; |
| 8 | const ROW_LIMIT = 10_001; |
| 9 | const NATIVE_SURFACES = ["tui", "exec", "cli", "app-server", "mcp-server", "serve"]; |
| 10 | export const CAVEATS = [ |
| 11 | "Website counters are aggregate interactions, not unique visitors or user conversion. Self-confirmations do not verify installation or a useful task.", |
| 12 | "Browser and native identifiers are independent; this report makes no website-to-CLI, GitHub or cross-device attribution join.", |
| 13 | "Runtime install means first initialized enabled telemetry state, not all installations or new people. IDs rotate every 90 days and are removed on opt-out.", |
| 14 | "Native success is observed model turns_ok, not a first-ever primary or useful task. Missing usage, same-process child activity and late cancellation can affect it.", |
| 15 | "Dates are received batch dates rather than exact event times. Offline, opted-out and dropped deliveries are absent; ingest has no replay deduplication guarantee.", |
| 16 | "Native IDs with an observed CI, fleet worker, agent or scripted start are excluded in full because the aggregate schema cannot assign model counts to individual sessions.", |
| 17 | ]; |
| 18 | |
| 19 | function instant(value, field) { |
| 20 | if (typeof value !== "string" || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{3})?Z$/.test(value) || !Number.isFinite(Date.parse(value))) throw new Error(`invalid ${field}`); |
| 21 | return new Date(value); |
| 22 | } |
| 23 | function count(value, field) { |
| 24 | if (typeof value !== "number" && (typeof value !== "string" || !/^\d+(?:\.0+)?$/.test(value))) throw new Error(`invalid ${field}`); |
| 25 | const number = Number(value); |
| 26 | if (!Number.isSafeInteger(number) || number < 0) throw new Error(`invalid ${field}`); |
| 27 | return number; |
| 28 | } |
| 29 | function within(date, from, to) { return date >= from && date < to; } |
| 30 | function sqlDate(date) { return date.toISOString().slice(0, 19).replace("T", " "); } |
| 31 | function rows(payload) { |
| 32 | if (!payload || !Array.isArray(payload.data) || payload.data.length >= ROW_LIMIT || payload.rows_before_limit_at_least >= ROW_LIMIT) throw new Error("incomplete or malformed query receipt"); |
| 33 | return payload.data; |
| 34 | } |
| 35 | function fresh(value) { return value.replace(" ", "T").replace(/(?:Z)?$/, "Z"); } |
| 36 | |
| 37 | export function funnelSql(fromValue, toValue) { |
| 38 | const from = instant(fromValue, "from"); const to = instant(toValue, "to"); |
| 39 | if (from >= to) throw new Error("from must precede to"); |
| 40 | const where = `timestamp >= toDateTime('${sqlDate(from)}') AND timestamp < toDateTime('${sqlDate(to)}')`; |
| 41 | return { |
| 42 | website: `SELECT toString(toDate(timestamp)) AS day, blob18 AS counters, SUM(_sample_interval) AS weight FROM codewhale_telemetry WHERE ${where} AND blob1 = 'funnel_usage' AND blob2 = 'website' AND blob19 = '5' GROUP BY day, counters LIMIT ${ROW_LIMIT} FORMAT JSON`, |
| 43 | native: `SELECT index1 AS install_id, blob1 AS event, blob2 AS surface, blob9 AS install_kind, blob11 AS session_source, toString(timestamp) AS received_at, blob19 AS schema_version, double1 AS turns_ok, _sample_interval AS weight FROM codewhale_telemetry WHERE ${where} AND blob1 IN ('install_or_upgrade','session_start','model_usage') AND blob2 IN ('tui','exec','cli','app-server','mcp-server','serve') LIMIT ${ROW_LIMIT} FORMAT JSON`, |
| 44 | }; |
| 45 | } |
| 46 | |
| 47 | export function buildFunnelReport(input, { now = new Date() } = {}) { |
| 48 | if (!input || input.format !== "codewhale-funnel-receipt-v1" || !["analytics-engine", "offline-receipt", "synthetic"].includes(input.source)) throw new Error("unsupported receipt format or source"); |
| 49 | const coverage = input.coverage; |
| 50 | if (!coverage || coverage.accepted_only !== true) throw new Error("receipt must establish accepted-only source coverage"); |
| 51 | const from = instant(coverage.from, "coverage.from"); const to = instant(coverage.to, "coverage.to"); |
| 52 | if (from >= to || to > now || to - from > 90 * DAY_MS) throw new Error("invalid or future coverage window; maximum 90 days"); |
| 53 | if (!Array.isArray(input.website_rows) || !Array.isArray(input.native_rows) || input.website_rows.length >= ROW_LIMIT || input.native_rows.length >= ROW_LIMIT) throw new Error("missing or truncated receipt rows"); |
| 54 | const totals = Object.fromEntries(FUNNEL_COUNTER_FIELDS.map((field) => [field, 0])); |
| 55 | const days = new Map(); let sampled = false; let newest = null; |
| 56 | for (const row of input.website_rows) { |
| 57 | const date = instant(`${row.day}T00:00:00Z`, "website day"); |
| 58 | if (!within(date, new Date(from.toISOString().slice(0, 10) + "T00:00:00Z"), to)) throw new Error("website row outside coverage"); |
| 59 | const weight = count(row.weight, "weight"); if (weight < 1) throw new Error("weight must be positive"); |
| 60 | const counters = typeof row.counters === "string" ? JSON.parse(row.counters) : row.counters; |
| 61 | if (!counters || typeof counters !== "object" || Object.keys(counters).length !== FUNNEL_COUNTER_FIELDS.length || Object.keys(counters).some((field) => !FUNNEL_COUNTER_FIELDS.includes(field))) throw new Error("unknown website counter field"); |
| 62 | const daily = days.get(row.day) ?? Object.fromEntries(FUNNEL_COUNTER_FIELDS.map((field) => [field, 0])); |
| 63 | for (const field of FUNNEL_COUNTER_FIELDS) { |
| 64 | const value = count(counters[field], field); if (value > 4294967295) throw new Error("website counter out of range"); |
| 65 | const weighted = value * weight; |
| 66 | if (!Number.isSafeInteger(weighted) || !Number.isSafeInteger(totals[field] + weighted)) throw new Error("report counter overflow"); |
| 67 | daily[field] += weighted; totals[field] += weighted; |
| 68 | } |
| 69 | days.set(row.day, daily); |
| 70 | if (newest === null || date > newest) newest = date; |
| 71 | } |
| 72 | const installs = new Map(); const successes = new Map(); const started = new Set(); const ci = new Set(); |
| 73 | const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; |
| 74 | for (const row of input.native_rows) { |
| 75 | if (!uuid.test(row.install_id) || !NATIVE_SURFACES.includes(row.surface) || ![1, 2, 3, 4, 6].includes(count(row.schema_version, "schema_version"))) throw new Error("invalid native identity, surface or version"); |
| 76 | const at = instant(fresh(row.received_at), "received_at"); |
| 77 | if (!within(at, from, to)) throw new Error("native row outside coverage"); |
| 78 | if (newest === null || at > newest) newest = at; |
| 79 | const weight = count(row.weight, "weight"); if (weight < 1) throw new Error("weight must be positive"); |
| 80 | if (weight !== 1) sampled = true; |
| 81 | if (row.event === "install_or_upgrade") { |
| 82 | if (!["install", "upgrade", "downgrade"].includes(row.install_kind)) throw new Error("invalid install kind"); |
| 83 | if (row.install_kind === "install" && (!installs.has(row.install_id) || at < installs.get(row.install_id))) installs.set(row.install_id, at); |
| 84 | } else if (row.event === "session_start") { |
| 85 | if (!["interactive", "resume", "fork", "api", "unknown", "ci", "fleet_worker", "agent", "scripted"].includes(row.session_source)) throw new Error("invalid session source"); |
| 86 | if (["ci", "fleet_worker", "agent", "scripted"].includes(row.session_source)) ci.add(row.install_id); |
| 87 | started.add(row.install_id); |
| 88 | } else if (row.event === "model_usage") { |
| 89 | if (![4, 6].includes(count(row.schema_version, "schema_version"))) throw new Error("model usage requires v4 or v6"); |
| 90 | if (count(row.turns_ok, "turns_ok") > 0) { |
| 91 | const observations = successes.get(row.install_id) ?? []; observations.push(at); successes.set(row.install_id, observations); |
| 92 | } |
| 93 | } else throw new Error("unexpected native event"); |
| 94 | } |
| 95 | const eligible = [...installs].filter(([id, at]) => !ci.has(id) && at.getTime() + 7 * DAY_MS <= to.getTime()); |
| 96 | const completed = eligible.filter(([id, at]) => successes.has(id) && successes.get(id).some((observed) => observed >= at && observed.getTime() < at.getTime() + 7 * DAY_MS)); |
| 97 | const unavailable = coverage.complete !== true ? "coverage is incomplete" : sampled ? "native query was sampled; distinct cohort coverage is incomplete" : eligible.length === 0 ? "no fully observed seven-day native initialization cohort" : null; |
| 98 | return { |
| 99 | report: "codewhale_observed_funnel", generated_at: now.toISOString(), source: input.source, synthetic: input.source === "synthetic", coverage, |
| 100 | freshness: { newest_observed_received_at: newest?.toISOString() ?? null, age_hours: newest === null ? null : Math.max(0, (now - newest) / 3_600_000), website_time_resolution: "UTC day only" }, |
| 101 | website: { measure: "weighted interaction counts; no unique visitors or cross-surface conversion", totals, days: [...days].sort(([a], [b]) => a.localeCompare(b)).map(([day, counters]) => ({ day, counters })) }, |
| 102 | native: { |
| 103 | measure: "observed native initialization and technical model completion, not people or useful tasks", |
| 104 | observed_started_ids: [...started].filter((id) => !ci.has(id)).length, |
| 105 | observed_initialized_ids: [...installs.keys()].filter((id) => !ci.has(id)).length, |
| 106 | observed_completed_ids: [...successes.keys()].filter((id) => !ci.has(id)).length, |
| 107 | excluded_ci_ids: ci.size, incomplete_followup_ids: [...installs].filter(([id, at]) => !ci.has(id) && at.getTime() + 7 * DAY_MS > to.getTime()).length, |
| 108 | seven_day_initialization_cohort: { denominator: eligible.length, numerator: completed.length, fraction: unavailable === null ? completed.length / eligible.length : null, unavailable_reason: unavailable, sampled }, |
| 109 | }, |
| 110 | caveats: CAVEATS, |
| 111 | }; |
| 112 | } |
| 113 | |
| 114 | export function parseArgs(argv) { |
| 115 | const result = { input: null, from: null, to: null, sql: false }; |
| 116 | for (let index = 0; index < argv.length; index++) { |
| 117 | const arg = argv[index]; |
| 118 | if (arg === "--sql") result.sql = true; |
| 119 | else if (["--input", "--from", "--to"].includes(arg)) { |
| 120 | const value = argv[++index]; if (!value || value.startsWith("--")) throw new Error(`missing ${arg}`); |
| 121 | result[arg.slice(2)] = value; |
| 122 | } else throw new Error("unknown report option"); |
| 123 | } |
| 124 | return result; |
| 125 | } |
| 126 | |
| 127 | export async function main(argv = process.argv.slice(2), env = process.env) { |
| 128 | const args = parseArgs(argv); |
| 129 | if (args.input) { |
| 130 | if (args.from || args.to || args.sql) throw new Error("offline input already defines its coverage"); |
| 131 | return buildFunnelReport(JSON.parse(readFileSync(args.input, "utf8"))); |
| 132 | } |
| 133 | const to = args.to ?? new Date().toISOString().slice(0, 10) + "T00:00:00Z"; |
| 134 | const from = args.from ?? new Date(Date.parse(to) - 30 * DAY_MS).toISOString(); |
| 135 | const sql = funnelSql(from, to); |
| 136 | if (args.sql) return { source: "query-plan-only", sql, caveats: CAVEATS }; |
| 137 | const accountId = env.CF_ACCOUNT_ID?.trim(); const apiToken = env.CF_API_TOKEN?.trim(); |
| 138 | if (!accountId || !apiToken) throw new Error("CF_ACCOUNT_ID and CF_API_TOKEN are required; use --input for offline receipts or --sql for query plans"); |
| 139 | const [websitePayload, nativePayload] = await Promise.all([ |
| 140 | querySql({ accountId, apiToken, sql: sql.website }), |
| 141 | querySql({ accountId, apiToken, sql: sql.native }), |
| 142 | ]); |
| 143 | const website = rows(websitePayload); const native = rows(nativePayload); |
| 144 | return buildFunnelReport({ format: "codewhale-funnel-receipt-v1", source: "analytics-engine", coverage: { from, to, complete: true, accepted_only: true }, website_rows: website, native_rows: native }); |
| 145 | } |
| 146 | |
| 147 | if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { |
| 148 | main().then((report) => process.stdout.write(`${JSON.stringify(report, null, 2)}\n`)).catch((error) => { process.stderr.write(`report:funnel: ${error instanceof SyntaxError ? "invalid JSON receipt or query response" : error.message}\n`); process.exitCode = 1; }); |
| 149 | } |
| 150 |