splithub 0.6.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/README.md +5 -5
  2. package/dist/{alerts-WOWJ3MZV.js → alerts-B7LKEY3J.js} +4 -4
  3. package/dist/{analytics-ZGLVQDIL.js → analytics-YY3O3HGL.js} +5 -5
  4. package/dist/{chunk-4DPMTGNP.js → chunk-3H7W4UIT.js} +3 -3
  5. package/dist/chunk-3H7W4UIT.js.map +1 -0
  6. package/dist/{chunk-4AZ2EOIY.js → chunk-4K2CNZYY.js} +3 -3
  7. package/dist/chunk-4K2CNZYY.js.map +1 -0
  8. package/dist/{chunk-PWLTCKEC.js → chunk-57IKDCOM.js} +6 -6
  9. package/dist/chunk-57IKDCOM.js.map +1 -0
  10. package/dist/{chunk-3V6SD74H.js → chunk-5UN2NKIF.js} +9 -9
  11. package/dist/chunk-5UN2NKIF.js.map +1 -0
  12. package/dist/{chunk-LF4ZI43E.js → chunk-BWYRU47V.js} +2 -2
  13. package/dist/{chunk-I5YYG3NU.js → chunk-DBGNAB2J.js} +3 -3
  14. package/dist/chunk-DBGNAB2J.js.map +1 -0
  15. package/dist/{chunk-Q5LYYWYC.js → chunk-FSMUHH4G.js} +15 -15
  16. package/dist/chunk-FSMUHH4G.js.map +1 -0
  17. package/dist/{chunk-XT7Z5GY2.js → chunk-H2OU4PJA.js} +2 -2
  18. package/dist/{chunk-JQA3WWEQ.js → chunk-K7KLCGYY.js} +4 -4
  19. package/dist/chunk-K7KLCGYY.js.map +1 -0
  20. package/dist/{chunk-5R6543RT.js → chunk-KXER4ZZ3.js} +6 -6
  21. package/dist/chunk-KXER4ZZ3.js.map +1 -0
  22. package/dist/{chunk-NZ4RSQ56.js → chunk-LFEVNQ75.js} +3 -3
  23. package/dist/{chunk-NZ4RSQ56.js.map → chunk-LFEVNQ75.js.map} +1 -1
  24. package/dist/{chunk-DOPSOUUT.js → chunk-LGL7JY6Y.js} +7 -7
  25. package/dist/chunk-LGL7JY6Y.js.map +1 -0
  26. package/dist/{chunk-BDCKWKJB.js → chunk-LOYPA5WN.js} +32 -32
  27. package/dist/chunk-LOYPA5WN.js.map +1 -0
  28. package/dist/{chunk-IIX2EISO.js → chunk-NQDGMBRF.js} +4 -4
  29. package/dist/chunk-NQDGMBRF.js.map +1 -0
  30. package/dist/{chunk-GWWJHAH4.js → chunk-OH735OOS.js} +4 -4
  31. package/dist/chunk-OH735OOS.js.map +1 -0
  32. package/dist/{chunk-BLEJ5DOY.js → chunk-OTK6B4QC.js} +2 -2
  33. package/dist/chunk-OTK6B4QC.js.map +1 -0
  34. package/dist/{chunk-KWL6EUML.js → chunk-Q6JPYA4Y.js} +3 -3
  35. package/dist/chunk-Q6JPYA4Y.js.map +1 -0
  36. package/dist/{chunk-VMYL36BP.js → chunk-QJQKARDO.js} +2 -2
  37. package/dist/{chunk-7ADMC5F3.js → chunk-RZGKAVA6.js} +3 -3
  38. package/dist/chunk-RZGKAVA6.js.map +1 -0
  39. package/dist/{chunk-ISEVDVKJ.js → chunk-SAH2BATZ.js} +3 -3
  40. package/dist/chunk-SAH2BATZ.js.map +1 -0
  41. package/dist/{chunk-H5GMGCOT.js → chunk-W66MJG3R.js} +2 -2
  42. package/dist/chunk-W66MJG3R.js.map +1 -0
  43. package/dist/{chunk-JFRRGBZU.js → chunk-X2ICUB5B.js} +5 -5
  44. package/dist/chunk-X2ICUB5B.js.map +1 -0
  45. package/dist/{ci-G4IQPM5K.js → ci-W72GPWEB.js} +2 -2
  46. package/dist/{connect-BICSF6XG.js → connect-5TIWPEIS.js} +11 -11
  47. package/dist/connect-5TIWPEIS.js.map +1 -0
  48. package/dist/{create-7VLV2H67.js → create-J2WN55LX.js} +3 -3
  49. package/dist/{dev-3CPW4LTF.js → dev-4UQ6KKB7.js} +3 -3
  50. package/dist/{doctor-L7NTDL2E.js → doctor-HYTPYAEW.js} +4 -4
  51. package/dist/domains-YIY7HXOS.js +10 -0
  52. package/dist/{experiment-reports-AN4S7PYS.js → experiment-reports-WCMLX34L.js} +5 -5
  53. package/dist/index.js +31 -31
  54. package/dist/index.js.map +1 -1
  55. package/dist/init-PTDL6EON.js +19 -0
  56. package/dist/{lifecycle-RROP7JMK.js → lifecycle-NKPKM76H.js} +3 -3
  57. package/dist/{links-DYSFIVRV.js → links-YD6QLNKY.js} +4 -4
  58. package/dist/{login-JIH5576K.js → login-4OQI2Q45.js} +3 -3
  59. package/dist/{menu-TCO6OVKR.js → menu-APVGU6TP.js} +26 -26
  60. package/dist/menu-APVGU6TP.js.map +1 -0
  61. package/dist/{notes-KHLQUNEF.js → notes-NSWGMP2V.js} +4 -4
  62. package/dist/{plan-BYRG2YK6.js → plan-DZGPGSIE.js} +3 -3
  63. package/dist/plan-DZGPGSIE.js.map +1 -0
  64. package/dist/{push-6MOHROGS.js → push-AI2M56OS.js} +3 -3
  65. package/dist/{remove-C65D4VDA.js → remove-R3AS4XYY.js} +2 -2
  66. package/dist/{report-Z5XHK5D6.js → report-VTJZEITT.js} +4 -4
  67. package/dist/report-VTJZEITT.js.map +1 -0
  68. package/dist/{results-3UYAU4OP.js → results-PZERL5HO.js} +6 -6
  69. package/dist/{review-FOE4IIXA.js → review-IB7Y2OIF.js} +2 -2
  70. package/dist/{ship-6HWSIA2E.js → ship-CFM5M6N3.js} +2 -2
  71. package/dist/{skills-RBRC7UWI.js → skills-GJGOA4HL.js} +4 -4
  72. package/dist/status-SOOLWHLW.js +17 -0
  73. package/package.json +3 -3
  74. package/dist/chunk-3V6SD74H.js.map +0 -1
  75. package/dist/chunk-4AZ2EOIY.js.map +0 -1
  76. package/dist/chunk-4DPMTGNP.js.map +0 -1
  77. package/dist/chunk-5R6543RT.js.map +0 -1
  78. package/dist/chunk-7ADMC5F3.js.map +0 -1
  79. package/dist/chunk-BDCKWKJB.js.map +0 -1
  80. package/dist/chunk-BLEJ5DOY.js.map +0 -1
  81. package/dist/chunk-DOPSOUUT.js.map +0 -1
  82. package/dist/chunk-GWWJHAH4.js.map +0 -1
  83. package/dist/chunk-H5GMGCOT.js.map +0 -1
  84. package/dist/chunk-I5YYG3NU.js.map +0 -1
  85. package/dist/chunk-IIX2EISO.js.map +0 -1
  86. package/dist/chunk-ISEVDVKJ.js.map +0 -1
  87. package/dist/chunk-JFRRGBZU.js.map +0 -1
  88. package/dist/chunk-JQA3WWEQ.js.map +0 -1
  89. package/dist/chunk-KWL6EUML.js.map +0 -1
  90. package/dist/chunk-PWLTCKEC.js.map +0 -1
  91. package/dist/chunk-Q5LYYWYC.js.map +0 -1
  92. package/dist/connect-BICSF6XG.js.map +0 -1
  93. package/dist/domains-J5SKVM6S.js +0 -10
  94. package/dist/init-Q234CCOT.js +0 -19
  95. package/dist/menu-TCO6OVKR.js.map +0 -1
  96. package/dist/plan-BYRG2YK6.js.map +0 -1
  97. package/dist/report-Z5XHK5D6.js.map +0 -1
  98. package/dist/status-RLKOX6NA.js +0 -17
  99. /package/dist/{alerts-WOWJ3MZV.js.map → alerts-B7LKEY3J.js.map} +0 -0
  100. /package/dist/{analytics-ZGLVQDIL.js.map → analytics-YY3O3HGL.js.map} +0 -0
  101. /package/dist/{chunk-LF4ZI43E.js.map → chunk-BWYRU47V.js.map} +0 -0
  102. /package/dist/{chunk-XT7Z5GY2.js.map → chunk-H2OU4PJA.js.map} +0 -0
  103. /package/dist/{chunk-VMYL36BP.js.map → chunk-QJQKARDO.js.map} +0 -0
  104. /package/dist/{ci-G4IQPM5K.js.map → ci-W72GPWEB.js.map} +0 -0
  105. /package/dist/{create-7VLV2H67.js.map → create-J2WN55LX.js.map} +0 -0
  106. /package/dist/{dev-3CPW4LTF.js.map → dev-4UQ6KKB7.js.map} +0 -0
  107. /package/dist/{doctor-L7NTDL2E.js.map → doctor-HYTPYAEW.js.map} +0 -0
  108. /package/dist/{domains-J5SKVM6S.js.map → domains-YIY7HXOS.js.map} +0 -0
  109. /package/dist/{experiment-reports-AN4S7PYS.js.map → experiment-reports-WCMLX34L.js.map} +0 -0
  110. /package/dist/{init-Q234CCOT.js.map → init-PTDL6EON.js.map} +0 -0
  111. /package/dist/{lifecycle-RROP7JMK.js.map → lifecycle-NKPKM76H.js.map} +0 -0
  112. /package/dist/{links-DYSFIVRV.js.map → links-YD6QLNKY.js.map} +0 -0
  113. /package/dist/{login-JIH5576K.js.map → login-4OQI2Q45.js.map} +0 -0
  114. /package/dist/{notes-KHLQUNEF.js.map → notes-NSWGMP2V.js.map} +0 -0
  115. /package/dist/{push-6MOHROGS.js.map → push-AI2M56OS.js.map} +0 -0
  116. /package/dist/{remove-C65D4VDA.js.map → remove-R3AS4XYY.js.map} +0 -0
  117. /package/dist/{results-3UYAU4OP.js.map → results-PZERL5HO.js.map} +0 -0
  118. /package/dist/{review-FOE4IIXA.js.map → review-IB7Y2OIF.js.map} +0 -0
  119. /package/dist/{ship-6HWSIA2E.js.map → ship-CFM5M6N3.js.map} +0 -0
  120. /package/dist/{skills-RBRC7UWI.js.map → skills-GJGOA4HL.js.map} +0 -0
  121. /package/dist/{status-RLKOX6NA.js.map → status-SOOLWHLW.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/skills-self-hosted.ts","../src/skills-ship.ts","../src/skills-analytics.ts","../src/skills-apps.ts","../src/skills.ts","../src/templates.ts"],"sourcesContent":["// Skill: sh2 with the user's own database (self mode) and reporting from the cloud.\n// Bundled fallback; sh2 Cloud serves the current text at GET /v1/skills.\nexport const SKILL_SELF_HOSTED = `---\nname: splithub-self-hosted\ndescription: Keep sh2 events in your own database (self mode): which tables, how to write a Store for Postgres, MySQL, Prisma, Drizzle, Supabase or anything else, where the ingest route lives, how the CLI reads results from it, and how to get cloud data into your own database for reports. Use when the user wants data in their infra or asks about tables, schema or reporting.\n---\n\n# sh2 with your own database\n\nTwo ways to own the data:\n\n1. **Self mode** — the app hosts the ingest route and the store; nothing leaves your infra.\n \\`splithub.config.ts\\`: \\`storage: { mode: 'self', endpoint: '/api/splithub' }\\`.\n2. **Cloud + export** — events go to sh2 Cloud; you pull summaries into your warehouse for reports.\n\n## Self mode: the pieces\n\n- Route: \\`app/api/splithub/[[...path]]/route.ts\\` (Next.js) or any fetch-style handler from\n \\`createSplitHubHandler({ config, store, adminToken })\\` in \\`@splithub/node\\`. It accepts\n \\`POST /events\\` from the SDK and answers \\`GET /status\\`, \\`GET /results/<id>\\` for the CLI\n (\\`npx splithub status\\` talks to the local dev server, or \\`--url https://your.app/api/splithub\\`).\n Self-hosted reads are raw numbers per variant (\\`variants[]\\`: visitors, conversions, rate, revenue)\n with \\`analysis: { available: false }\\`. Verdicts, data-quality stars and recommendations come with sh2 Cloud,\n and so do slices, breakdowns, timelines and raw experiment events (\\`results --from/--filter/--by\\` answer \\`NOT_CLOUD\\` here).\n With an analytics property the SDK sends \\`track()\\` as one \\`event\\` row and a page as one \\`page\\` row; the handler\n stores the goal rows experiments need next to them (goals of the config's experiments only), so the store sees goals as before.\n- Store: an object with three methods (below). Ready-made: \\`@splithub/adapter-sqlite\\`\n (Node 22.13+, \\`node:sqlite\\`, zero setup) and \\`@splithub/adapter-d1\\` (Cloudflare D1).\n \\`npx splithub init --mode self --db postgres|mysql|custom\\` writes \\`splithub/store.ts\\` with a\n working Postgres (pg) or MySQL (mysql2) store, or a documented stub for anything else.\n- Admin token: set \\`SPLITHUB_ADMIN_TOKEN\\` in the app and \\`--token\\` / \\`SPLITHUB_ADMIN_TOKEN\\` for\n the CLI, so results are not public.\n\n## The events table\n\nOne table, one row per event. Column names are yours; the templates use these:\n\n| column | type | meaning |\n|---|---|---|\n| id | text, primary key | client-generated, unique; dedupe on it (retries resend batches) |\n| type | text | \\`exposure\\` or \\`goal\\` |\n| experiment, variant | text | for exposures |\n| goal | text | for goals |\n| visitor_id, session_id | text | \\`sh_vid\\` cookie / session |\n| ts | bigint | client time, unix ms |\n| url | text | page |\n| props | json | goal payload, e.g. \\`{ \"revenue\": 49 }\\` |\n| received_at | bigint | server time, unix ms |\n| host, country, device, browser | text | request metadata (fill from headers if you want breakdowns) |\n\nIndexes: \\`(type, experiment, visitor_id, ts)\\` and \\`(type, goal, visitor_id, ts)\\`.\n\n## The Store interface (\\`@splithub/node\\`)\n\n\\`\\`\\`ts\ninterface Store {\n insertEvents(events: StoredEvent[]): Promise<number>; // skip existing ids, return inserted count\n variantCounts(experiment: string, goal: string): Promise<VariantCounts[]>; // per variant: exposures, conversions, revenue\n summaries(): Promise<ExperimentSummary[]>; // per experiment: exposures, visitors, first/last ts\n close?(): Promise<void> | void;\n}\n\\`\\`\\`\n\nAttribution rule — keep it exactly, so self-hosted results equal the cloud's:\n**a visitor converts for a variant when they sent the goal at or after their first exposure to\nthat variant; exposures and conversions count unique visitors.** The SQL in the generated\n\\`splithub/store.ts\\` implements it (CTE \\`first_exposure\\`, then goals joined with \\`ts >= first_ts\\`).\n\nPrisma / Drizzle: map the table in your schema and write the three methods with the ORM, or run the\none raw query for \\`variantCounts\\`. Supabase: the same SQL as a Postgres function called through\n\\`rpc\\`. Mongo: \\`$group\\` by variant and visitor with \\`$min ts\\`, then \\`$lookup\\` goals.\n\n## Reports from the cloud into your database\n\n- CSV: dashboard → experiment → Export (summary, daily timeline, raw events up to 50k rows).\n- Webhook channel for alerts and the digest: POST JSON to your endpoint when something happens.\n- Scheduled pull: a cron in your app calls \\`GET /v1/status\\` and \\`GET /v1/results/<id>\\` with the\n API key (\\`sk_…\\`) and stores the verdicts. Raw events live 30–90 days in the cloud (plan dependent),\n aggregates a year: pull summaries, not raw rows, for long-term reporting.\n- Need every raw event forever in your infra? Use self mode; one store per project.\n\n## Do not\n\n- Put database credentials in \\`splithub.config.ts\\` (it ships to the browser). They belong in the route's env.\n- Call a winner from raw rates: a higher rate is often noise. Say the numbers as they are; verdicts come with sh2 Cloud.\n`;\n","// Skills: ship the winner (`splithub ship`) and the full agent loop. Installed next\n// to the other skills by `splithub init` / `splithub skills`.\n\nexport const SKILL_SHIP = `---\nname: splithub-ship\ndescription: Ship the winner of an experiment and remove the experiment from the code: keep only the winning value, component or page, delete the losing variants, finish the experiment and clean splithub.config.ts. Use when an experiment has a verdict and the user says ship it, roll out the winner, remove the experiment, or clean up; and whenever an experiment shows status finished and the user agreed on which variant to keep.\n---\n\n# Shipping the winner\n\nGoal: the app behaves exactly as the kept variant did, with no experiment left in the code or in the config.\n\n## 1. Decide\n\n\\`npx splithub results <id> --json\\` (MCP: \\`splithub_results\\`). Act on \\`verdict.status\\`:\n- \\`winner_found\\`: keep \\`verdict.winner\\`.\n- \\`no_significant_difference\\`: keep the control, or the simpler variant if the user agrees.\n- \\`insufficient_sample\\`: do not ship. Say when to look again: \\`daysToVerdict\\` days at the current traffic.\n- \\`srm_detected\\`: do not ship. The split is broken; fix the setup first.\n- \\`guardrail_breached\\`: do not ship the variant in \\`verdict.guardrailBreached\\`; it made a guardrail worse. Say what broke.\nAsk the user which variant to keep before going on. Never pick from raw rates.\n\n## 2. Preview, then ship\n\n\\`\\`\\`bash\nnpx splithub ship <id> --keep <variant> --dry-run --json # diff + leftovers, nothing written\nnpx splithub ship <id> --keep <variant> --json # apply\n\\`\\`\\`\nMCP: \\`splithub_ship\\` with \\`dryRun: true\\`, then without. It archives the experiment in the cloud (numbers stay readable), removes it from\n\\`splithub.config.ts\\` (checked by reloading the file) and rewrites the code:\n- \\`<Experiment id>\\` → the kept \\`<Variant>\\`'s children; the other variants are dropped.\n- \\`useValue('<id>')\\` / \\`sh.value('<id>')\\` → the kept value as a literal.\n- \\`useVariant('<id>')\\` comparisons, ternaries, \\`&&\\`, \\`if\\` and \\`switch\\` → the kept branch.\n- Unused \\`Experiment\\`, \\`Variant\\`, \\`useVariant\\`, \\`useValue\\` imports go.\n\n## 3. Finish by hand\n\n- \\`leftovers[]\\`: each \\`{ file, line, text, reason }\\` still mentions the experiment; rewrite those yourself.\n- component kind: delete components and files only the losing variants used (e.g. \\`splithub/<id>/\\`).\n- redirect kind: make the kept URL the real page (move the route or add a permanent redirect), delete the other page.\n- Goal: keep \\`track('<goal>')\\` when another experiment measures it (\\`next\\` says so); otherwise ask before removing it.\n- Cloud mode: \\`npx splithub push\\`. Then \\`npx splithub doctor\\` and the project's typecheck and tests.\n- \\`npx splithub refs <id> --json\\` must return \\`count: 0\\` for the experiment.\n\nReport what changed (files, the kept content) and the verdict in one line with its numbers. Never reuse the id.\n`;\n\nexport const SKILL_LOOP = `---\nname: splithub-loop\ndescription: The whole experiment loop for an agent with sh2, step by step with the MCP tools and CLI --json fields: plan, create, implement, check, push, read results, finish, ship. Use when the user asks to run an experiment end to end, or to pick up an experiment where it stands.\n---\n\n# The full loop\n\nEach step: MCP tool, or the CLI with \\`--json\\` (one line of JSON; errors are \\`{ error, code, hint }\\`, exit 1).\n\n| step | MCP tool | CLI | read |\n|---|---|---|---|\n| 0. size it | \\`splithub_plan\\` | \\`plan --baseline 0.05 --mde 0.1 [<id>]\\` | \\`perVariant\\`, \\`total\\`, \\`traffic.daysLeft\\` |\n| 1. create | \\`splithub_experiment_create\\` | \\`create --kind … --id … --goal … --yes\\` | \\`snippet\\`, \\`files\\`, \\`nextStep\\`, \\`handoff\\` |\n| 2. implement | (edit code) | | wire \\`snippet\\`; \\`track('<goal>')\\` where it converts |\n| 3. check | \\`splithub_doctor\\`, \\`splithub_refs\\` | \\`doctor\\`, \\`refs <id>\\` | \\`ok\\`, \\`checks[]\\`; \\`refs[]\\` shows the wiring |\n| 4. push (cloud) | \\`splithub_push\\` | \\`push\\` (\\`--dry-run\\` to preview) | \\`adopted\\`, \\`diff\\` |\n| 5. results | \\`splithub_status\\`, \\`splithub_results\\` | \\`status\\`, \\`results <id>\\` | \\`verdict.status\\`, \\`verdict.message\\`, \\`verdict.notes[]\\`, \\`daysToVerdict\\` |\n| 6. finish | \\`splithub_experiment_status\\` | \\`finish <id>\\` | \\`live\\`, \\`next\\` |\n| 7. ship | \\`splithub_ship\\` | \\`ship <id> --keep <v> [--dry-run]\\` | \\`diff\\`, \\`leftovers[]\\`, \\`next\\` |\n\nRules that keep the answer honest:\n- Plan before creating: if \\`traffic.daysLeft\\` is months, try a bigger change or a busier page.\n- \\`create\\` writes a running experiment; it goes live when the code is deployed (and pushed in cloud mode). Tell the user.\n- Verdicts are sequential (always-valid): checking any day is safe. Quote \\`verdict.message\\` and the always-valid\n \\`comparisons[].sequential.pValue\\`, not the fixed-horizon \\`pValue\\` (p = 0.01 there can still be not significant).\n Relay \\`verdict.notes[]\\`. Verdicts depend on sample size, not days. Say \\`verdict.sample.quality\\` (small | ok | good;\n good = every variant has its share of \\`goodSample\\`, default 5000 visitors, \\`create --good-sample\\`) next to the verdict.\n- \\`daysToVerdict\\` is the re-check date: schedule (or tell the user) a look in that many days instead of polling.\n- \\`srm_detected\\`: the split is broken; fix the setup, do not read the numbers.\n- \\`guardrail_breached\\`: don't ship. A variant made a guardrail worse (\\`verdict.guardrailBreached[]\\`), e.g. \"bold wins on\n signups but raises refunds\". \\`verdict.metrics[]\\` has the secondary metrics and guardrails, read like the main table.\n- Guard what matters when creating: \\`--secondary pricing_view --guardrail refunds:higher\\` (MCP: \\`secondary\\`, \\`guardrails\\`).\n Experiments that could clash on one page go in one layer: \\`--layer checkout:0-50\\` and \\`checkout:50-100\\` never share a visitor.\n- \\`splithub holdout set 5\\` keeps 5% of visitors out of every experiment; the \\`__holdout\\` row (\"Holdout: long-term impact\")\n compares them with everyone else.\n- Ask the user which variant to keep before \\`ship\\`; preview with \\`dryRun\\` and show them the diff.\n- Error \\`code\\` → action: \\`NOT_LOGGED_IN\\` → \\`splithub_login\\`, show the link, wait, retry · \\`INSUFFICIENT_SCOPE\\` → the key\n can only read; ask for a key with write scope · \\`NO_CONFIG\\` → \\`splithub_init\\` ·\n \\`EXPERIMENT_NOT_FOUND\\` → \\`splithub_status\\` for ids · \\`CONFIG_UNSAFE\\` → edit the config by hand where the experiment is\n defined · \\`CONFIG_WRITE\\` → the file was restored; edit by hand, then \\`doctor\\`.\n`;\n","// Skill: analytics properties (pageviews and custom events, read as reports).\n\nexport const SKILL_ANALYTICS = `---\nname: splithub-analytics\ndescription: Collect and read web analytics with sh2: analytics properties (pageviews, events with track(), identified users, sources, channels, pages, goals and conversions), setting one up in the app (analytics connect), funnels, paths, retention, realtime, event props, CSV export, segments, notes and alerts on traffic, sh.js or the SDK, allowed domains. Use when the user wants traffic numbers, page or source reports, event tracking, funnels, or asks to \"add analytics\" to an app that uses sh2 or could.\n---\n\n# sh2 analytics\n\nAn analytics property is a stream of pageviews and custom events, like a site in Google Analytics. It sits next to the\nexperiments: same config file, same CLI, same key, same storage choice (sh2 Cloud or the app's own database).\nThere are no variants and no verdicts: reports are counts.\n\n## Set it up\n\n1. One step: \\`npx splithub analytics connect --json\\` (or Analytics → Set up in the \\`npx splithub\\` menu) picks the project's\n property (or creates one: \\`--name \"Marketing site\"\\`; a given id is used, \\`connect sh-x1h78w\\`) and adds\n \\`property=\"sh-…\"\\` to the one \\`<SplitHubProvider>\\` / \\`<SplitHubNextProvider>\\` in the code. It answers \\`wired.status\\`:\n added | already | other (another property is named there: ask, then \\`--force\\`) | none | many (add \\`snippets.provider\\`\n or \\`snippets.script\\` yourself), plus \\`snippets.track\\` and \\`next\\`.\n By hand: \\`npx splithub analytics create --name \"Marketing site\" --json\\` writes \\`properties: { 'sh-x1h78w': { name: … } }\\`\n into \\`splithub.config.ts\\` (self-hosted projects keep their properties there). Cloud mode: both also create it in the\n cloud at once (\\`live: applied\\`), so no push is needed; when \\`live\\` names a missing API key, \\`npx splithub login\\` and run it\n again, or \\`npx splithub push\\`. A property made in the dashboard needs no push either; its id is on its page.\n2. Send events. Events go only to a property named by its id, never to a guess:\n - SDK: \\`<SplitHubProvider config={config} property=\"sh-x1h78w\">\\`: a pageview on load and on every client-side route change.\n - Events: one call, \\`const track = useTrack(); track('Video Played', { id: 3 })\\` (or \\`client.track(...)\\`). Names: letters,\n digits, spaces and \\`_ . : / -\\`, up to 64 characters; props: a flat object up to 4 KB. The same call counts for\n experiments whose goal is that event. Only what the app passes to \\`track()\\` is sent.\n - Users: \\`const identify = useIdentify(); identify(user.id, { plan: 'pro' })\\` after sign-in (\\`identify(null)\\` on sign-out;\n sh.js: \\`splithub.identify(id, traits)\\`) ties visits to the app's user; reports then count \\`users\\`. No emails or names in traits.\n - No SDK: \\`<script src=\"https://go.sh2.uk/sh.js\" data-key=\"pk_…\" async></script>\\` sends pageviews (SPA navigations\n included) and \\`window.splithub.track(name, props)\\` once the tag has \\`data-property=\"sh-x1h78w\"\\`.\n - One install covers analytics and experiments: the provider (or sh.js) with \\`property\\` collects pageviews and runs\n experiments. Each \\`track()\\` sends one event row and each page one page row; experiments whose goal is that event or\n page count them from those rows, so nothing extra is sent or billed. Never add sh.js and the SDK for the same\n property: when both run on a page, only the first collects pageviews.\n - Servers and other languages: \\`POST /v1/events\\` with \\`{ type: 'page', prop, url, vid, sid, ts, id, title?, ref? }\\` or\n \\`{ type: 'event', prop, name, props?, … }\\` (splithub-api skill).\n3. Development never sends to the cloud (same rule as experiments): check a deploy or \\`vite preview\\`.\n4. Events: any name is recorded, nothing to declare first. A goal is an event marked as one (\\`goals\\` in the config, the\n goal switch on an event in the dashboard, or simply naming the event as an experiment's goal); goals count as\n conversions in every property (a property's \\`goals\\` list narrows that). \\`value\\` is what one conversion is worth\n when the event carries no \\`revenue\\` prop; \\`event: 'Video Played'\\` matches an event name that is not a valid key.\n\n## Read it\n\n- \\`npx splithub analytics --json\\`: every property with visitors, visits, pageviews and bounce for the last 30 days.\n- \\`npx splithub status --json\\` (sh2 Cloud) also lists every property under \\`properties\\`: the last 7 days against the 7 before\n (visitors, \\`change\\`, goal conversions); \\`npx splithub report\\` adds them as an Analytics table. The digest (Pro, set in the\n dashboard under Alerts) covers properties too: visitors, top sources and pages, goals and events against the period before.\n- \\`npx splithub analytics site --json\\` (\\`--days 7\\`, or \\`--from 2026-10-01 --to 2026-10-31\\`): totals, \\`users\\` (identified),\n goals (conversions = unique visitors who reached the goal in the range, completions, revenue), top pages, top sources, notes.\n- \\`--by page|source|channel|referrer|utm_source|utm_medium|utm_campaign|country|device|browser|os|platform|app_version|entry|exit|event|goal\\`; with a\n visit dimension, \\`--goal signup\\` adds conversions per row; \\`--by variant --experiment hero\\` splits visits by the\n variant each visitor saw, \\`--by trait --key plan\\` by an identify() trait. \\`--filter country=DE,FR --filter source=\"(none)\"\\` narrows any report.\n- \\`npx splithub analytics events site --json\\`: the latest raw pageviews and events, to check tracking right after wiring it.\n- More reports (sh2 Cloud), each with the same \\`--days\\` / \\`--from --to\\` / \\`--filter\\` flags:\n - \\`analytics funnel site --steps \"page:/,event:Signup,goal:paid\" [--within visit|7d|30d] [--by country]\\`: visitors per step\n in order, \\`conversion\\` (share of step 1) and \\`dropoff\\` (share lost since the step before).\n - \\`analytics funnels site\\`: the funnels saved on the property (its Funnels tab, shared with the team).\n \\`--save Signup --steps \"page:/,goal:signup\" [--within 7d]\\` saves one (a saved name updates it), \\`--delete <id|name>\\`\n removes one, and \\`analytics funnel site --funnel Signup\\` runs it. Save a funnel the user will want to read again.\n - \\`analytics paths site --page /pricing [--prev]\\`: where visits went next (or came from).\n - \\`analytics retention site [--start visit|event:<name>|goal:<key>] [--return visit|event:<name>] [--period day|week]\\`: cohorts\n \\`{ start, users, retained[] }\\`, \\`retained[0]\\` = the cohort period itself; up to 90 days or 26 weeks (\\`clamped\\`).\n - \\`analytics realtime site\\`: visitors in the last 5 minutes, top pages and sources.\n - \\`analytics props site --event Signup [--key plan]\\`: an event's prop names, or one prop's values.\n - \\`analytics export site --by page|day [--raw] > report.csv\\`: CSV to stdout.\n - \\`--compare\\` on a report adds the period right before (\\`previous\\`), \\`--compare year\\` the same days a year earlier, \\`--compare 2026-08-01..2026-08-31\\` chosen days; \\`--segment \"Paid traffic\"\\` applies a saved segment\n (\\`analytics segments\\`, \\`--save <name> country=DE\\`, \\`--delete <id|name>\\`).\n - Notes mark a day on the charts: \\`npx splithub notes add \"Launched new pricing\" [--kind win] [--property site] [--day 2026-10-05]\\`,\n \\`notes --property site\\` lists them; add one when you ship something that may move traffic.\n - Alerts on a property (sh2 Cloud, Pro): \\`npx splithub alerts add traffic_drop --property site --percent 50\\`, \\`traffic_spike\\`,\n \\`goal_silent --property site --goal signup --hours 24\\`, \\`event_count --property site --event Signup --count 1000 [--repeat]\\`.\n- Words: a visit (\\`sessions\\`) ends after 30 minutes without events; a bounce is a visit with one page and no event;\n \\`source\\` is the UTM source or the referrer's site (Google, Facebook, …), \\`(none)\\` = direct; \\`channel\\` groups them (Direct,\n Organic Search, Paid Social, Email, Referral, …); a conversion is a visitor reaching a goal (once per visitor in the range);\n \\`duration\\` is in milliseconds. Bots are never counted.\n- Self-hosted (\\`mode: 'self'\\`): the same commands give raw counts from the app's database (pageviews, visitors,\n sessions, events by name) for \\`--days\\` or \\`--from --to\\` (UTC days). Filters, \\`--by\\`, \\`--compare\\` and reports with sources,\n pages, visits and conversions come with sh2 Cloud: say so.\n\n## Manage it\n\n- \\`npx splithub analytics pause site\\` / \\`resume site\\`: live in the cloud within a minute; paused events are dropped and not billed.\n- \\`npx splithub analytics archive site\\` / \\`restore site\\` (sh2 Cloud): like Archive in the dashboard, it stops collecting and leaves\n the list (\\`archived\\` in it), numbers kept; restored comes back paused.\n- \\`npx splithub analytics remove site\\`: out of the config (push next); a dashboard-made property is deleted with its numbers.\n- Allowed domains are per experiment and per property: \\`npx splithub domains set property site example.com\\` (subdomains included),\n \\`npx splithub domains clear property site\\` (any domain again), \\`npx splithub domains\\` lists them all. An empty list\n accepts every origin. Add localhost too when testing from it.\n- Apps: \\`kind: 'app'\\` on a property (\\`analytics create --kind app\\`, the default in an app project) shows screens, versions and\n retention in the dashboard; screens are page events (the \\`splithub-apps\\` skill).\n- Billing: every pageview and custom event counts like one exposure against the project's allowance.\n\n## Do not\n\n- Put personal data in event props (emails, names, ids from other systems).\n- Fire an event in a render loop or on every scroll: each one is stored and billed.\n- Read analytics counts as an experiment result: use \\`splithub results\\` for experiments.\n`;\n","// Skill: experiments and analytics in mobile and desktop apps (React Native / Expo, iOS, Android).\n\nexport const SKILL_APPS = `---\nname: splithub-apps\ndescription: Run sh2 experiments and analytics in a mobile or desktop app: React Native and Expo (@splithub/react-native), native iOS (Swift package SplitHub) and Android (io.splithub:splithub). Screens, app_version targeting, retention, and why app experiments are created in the cloud. Use when the project has react-native, expo, an Xcode project or an Android Gradle build, or the user asks to A/B test or measure an app.\n---\n\n# sh2 in apps\n\nSame experiments, goals and analytics as on the web. Two things differ: an app's config is built into the binary,\nand screens take the place of pages.\n\n## Install\n\n- React Native / Expo: \\`npx splithub init --mode cloud --yes --json\\`. It installs \\`@splithub/react-native\\` (plus\n \\`@react-native-async-storage/async-storage\\`, through \\`npx expo install\\` on Expo) and wraps the entry in\n \\`<SplitHubProvider config={config}>\\`: \\`app/_layout.tsx\\` with Expo Router (adds \\`<ExpoRouterScreens />\\`),\n else \\`App.tsx\\` (adds \\`<NavigationScreens />\\` inside \\`<NavigationContainer>\\` with React Navigation). Both come from\n \\`@splithub/react-native\\`; the hooks \\`useExpoRouterTracking()\\` / \\`useNavigationTracking(ref)\\` do the same by hand.\n Without a config file: \\`<SplitHubProvider publicKey=\"pk_…\" property=\"sh-…\">\\`.\n \\`app.entry.status\\`: added | already | manual (wire \\`nextStep\\` by hand). Hooks are the web ones, imported from\n \\`@splithub/react-native\\`: \\`useValue\\`, \\`useVariant\\`, \\`<Experiment>\\`, \\`useTrack\\`, \\`useIdentify\\`.\n- iOS: Swift package \\`SplitHub\\` (Xcode: File → Add Package Dependencies → \\`https://github.com/splithub-io/splithub-sdk\\`).\n \\`SplitHub.start(publicKey: \"pk_…\", property: \"sh-…\")\\` once at launch; \\`SplitHub.variant(\"id\")\\`, SwiftUI \\`SplitHubExperiment(\"id\") { variant in }\\`.\n- Android: \\`implementation(\"io.splithub:splithub:<version>\")\\` (+ \\`io.splithub:splithub-compose\\` for Compose).\n \\`SplitHub.start(this, \"pk_…\", property = \"sh-…\")\\` in \\`Application.onCreate\\`; \\`SplitHub.variant(\"id\")\\`, Compose \\`Experiment(\"id\") { variant -> }\\`, \\`TrackScreen(\"Home\")\\`.\n- Native apps have no \\`splithub.config.ts\\`: \\`init\\` prints the install lines and a quick start, and experiments come from the cloud.\n- Analytics: \\`npx splithub analytics connect --json\\` names a property on the provider; in an app project it is created with \\`kind: 'app'\\`.\n- \\`npx splithub doctor\\` checks the package, the storage module and the provider.\n\n## Experiments reach apps through the cloud\n\n- The config file ships inside the binary: an experiment added there reaches users only with the next store release,\n and only users who update. Old versions stay on what they were built with.\n- Start new experiments in the dashboard (no release; installed apps get them on the next launch with network). Pause,\n finish, weights and values set in the dashboard or with \\`npx splithub pause|start|finish <id>\\` also apply live.\n- Still \\`npx splithub push\\` after any config change, so the cloud and the file agree. Apps also receive the pushed\n experiments from the cloud (overrides JSON with \\`?all=1\\`), so a pushed experiment reaches an app whose build has its variants.\n- Redirect experiments do nothing in an app: use \\`value\\` (copy, prices, flags as JSON) or \\`component\\`.\n- Assignment is the same local hash on every platform: a visitor gets the same variant on web, iOS and Android.\n\n## Screens, versions, platforms\n\n- A screen is a \\`page\\` event: url \\`/<screen name>\\` (or the route path with Expo Router), title the screen name. Every\n page report, funnel (\\`page:/Checkout\\`) and pageview goal (\\`{ type: 'pageview', path: '/Checkout' }\\`) works on screens.\n- Without a navigation tracker: \\`useScreen('Settings')\\` (React Native), \\`SplitHub.screen(\"Settings\")\\` (iOS, Android).\n- Target app versions in the experiment's flow (dashboard targeting, or by hand):\n \\`{ type: 'condition', conditions: [{ field: 'app_version', op: 'gte', value: '2.4' }], then: 'split', else: 'skip' }\\`.\n \\`gte\\` / \\`lt\\` compare dotted versions part by part (\\`2.10.0\\` ≥ \\`2.9\\`). \\`platform\\` is \\`ios | android | macos | windows | linux | web\\`.\n Gate on the version that ships the variant code, so older builds skip the experiment.\n- Break down or filter by them: \\`results <id> --by platform\\`, \\`--by app_version\\`, \\`--filter platform=ios\\`;\n \\`analytics <property> --by app_version\\`, \\`--filter app_version=2.5.0\\`.\n- Events sent offline are kept on the device and arrive later with their own time: today's numbers can still grow.\n\n## Retention\n\n\\`npx splithub analytics retention <property> [--period day|week] [--from --to] --json\\`: \\`cohorts[] { start, users, retained[] }\\`,\n\\`retained[0]\\` is the cohort period itself, \\`retained[n] / users\\` the share back in period n. Up to 90 days or 26 weeks\n(\\`clamped: true\\` when cut). \\`--start event:Signup\\` and \\`--return event:<name>\\` change who counts. Counts, never a verdict.\n`;\n","// Agent skills installed by `splithub init` / `splithub skills`. One folder per\n// topic under .claude/skills/, so an agent loads only what the task needs:\n// splithub — the library, the config file, the CLI, where things live\n// ab-testing — what a good test is, metrics, sample size, when to stop\n// splithub-api — the HTTP API (keys, endpoints, payloads) for scripts and servers\n// splithub-mcp — the MCP server: tools, how to register it in Claude Code / Cursor\n// splithub-ship — keep a variant and take the test out (`splithub ship`)\n// splithub-loop — the whole loop for an agent, tool by tool\n// splithub-analytics — analytics properties: pageviews, events, reports, allowed domains\n// splithub-apps — React Native / Expo, iOS and Android: install, screens, versions, retention\n// Same text goes to .cursor/rules and the AGENTS.md section points here.\n\nexport interface Skill {\n dir: string;\n body: string;\n}\n\nexport const SKILL_SPLITHUB = `---\nname: splithub\ndescription: Add, change, run or read experiments in an app that uses sh2 (@splithub/react, splithub.config.ts, the splithub CLI, sh2 Cloud). Use when the user asks to A/B test a component, headline, image, price, CTA or page, asks which variant is winning, or wants to start, pause or finish an experiment; also for notes on the charts, alert rules (events used, traffic, goals, winners), short links and allowed domains.\n---\n\n# sh2 for coding agents\n\nThree pieces: \\`splithub.config.ts\\` (the experiments; source of truth when it exists),\n\\`@splithub/react\\` (renders variants), the \\`splithub\\` CLI (creates, pushes, reads results).\nEvents go to the app's own database (self mode) or to sh2 Cloud (cloud mode).\n\n## Where things live\n\n- Config: \\`splithub.config.ts\\` in the project root. Experiments and goals. Ships to the browser: never put secrets in it.\n- Credentials: \\`npx splithub login\\` (or \\`init --mode cloud\\`) prints a link; the human approves it in the browser; the CLI\n stores a project API key for this folder. Never ask the user to paste keys. CI uses \\`SPLITHUB_API_KEY\\`.\n- The public key (\\`pk_\\`) ends up in \\`storage.key\\` of the config from any of: \\`login\\` (saved credentials), the first\n \\`push\\`, \\`init --key\\`, or \\`SPLITHUB_API_KEY\\` in the environment (init asks the cloud). Missing key = events go nowhere.\n- Cloud: \\`npx splithub push\\` uploads the config. Experiments the cloud has from an earlier push that the file lacks are\n kept (\\`kept\\` in the answer); only \\`npx splithub push --prune\\` removes them, and only when the user asked for that.\n \\`npx splithub pull\\` writes dashboard-created experiments into the file.\n- Results: \\`npx splithub status --json\\` (in the cloud it also has \\`properties\\`: each analytics property's last 7 days), \\`npx splithub results <id> --json\\`. Sizing: \\`npx splithub plan --baseline 0.05 --mde 0.1\\`.\n- Closer reads (cloud): \\`results <id> --from --to --filter country=DE\\` (a slice), \\`--by <dimension>\\`, \\`--timeline\\`, \\`--engagement\\`,\n \\`--events\\`, \\`--export --by <dimension>\\` or \\`--export --events\\` (CSV); \\`npx splithub events --experiment <id>\\` for the raw tail. See \"Read results\".\n- Code that uses an experiment: \\`npx splithub refs <id> --json\\`. Keep a variant and remove the experiment: \\`npx splithub ship <id> --keep <v>\\`.\n- \\`--json\\` prints one line; errors are \\`{ error, code, hint }\\` with exit code 1. \\`INSUFFICIENT_SCOPE\\` adds \\`scope\\`\n (e.g. \\`notes:write\\`): the API key is limited to some areas; ask the user for a key with that scope. The \\`splithub-loop\\` skill has the whole flow.\n- Everything interactive: \\`npx splithub\\`, one menu: Experiments, Analytics, Short links, Alerts, Notes, Allowed domains,\n push / pull, local testing, doctor, agent skills. Everything scriptable: subcommands + \\`--json\\` (\\`npx splithub --help\\`).\n- Web analytics (pageviews, events, sources, pages, funnels) live in analytics properties: \\`npx splithub analytics connect\\`\n sets one up in the app; the \\`splithub-analytics\\` skill has the rest.\n- Apps (React Native, Expo, iOS, Android): the \\`splithub-apps\\` skill. The config is built into the binary, so new\n experiments for an app start in the dashboard; screens are page events; target versions with \\`app_version\\` \\`gte\\`.\n\n## Pick the kind\n\n| kind | use it when | create | read in code |\n|---|---|---|---|\n| \\`value\\` | only data changes: text, number, image URL, price, JSON. The default choice: no new components. | \\`--variants control,bold --value control=\"Old text\" --value bold=\"New text\"\\` | \\`const text = useValue<string>('<id>')\\`; server components: \\`getValue\\` from \\`@splithub/next\\`; no SDK: \\`sh.value('<id>')\\` |\n| \\`component\\` | structure changes: a layout, a section, a flow, a different component per variant | \\`--variants control,bold\\` (the CLI scaffolds \\`splithub/<id>/<Variant>.tsx\\` stubs) | \\`<Experiment id=\"<id>\"><Variant name=\"control\">…</Variant><Variant name=\"bold\">…</Variant></Experiment>\\`, or \\`useVariant('<id>')\\` in a switch |\n| \\`redirect\\` | a whole page changes: another URL per variant | \\`--match / --to control=/ --to v2=/home-v2\\` | nothing: \\`@splithub/next\\` middleware or the drop-in script \\`<script src=\"https://go.sh2.uk/sh.js\" data-key=\"pk_…\">\\` sends visitors there |\n| \\`mvt\\` | several things change at once (headline × button × image) and the user wants to know which of them matters; every combination is tested and each factor is read on its own | \\`--factor headline=old:\"Old text\",new:\"New text\" --factor button=blue:#2563eb,green:#16a34a\\` (no \\`--variants\\`; first level = control; at most 4 factors × 4 levels, 16 combinations) | \\`const { headline, button } = useValue<{ headline: string; button: string }>('<id>')\\` |\n\nmvt needs more visitors than a two-variant experiment: every combination must reach the minimum on its own (the results show the\ncombinations and, below them, each factor summed over its combinations). With little traffic, change one thing with \\`value\\`.\n\n## Create an experiment\n\n1. \\`npx splithub create --kind <value|component|redirect|mvt> --id <key> … --goal <event name> --yes --json\\` (see the table).\n The key is the experiment's id for good: never reuse one from an earlier experiment. \\`--name \"Signup button\"\\` adds a human\n name (dashboard, CLI) that can change any time. \\`push\\` fails with \\`KEY_CONFLICT\\` when a key already belongs to\n another experiment: ask the user, then rename the key, or push with \\`--replace <key>\\` (new experiment, old numbers cleared)\n or \\`--same <key>\\` (same experiment). \\`KEY_DELETED\\`: a deleted experiment used the key; pick a new one.\n2. Goal: any event the app sends with \\`track('<name>', props?)\\`, the one call for every event. Nothing to declare\n first: a name not in \\`goals\\` becomes an event goal keyed by its slug (\\`Video Played\\` → \\`video-played\\`) and \\`create\\`\n says so. A goal is just an event marked as one; page visits and clicks are goals declared in \\`goals\\`:\n \\`{ type: 'pageview', path: '/thanks' }\\`, \\`{ type: 'click', selector: '#buy' }\\` (tracked automatically by the SDK and the script).\n With an analytics property on the provider, the same \\`track()\\` and pageviews feed both: one install, one row per action.\n3. Wire it in code. \\`create\\` writes \\`status: 'running'\\`: the experiment goes live for every visitor, first page view\n included, as soon as this code is deployed. Use \\`--status draft\\` only when the user asks to hold it.\n4. Cloud mode: \\`npx splithub push\\` after any config change.\n5. Hand-off, always: end your reply by saying the experiment is **running in the config** and goes live when the user deploys\n this code; nothing is recorded before that, and local development never sends events to the cloud. Tell them how to\n check it locally (\\`?sh_force=<id>:<variant>\\`) and that Pause in the dashboard or \\`npx splithub pause <id>\\` holds it.\n In cloud mode a status set in the dashboard wins over the file for every visitor, first page included.\n For a draft (only if asked): say visitors do not see it and nothing is recorded until \\`npx splithub start <id>\\`.\n\nA draft is invisible to visitors. To check one before starting: \\`runDraftsInDev: true\\` at the top level of the config\nserves drafts like running experiments in development only (\\`NODE_ENV=development\\`: \\`next dev\\`, \\`vite\\`);\n\\`?sh_force=<id>:<variant>\\` shows one variant on any page, draft or not, without recording an exposure;\n\\`?sh_debug=1\\` (or \\`npx splithub dev\\`) logs every decision and opens a panel to switch variants.\nIn development the SDK explains drafts, paused experiments and held-back events in one line each. Vite apps: add \\`splithub()\\`\nfrom \\`@splithub/core/vite\\` to the plugins in vite.config so these lines and a summary of every experiment appear in the\nterminal that runs \\`vite\\`; Next.js server code prints them in its terminal anyway.\n\nKeys: lowercase a-z 0-9 - _, max 64 chars. First variant = control. Weights are relative (50/50, 1/1, 90/10).\nTargeting (country, device, UTM, cookie, time) is a \\`flow\\` graph on the experiment, edited in the dashboard; \\`pull\\` brings it into the file.\n\n## Read results\n\n\\`verdict.status\\` ∈ no_data | insufficient_sample | srm_detected | winner_found | no_significant_difference.\nReport \\`verdict.message\\` verbatim and the numbers behind it (visitors per variant, lift, the always-valid\n\\`comparisons[].sequential.pValue\\` and \\`sequential.ci\\`; the plain \\`pValue\\` is fixed-horizon, for display only) and relay\n\\`verdict.notes[]\\`. Verdicts are sequential and depend on sample size, not days: safe to check any time. \\`verdict.sample.quality\\` is\nsmall (below 100 visitors per variant or 50 conversions), ok, or good (every variant has its share of \\`goodSample\\`, default 5000\nvisitors; \\`create --good-sample\\`); say it next to the verdict. \\`verdict.sample.stars\\` (0..5) scores data quality from\n\\`verdict.sample.checks[]\\`: report the stars and the unmet labels; they never override the verdict. \\`daysToVerdict\\` says when to look again.\nNever declare a winner from raw rates. \\`srm_detected\\` means the split is broken: fix the setup before anything else.\n\n### Slices, breakdowns, timelines (sh2 Cloud)\n\n- A slice: \\`npx splithub results <id> --from 2026-10-01 --to 2026-10-15 --filter country=DE --filter channel=\"Paid Search\" --json\\`.\n \\`from\\` / \\`to\\` are first-exposure days (project time zone): the visitors who entered the experiment then, with all their\n later conversions. Filters: country, region, city, device, os, browser, language, host, source, channel, utm_source,\n utm_medium, utm_campaign, utm_term, utm_content, landing or page (the page of the first exposure); comma-separated values,\n \\`(none)\\` matches empty. The answer carries \\`scope\\` and its verdict is computed on the slice only: say so and quote\n \\`scope.note\\`. The decision stays with the unfiltered verdict; a slice carries no \\`voice\\` (no advice).\n- One view at a time, same range and filters (\\`--json\\` adds \\`view\\`): \\`--by country|device|source|channel|page|landing|utm_campaign|…\\`\n gives \\`segments[]\\` with each variant's cells and its lift against the control inside the segment (\\`significant\\`, \\`better\\`,\n \\`small\\` = too few visitors); \\`--timeline\\` gives visitors and conversions per day and variant (a day = visitors first seen\n that day); \\`--engagement\\` gives bounce rate, pages per visit and visit length per variant from the analytics property on\n the same visitors (\\`property: null\\` = none); \\`--events\\` gives \\`rows[]\\` for every goal (the experiment's goal, metrics and\n guardrails first, \\`measured\\`) and event of these visitors, each with \\`perVariant\\` visitors and rate and \\`comparisons[]\\` against\n the control (\\`property: null\\` = goals only: other events need analytics on the same site). \\`--export --by <dimension>\\` prints\n the breakdown as CSV, \\`--export --events\\` the events table.\n- \\`npx splithub events --experiment <id> [--type exposure|goal] [--limit 50] [--before <nextBefore>]\\` lists the raw exposures\n and goals (same filters; 7 days, 30 on Pro). Use it to check the wiring.\n- Segments and events are for hypotheses: never call a winner from one segment or one event. With several segments, one will look great by chance.\n A self-hosted endpoint answers none of these (\\`NOT_CLOUD\\`); its results stay raw counts.\n\n## Finish, and what to do when an experiment is finished\n\n\\`npx splithub finish <id>\\` stops the experiment (live within a minute in cloud mode). A finished experiment keeps its numbers for as long\nas it stays in the config; the code still contains every variant until someone removes it.\n\nWhenever you see an experiment with \\`status: finished\\` (in \\`status\\`, \\`results\\`, the MCP tools, or right after you finished it):\n1. Read \\`npx splithub results <id> --json\\` and tell the user the verdict in one line with its numbers.\n2. Ask two questions, do not assume: **which variant to keep** (recommend \\`verdict.winner\\`; with no significant\n difference, the control or the simpler one) and **whether to remove the experiment from the code now**.\n3. On yes, follow the \\`splithub-ship\\` skill: \\`npx splithub ship <id> --keep <variant> --dry-run\\`, show the diff, then run it\n without \\`--dry-run\\`; fix the \\`leftovers\\`, \\`push\\` in cloud mode, run \\`doctor\\` and the project's checks.\n4. On no, leave everything: a finished experiment costs nothing and the user may come back to it.\n\nA \\`paused\\` experiment is not over: say so and ask whether to resume (\\`start\\`) or finish it.\n\n## Around experiments (sh2 Cloud)\n\n- **Notes**: what happened on a day, marked on experiment timelines and analytics charts. \\`npx splithub notes add \"Launched the\n new pricing page\" [--kind note|issue|win] [--experiment <key> | --property <id>] [--day 2026-10-05]\\` (none = the whole\n project); \\`notes\\` lists them (\\`--experiment\\`, \\`--property\\`, \\`--kind\\`, \\`--days\\`), \\`notes edit <id> \"<text>\"\\`, \\`notes delete <id>\\`.\n Add one when you ship something that may move the numbers.\n- **Alerts** (they fire on Pro; added on another plan they are saved switched off): \\`npx splithub alerts\\` lists rules, progress\n and recent alerts; \\`alerts add <condition>\\`: experiments \\`srm\\`, \\`winner\\`, \\`loser --lift 10\\`, \\`exposures --visitors N\\`,\n \\`conversions --conversions N\\`, \\`duration --days N\\`, \\`no_events --hours 24\\` (\\`--experiment <key>\\`, else every running one;\n \\`--pause\\`, \\`--finish\\`, \\`--drop-loser\\` act on it); account \\`quota --percent 80\\`, \\`usage --every 1000\\` (each time this month's\n events cross another 1,000); analytics \\`traffic_drop|traffic_spike --property <id> --percent 50\\`, \\`goal_silent --property <id>\n --goal <key> --hours 24\\`, \\`event_count --property <id> [--event <name>] --count 500 [--repeat]\\`. \\`alerts enable|disable|delete|test <id>\\`\n (\\`test\\` = what would fire now, nothing sent). Channels (email, Slack, Discord, webhook) are set in the dashboard.\n- **Short links**: \\`npx splithub links create https://example.com/spring [--slug spring] [--name \"Spring\"]\\`; several URLs with\n \\`--weights 70,30\\` split visitors between pages. \\`links\\` lists them with clicks, \\`links <slug>\\` shows one link's clicks,\n \\`links pause|resume|delete <slug>\\`.\n- **Allowed domains**: \\`npx splithub domains set experiment <key> example.com\\` (subdomains included), \\`domains clear experiment <key>\\`,\n \\`domains\\` lists them. No list = any origin.\n\n## Do not\n\n- Nest an \\`<Experiment>\\` inside a \\`<Variant>\\` of the same id; call hooks conditionally.\n- Change \\`seed\\`, weights or variants of a running experiment (reshuffles visitors). Create a new experiment instead.\n- Edit in the dashboard what the config file owns: file experiments are read-only there (pause/finish still work).\n- Run more than 2-3 experiments on one page of a low-traffic site.\n- Put secrets, API keys or database credentials in the config or in the browser. \\`pk_\\` is public, \\`sk_\\` is not.\n`;\n\nexport const SKILL_AB_TESTING = `---\nname: ab-testing\ndescription: How to design, run and read an experiment correctly: hypothesis, control, primary metric, sample size, significance, SRM, peeking, when to stop. Use before creating an experiment or when interpreting results, with any tool.\n---\n\n# A/B testing, the parts that matter\n\nAn experiment splits visitors at random into variants and compares one metric. It answers one question:\n\"does this change move this metric?\" Everything below exists to keep that answer honest.\n\n## Before creating an experiment\n\n1. **One hypothesis, one primary metric.** \"A shorter signup form raises signup completion.\" The metric is a goal\n (event, page visit or click) that happens after the exposure. Pick it before looking at data.\n2. **Control first.** The first variant is what exists today. Change one thing per variant; several unrelated changes\n in one variant cannot be attributed.\n3. **Traffic reality.** Rough rule: to detect a relative lift L on a baseline rate p you need about\n \\`16 · p(1-p) / (p·L)²\\` visitors per variant (95% confidence, 80% power).\n Examples: baseline 5%, lift 20% → ~7,600 per variant; baseline 2%, lift 10% → ~78,000 per variant.\n If the site cannot reach that in 2-4 weeks, try a bigger change or a higher-traffic page.\n4. **Few experiments per page.** Interactions between simultaneous experiments on the same page muddy both.\n\n## While it runs\n\n- **Do not peek and stop early.** Checking daily and stopping at the first \"significant\" moment inflates false\n positives several times. Decide the sample or the duration up front; run whole weeks (weekday/weekend cycles).\n- **SRM (sample ratio mismatch).** If the split is 50/50 and you see 60/40, the assignment or the tracking is broken\n (bots, caching, redirect loops, a variant that errors). Fix first; results from an SRM run are meaningless.\n- **Keep variants frozen.** Changing copy, weights or targeting mid-run reshuffles who saw what. Start a new experiment.\n- **Watch the guardrails.** A variant that wins the primary metric but breaks revenue, errors or latency is not a win.\n\n## Reading results\n\n- Significance (p < 0.05 after correction for several variants) says the difference is unlikely to be noise;\n the confidence interval says how big it plausibly is. A \"winner\" with a CI that touches 0 is a weak win.\n- \"No significant difference\" with a sample smaller than needed means **keep running**, not \"no effect\".\n With enough sample it means the change does not matter: ship whichever is cheaper or cleaner.\n- Relative lift is on the baseline rate: 5% → 6% is +20% relative, +1 point absolute. Report both.\n- Attribution: conversions count only after the visitor's first exposure, per unique visitor.\n- Segments (country, device) are for hypotheses, not verdicts: slicing after the fact finds noise.\n\n## When to stop\n\n- Winner found with the planned sample → ship it, finish the experiment, remove the losing code.\n- Planned sample reached, no difference → ship the simpler variant, finish.\n- SRM or broken tracking → stop, fix, restart as a new experiment.\n- The business moved on → finish; do not leave experiments running forever (they cost events and split traffic).\n\n## Vocabulary\n\nexposure = a visitor saw a variant · conversion = the goal happened after exposure · lift = relative change in rate ·\np-value = chance of seeing this difference by luck · CI = range the true difference likely lies in ·\nSRM = the split differs from the configured weights · guardrail = a metric that must not get worse.\n`;\n\nexport const SKILL_SPLITHUB_API = `---\nname: splithub-api\ndescription: Use the sh2 Cloud HTTP API directly: public key event ingest, API-key endpoints for config, status, results, overrides, analytics reports, notes, short links and alert rules. Use when writing a server, a script, a non-JS client, or when the CLI is not available.\n---\n\n# sh2 Cloud API\n\nBase URL: \\`https://go.sh2.uk\\`. JSON in, JSON out (no envelope under \\`/v1/*\\`). Two credentials:\n\n- **Public key \\`pk_…\\`**: identifies the project to browsers and SDKs. Safe to ship. Can only send events and read\n the public overrides JSON.\n- **API key \\`sk_…\\`**: project-scoped secret for servers, CI and the CLI (\\`npx splithub login\\` mints one through a\n browser approval; or Settings → API keys in the dashboard). Never in client code. It can be limited to some areas:\n see API keys and scopes below.\n\n## Send events (public key)\n\n\\`\\`\\`http\nPOST /v1/events\nAuthorization: Bearer pk_live_…\nContent-Type: application/json\n\n{ \"project\": \"my-app\", \"sdk\": \"custom/1.0\", \"events\": [\n { \"id\": \"e_01h…\", \"type\": \"exposure\", \"exp\": \"hero-cta\", \"var\": \"bold\", \"vid\": \"v_abc\", \"sid\": \"s_1\", \"ts\": 1760000000000, \"url\": \"/\" },\n { \"id\": \"g_01h…\", \"type\": \"goal\", \"goal\": \"signup\", \"vid\": \"v_abc\", \"sid\": \"s_1\", \"ts\": 1760000010000, \"props\": { \"revenue\": 49 } }\n] }\n\\`\\`\\`\n\n- Analytics properties take two more types: \\`{ \"type\": \"page\", \"prop\": \"site\", \"url\": \"/pricing\", \"title\"?, \"ref\"?, … }\\`\n (\\`ref\\` = document.referrer) and \\`{ \"type\": \"event\", \"prop\": \"site\", \"name\": \"Video Played\", \"props\"?: { … }, … }\\`.\n Both are billed like one exposure each; events of a property that is paused or unknown are dropped.\n An \\`event\\` row also converts the experiments whose goal is that event, and a \\`page\\` row the page-visit goals its path\n matches (not billed again): send one row per action, not a goal row next to it (one within 1 s is counted once).\n \\`{ \"type\": \"identify\", \"prop\": \"site\", \"uid\": \"user_42\", \"traits\"?: { \"plan\": \"pro\" }, … }\\` ties the visitor to your user\n (not billed). Requests from bots are dropped.\n- \\`id\\`: unique per event (8-64 chars, [a-z0-9_-]); duplicates are ignored. \\`vid\\`: stable visitor id (cookie \\`sh_vid\\`).\n- Reply \\`202 { ok, received, inserted, dropped }\\`. A project with nothing running or no config yet answers\n \\`202 { ok, inserted: 0, idle: 'no_running' | 'no_config' }\\`: nothing stored, not an error. \\`429\\` with \\`code\\` ∈\n quota_exceeded | deleted: back off for \\`Retry-After\\` seconds; nothing was stored. Allowed domains are set per experiment and per\n property: events from another origin are dropped, and \\`403 origin_not_allowed\\` comes back when nothing in the batch was allowed.\n- Exposures for experiments that are not running are dropped and not billed. Goals are never billed.\n\n## API keys and scopes\n\nA key can do everything (\\`*\\`, the default) or only some areas, each with read or write (write includes read).\nPick them in Settings → API keys when creating the key.\n\n| Area | Covers |\n|---|---|\n| \\`experiments\\` | status, results, report, config push, overrides, archive, reviews |\n| \\`analytics\\` | properties, their reports, segments, the event catalog |\n| \\`events\\` | read: raw events and \\`export.csv?raw=1\\`; write: send events from your server with this key |\n| \\`notes\\`, \\`links\\`, \\`alerts\\`, \\`domains\\` | those endpoints |\n\nScope strings: \\`<area>:read\\` / \\`<area>:write\\` (e.g. \\`notes:write\\`, \\`analytics:read\\`), \\`read\\` / \\`write\\` for every area,\n\\`*\\` for everything. Keys made before scopes existed have \\`*\\`.\n\nServer-side sending: a key with \\`events:write\\` can post to \\`POST /v1/events\\` instead of the public key. It is trusted,\nso there is no origin check; keep it on the server.\n\n\\`\\`\\`bash\ncurl -X POST https://go.sh2.uk/v1/events \\\\\n -H \"Authorization: Bearer $SPLITHUB_API_KEY\" -H \"Content-Type: application/json\" \\\\\n -d '{ \"sdk\": \"server/1.0\", \"events\": [\n { \"id\": \"g_order_1042\", \"type\": \"goal\", \"goal\": \"purchase\", \"vid\": \"v_abc\", \"ts\": 1760000010000, \"props\": { \"revenue\": 49 } },\n { \"id\": \"e_order_1042\", \"type\": \"event\", \"prop\": \"site\", \"name\": \"Order Paid\", \"vid\": \"v_abc\", \"ts\": 1760000010000 }\n ] }'\n\\`\\`\\`\n\n\\`vid\\` is the visitor's \\`sh_vid\\` cookie, so the goal lands on the variant they saw. A request the key may not make\nanswers \\`403 { code: 'insufficient_scope', scope: 'notes:write', error, hint }\\`: \\`scope\\` names the missing one, and the CLI\nshows it (\\`--json\\` adds \\`scope\\`). Ask the user for a key with that scope; don't retry with another key.\n\n## Live config for clients (public key)\n\n\\`GET /v1/overrides/<pk>.json\\` (apps add \\`?all=1\\`: \\`added\\` then also carries the pushed experiments) → \\`{ version, experiments: { <id>: { status?, traffic?, weights?, values? } }, added: [ …hosted experiments… ], goals: [...], ctx: { country, region, city } }\\`.\nPoll it at most once a minute; the SDK caches it in localStorage. \\`ctx\\` is the visitor's geo for targeting.\n\n## Project endpoints (API key)\n\n\\`\\`\\`http\nGET /v1/status every experiment: status, visitors, days, verdict headline\nGET /v1/results/<experiment> full verdict: sample, comparisons (lift, p-value, CI, P(beat)), srm, winner\n ?from=&to= (first-exposure days) &country=DE&channel=…: the verdict on that slice, with scope { filtered, range, filters, note }\nGET /v1/experiments/<experiment>/timeline ?from=&to=&<filters>: exposures[] and conversions[] per day and variant, notes\nGET /v1/experiments/<experiment>/breakdown/<by> by country|region|city|device|os|platform|app_version|browser|language|host|page (= url)|referrer|source|channel|landing|utm_*:\n order[], segments[] { dim, cells, comparisons { lift, pValue, significant, better }, total, small }\nGET /v1/experiments/<experiment>/engagement { property, variants[] { visitors, sessions, pagesPerVisit, bounceRate, avgVisit } } (&property=)\nGET /v1/experiments/<experiment>/events-summary { property, variants[], visitors, rows[] { name, goalKey, isGoal, measured, perVariant, comparisons, small } } (&property=)\nGET /v1/experiments/<experiment>/export.breakdown.csv?by= the breakdown as CSV, lift per segment\nGET /v1/experiments/<experiment>/export.events-summary.csv the events table as CSV, lift per event\nGET /v1/experiments/<experiment>/events ?type=exposure|goal&before=&limit=&<filters>: raw events, nextBefore (needs events:read)\nGET /v1/config the config stored in the cloud (file + dashboard experiments)\nPUT /v1/config { config, prune? } push a normalized config (what defineConfig returns); answers cloudOnly experiments to adopt and kept ones (from an earlier push, missing from this one; prune: true removes them)\nGET /v1/overrides live overrides\nPUT /v1/overrides/<experiment> { status | traffic | weights | values } pause / resume / reweight without a deploy\nDELETE /v1/overrides/<experiment>\nGET /v1/properties analytics properties: live status, goals, domains, last 30 days\nPOST /v1/properties { key, name?, goals?, domains? } create one (dashboard-owned)\nPATCH /v1/properties/<key> { status: running | paused, name?, goals? }\nGET /v1/properties/<key>/summary ?from=&to= (YYYY-MM-DD) &<dimension>=a,b[&compare=previous|year|custom&cfrom=&cto=]: totals, days, goals, notes\nGET /v1/properties/<key>/breakdown ?by=source|channel|page|event|goal|country|…&goal=[&compare=…]: rows\nGET /v1/properties/<key>/funnel ?steps=page:/,event:Signup,goal:paid&within=visit|7d|30d[&by=]: steps with visitors, conversion, dropoff\n ?funnel=<id> runs a saved funnel (its steps and within)\nGET|POST /v1/properties/<key>/funnels { name, steps[], within? } PATCH|DELETE /v1/properties/<key>/funnels/<id>\nGET /v1/properties/<key>/paths ?page=/pricing&direction=next|prev: rows { value, visits }\nGET /v1/properties/<key>/retention ?start=visit|event:<n>|goal:<k>&return=visit|event:<n>&period=day|week&from=&to=: { period, cohorts[] { start, users, retained[] } }\nGET /v1/properties/<key>/realtime | /events?type=page|event | /props?name=&key= | /export.csv?by=|day (&raw=1)\nGET|POST /v1/segments { name, filters, propertyKey? } PATCH|DELETE /v1/segments/<id>\nGET /v1/domains every allowed domain and where it applies, observed origins\nPUT /v1/domains/<experiment|property>/<key> { hosts: [...] } replace one list ([] = any origin)\nGET /v1/notes ?experiment=&property=&kind=&from=&to=[&exact=1] newest first; experiment / property also return project-wide notes unless exact=1\nPOST /v1/notes { text (≤ 2000), day? (default today, project time zone), kind?: note|issue|win, experimentKey? | propertyKey? (none = whole project) }\nPATCH|DELETE /v1/notes/<id> { text?, day?, kind? }\nGET /v1/links short links: shortUrl, destinations [{ id, url, weight }], status, totalClicks\nPOST /v1/links { name, destinations: [{ url, weight? }], shortCode?, description?, clickLimit? }\nPATCH|DELETE /v1/links/<id> { name?, shortCode?, status: active|paused, destinations?, description? } GET /v1/links/<id>/stats: byDay (30 days), byDestination, byCountry, byDevice, byReferrer\nGET /v1/alerts rules, channels, digest, history, conditions, plan\nPOST /v1/alerts/rules { condition, params, actions?: { notify, pause, finish, dropLoser }, name?, experiment?, enabled?, cooldownHours? }\nPATCH|DELETE /v1/alerts/rules/<id> POST /v1/alerts/rules/<id>/test (dry run: what would fire now)\n\\`\\`\\`\n\nAlert conditions and params: experiments \\`srm\\`, \\`winner\\` { minVisitors? }, \\`loser\\` { lift, minVisitors? }, \\`exposures\\` { visitors },\n\\`conversions\\` { conversions }, \\`duration\\` { days }, \\`no_events\\` { hours }; account \\`quota\\` { percent }, \\`usage\\` { every } (each time this\nmonth's billed events cross another multiple); analytics \\`traffic_drop\\` / \\`traffic_spike\\` { property, percent }, \\`goal_silent\\`\n{ property, goal, hours }, \\`event_count\\` { property, event? (any event when absent), count, repeat? }. \\`params.progress\\` { total, fired,\nmonth? } is read-only. Enabled rules need Pro: \\`402 pro_required\\` otherwise (save it with \\`enabled: false\\`).\n\n\\`Authorization: Bearer sk_live_…\\` on each. Status values: draft | running | paused | finished.\n\n## Dashboard-scope endpoints (session, same shapes the dashboard uses)\n\nUnder \\`/v1/projects/<projectId>/…\\` with a user session: \\`experiments\\` (hosted experiments CRUD incl. \\`flow\\` targeting),\n\\`goals\\`, \\`timeline\\`, \\`breakdown\\`, \\`realtime\\`, \\`events\\`, \\`export\\`, \\`notes\\`, \\`domains\\`, \\`properties\\`, \\`links\\`, \\`alerts\\`, \\`billing\\`, \\`ai\\`.\nScripts should prefer the API-key endpoints above; the session ones exist for the UI.\n\n## Drop-in script (no SDK)\n\n\\`<script src=\"https://go.sh2.uk/sh.js\" data-key=\"pk_live_…\"></script>\\` in \\`<head>\\`: redirect experiments, page-visit and\nclick goals from the cloud config, \\`window.splithub.track(name, props)\\` for every event (goals included), pageviews\nfor analytics properties (\\`data-property=\"site\"\\`). An app with the SDK does not need it: one install per property,\nor only the first of the two collects pageviews.\n\\`<meta name=\"splithub-experiment\" content=\"<id>\">\\` on a tested page for an instant decision.\n\n## Errors\n\n\\`400\\` validation (message in \\`error\\`), \\`401\\` bad key, \\`403\\` forbidden (\\`insufficient_scope\\` names the missing \\`scope\\`), \\`404\\` unknown experiment/project, \\`409\\` state\n(e.g. \\`config_not_pushed\\`, \\`file_owned\\`), \\`429\\` gate or rate limit. Bodies: \\`{ error, code?, hint? }\\`, auth errors included; \\`hint\\` is the next step.\n`;\n\nexport const SKILL_SPLITHUB_MCP = `---\nname: splithub-mcp\ndescription: Use or set up the sh2 MCP server (@splithub/mcp) so an agent can create experiments, read verdicts, start/pause/finish experiments and push config through tools instead of shelling out, plus analytics, notes, alerts and short links. Use when the user asks to connect sh2 to Claude Code, Cursor, Codex or another MCP client.\n---\n\n# sh2 MCP server\n\n\\`@splithub/mcp\\` is a stdio MCP server that wraps the \\`splithub\\` CLI for the current project folder.\nSame credentials and config file as the CLI; nothing extra to configure.\n\n## Register it\n\nClaude Code (project scope, committed in \\`.mcp.json\\`):\n\n\\`\\`\\`json\n{ \"mcpServers\": { \"splithub\": { \"command\": \"npx\", \"args\": [\"-y\", \"@splithub/mcp\"] } } }\n\\`\\`\\`\n\nor \\`claude mcp add splithub -- npx -y @splithub/mcp\\`. Cursor: the same object in \\`.cursor/mcp.json\\`.\nCodex / other clients: command \\`npx\\`, args \\`-y @splithub/mcp\\`. \\`npx splithub skills --mcp\\` writes both files.\nEnv: \\`SPLITHUB_PROJECT_DIR\\` (defaults to the MCP client's working directory), \\`SPLITHUB_API\\` (staging or self-hosted cloud), \\`SPLITHUB_API_KEY\\` (CI).\n\n## Tools\n\n| tool | does | notes |\n|---|---|---|\n| \\`splithub_status\\` | all experiments with verdict headline | start here |\n| \\`splithub_results\\` | full verdict for one experiment; from / to / filters for a slice, by / timeline / engagement / events for one view (cloud) | report \\`verdict.message\\` verbatim; \\`daysToVerdict\\` = when to check again; a slice's verdict is not the experiment's |\n| \\`splithub_experiment_events\\` | the latest raw exposures and goals of an experiment (cloud) | check the wiring |\n| \\`splithub_review\\` | stored AI reviews (Pro): at start, on verdict changes, on finish, on demand | quote them as the analyst's opinion, the verdict stays the source of truth |\n| \\`splithub_plan\\` | visitors per variant for a baseline and a lift; days at an experiment's traffic | before creating |\n| \\`splithub_experiment_create\\` | adds an experiment to splithub.config.ts | kind value / component / redirect / mvt, id, variants (or factors for mvt), goal, values/to, weights, traffic, maxVisitors, start/end; running by default |\n| \\`splithub_refs\\` | files and lines that use an experiment and its goal | check the wiring, find leftovers |\n| \\`splithub_ship\\` | finish, remove from the config, rewrite the code to the kept variant | \\`dryRun: true\\` first; returns \\`diff\\` and \\`leftovers\\` |\n| \\`splithub_remove\\` | removes an experiment from the config (archived in the cloud) | when the code is already clean |\n| \\`splithub_projects\\` | every folder on this machine connected to a cloud project | |\n| \\`splithub_init\\` | sets up the config, framework files and skills | once per project |\n| \\`splithub_experiment_status\\` | start / pause / finish | applies live in cloud mode; after \\`finished\\`, ask which variant to keep and whether to clean the code (splithub-ship skill) |\n| \\`splithub_push\\` / \\`splithub_pull\\` | sync the config with the cloud | pull adopts dashboard-created experiments |\n| \\`splithub_doctor\\` | checks the installation | run after wiring code |\n| \\`splithub_login\\` | returns a sign-in link; the human approves it in the browser | show the link, then call \\`splithub_whoami\\` |\n| \\`splithub_whoami\\` | connected project and keys | |\n| \\`splithub_analytics\\` | analytics properties; one property's totals, goals, top pages and sources; \\`by\\` a dimension | counts, never verdicts |\n| \\`splithub_analytics_events\\` | the latest raw pageviews and events of a property | check tracking after wiring it |\n| \\`splithub_analytics_funnel\\` / \\`_funnels\\` / \\`_paths\\` / \\`_retention\\` / \\`_realtime\\` | funnels (run, save, list), next pages, cohorts, visitors now (cloud) | counts, never verdicts |\n| \\`splithub_analytics_connect\\` | picks or creates a property and names it on the app's provider | \\`wired.status\\` none / many: add the snippet yourself |\n| \\`splithub_segments\\` | saved report filters (cloud) | |\n| \\`splithub_notes\\` | what happened on a day, per experiment, property or project: list / add / edit / delete (cloud) | add one when you ship |\n| \\`splithub_alerts\\` | alert rules: list / add / enable / disable / delete / test (cloud, fire on Pro) | conditions in the splithub skill |\n| \\`splithub_links\\` | short links: list / stats / create / edit / pause / resume / delete (cloud) | several URLs split by weight |\n| \\`splithub_property_create\\` | adds an analytics property to splithub.config.ts and to the cloud | no push needed |\n| \\`splithub_property_status\\` | pause / resume, archive / restore (cloud) or remove a property | live in cloud mode |\n| \\`splithub_domains\\` | allowed domains per experiment and property; set or clear one list | empty = any origin |\n\nOld names still answer for one release: \\`splithub_create_experiment\\`, \\`splithub_set_status\\`, \\`splithub_create_property\\`,\n\\`splithub_set_property_status\\`. Use the names above.\n\n## Working rules\n\n- Create (running by default) → wire in code → \\`doctor\\` → \\`push\\` (cloud mode) → tell the user it goes live when they\n deploy this code and that \\`set_status paused\\` or Pause in the dashboard holds it.\n- Results: never call a winner from raw rates; quote the verdict. \\`srm_detected\\` = fix the setup first.\n- Running experiments are frozen: no weight / variant / seed edits; create a new one.\n- Errors carry a \\`code\\`. \\`NOT_LOGGED_IN\\`: call \\`splithub_login\\`, show the link to the user, wait for them, then retry.\n- The whole loop (plan → create → implement → doctor → push → results → finish → ship) is in the \\`splithub-loop\\` skill.\n- A \\`finished\\` experiment in \\`splithub_status\\` or \\`splithub_results\\` means the experiment is over but its code is still there: report\n the verdict, ask which variant to keep and whether to remove the experiment from the code, then follow the \\`splithub-ship\\` skill.\n`;\n\nexport { SKILL_SELF_HOSTED } from './skills-self-hosted';\nimport { SKILL_SELF_HOSTED } from './skills-self-hosted';\nexport { SKILL_LOOP, SKILL_SHIP } from './skills-ship';\nimport { SKILL_LOOP, SKILL_SHIP } from './skills-ship';\nexport { SKILL_ANALYTICS } from './skills-analytics';\nimport { SKILL_ANALYTICS } from './skills-analytics';\nexport { SKILL_APPS } from './skills-apps';\nimport { SKILL_APPS } from './skills-apps';\n\nexport const SKILLS: Skill[] = [\n { dir: 'splithub', body: SKILL_SPLITHUB },\n { dir: 'ab-testing', body: SKILL_AB_TESTING },\n { dir: 'splithub-api', body: SKILL_SPLITHUB_API },\n { dir: 'splithub-mcp', body: SKILL_SPLITHUB_MCP },\n { dir: 'splithub-self-hosted', body: SKILL_SELF_HOSTED },\n { dir: 'splithub-ship', body: SKILL_SHIP },\n { dir: 'splithub-loop', body: SKILL_LOOP },\n { dir: 'splithub-analytics', body: SKILL_ANALYTICS },\n { dir: 'splithub-apps', body: SKILL_APPS },\n];\n\nexport const MCP_SERVER_ENTRY = { command: 'npx', args: ['-y', '@splithub/mcp'] };\n","export function configTemplate(project: string, mode: 'self' | 'cloud', key?: string, options: { app?: boolean } = {}): string {\n // An app has no origin of its own: self-hosted events go to the server's full URL, and Expo inlines EXPO_PUBLIC_* variables.\n const endpoint = options.app ? \"process.env.EXPO_PUBLIC_SPLITHUB_ENDPOINT ?? 'https://example.com/api/splithub'\" : \"'/api/splithub'\";\n const envKey = options.app ? 'EXPO_PUBLIC_SPLITHUB_KEY' : 'NEXT_PUBLIC_SPLITHUB_KEY';\n const storage = mode === 'self' ? `{ mode: 'self', endpoint: ${endpoint} }` : `{ mode: 'cloud', key: ${key ? `'${key}'` : `process.env.${envKey} ?? ''`} }`;\n const appNote = options.app\n ? `\n// In an app this file is built into the binary: a new experiment here reaches users with the next\n// store release. Create experiments in the dashboard to start them without a release.`\n : '';\n return `import { defineConfig } from '@splithub/core';\n\n// sh2 experiments. This file is the source of truth: the SDK, the CLI\n// and the dashboard all read it. Keys: lowercase a-z 0-9 - _. First variant = control.${appNote}\nexport default defineConfig({\n project: '${project}',\n storage: ${storage},\n // Drafts behave like running experiments while you develop (next dev, vite); production ignores them.\n runDraftsInDev: true,\n\n goals: {\n // events you mark as goals: call track('signup') where it happens.\n // An experiment's goal may also be any other event name you track().\n signup: { type: 'event' },\n },\n\n experiments: {\n // run \\`npx splithub create\\` or add entries here:\n //\n // 'hero-title': {\n // kind: 'value',\n // status: 'running',\n // variants: {\n // control: { weight: 50, value: 'Ship faster' },\n // direct: { weight: 50, value: 'Know which version wins' },\n // },\n // goal: 'signup',\n // },\n },\n});\n`;\n}\n\nexport function nextMiddlewareTemplate(configImport: string): string {\n return `import { splithubMiddleware } from '@splithub/next';\nimport splithub from '${configImport}';\n\n// Sets the visitor cookie, forwards it to Server Components and serves\n// redirect experiments with an invisible rewrite.\nexport default splithubMiddleware(splithub);\n\nexport const config = {\n matcher: ['/((?!_next|api|.*\\\\\\\\..*).*)'],\n};\n`;\n}\n\nexport function nextRouteTemplate(configImport: string, store: { imports: string; factory: string } = { imports: \"import { sqliteStore } from '@splithub/adapter-sqlite';\", factory: \"sqliteStore({ file: process.env.SPLITHUB_DB ?? './splithub.db' })\" }): string {\n return `import { createSplitHubHandler } from '@splithub/node';\n${store.imports}\nimport config from '${configImport}';\n\n// Self-hosted ingest + results: events stay in your database. The CLI reads\n// status / results from this route; set SPLITHUB_ADMIN_TOKEN to protect it.\nconst handler = createSplitHubHandler({\n config,\n store: ${store.factory},\n adminToken: process.env.SPLITHUB_ADMIN_TOKEN,\n});\n\nexport const POST = handler;\nexport const GET = handler;\nexport const runtime = 'nodejs';\n`;\n}\n\nexport function componentVariantTemplate(name: string, experiment: string, variant: string): string {\n return `// Variant \"${variant}\" of experiment \"${experiment}\". Edit freely.\nexport function ${name}() {\n return (\n <section>\n <h2>${experiment} · ${variant}</h2>\n </section>\n );\n}\n`;\n}\n\nexport const AGENTS_SECTION = `\n## A/B testing (sh2)\n\nThis project uses sh2 (\\`@splithub/react\\`). Experiments are declared in\n\\`splithub.config.ts\\` and rendered with \\`<Experiment id>\\` / \\`useVariant(id)\\` /\n\\`useValue(id)\\`. Events: \\`useTrack()\\` then \\`track('<event name>')\\`; an experiment's goal is any event name.\n\n- Not connected yet? \\`npx splithub init --mode cloud\\` (or \\`npx splithub login\\`) prints a link: show it to the user, they sign in and approve, the CLI gets the keys. Never ask the user to paste keys.\n- New experiment: \\`npx splithub create --kind value|component|redirect|mvt --id <key> --variants control,<other> --goal <event name> --yes\\`\n then wire it in code (value → \\`useValue\\`, component → \\`<Experiment>\\` with one \\`<Variant>\\` per key, redirect → nothing,\n mvt → \\`--factor name=level:value,…\\` and \\`const { a, b } = useValue(id)\\`).\n- Results: \\`npx splithub results <id> --json\\`; report \\`verdict.message\\` verbatim, never call a winner from raw rates.\n- Lifecycle: \\`npx splithub start|pause|finish <id>\\`. Check setup: \\`npx splithub doctor\\`.\n- A \\`finished\\` experiment still has all its variants in the code: report the verdict, ask which variant to keep and whether to\n remove the experiment from the code, then follow .claude/skills/splithub-ship/SKILL.md. Never delete experiment code unasked.\n- \\`create\\` writes \\`status: 'running'\\`: the experiment goes live when the code is deployed. Always tell the user that, and that\n \\`npx splithub pause <id>\\` or Pause in the dashboard holds it. Never change \\`seed\\` of a running experiment.\n- Analytics: set it up with \\`npx splithub analytics connect --json\\` (names the property on the provider), read it with\n \\`npx splithub analytics <property> --json\\`; also \\`funnel\\`, \\`paths\\`, \\`retention\\`, \\`realtime\\`, \\`export\\` (sh2 Cloud).\n Details: .claude/skills/splithub-analytics/SKILL.md\n- Notes, alerts, links, domains (sh2 Cloud): \\`npx splithub notes add \"<what shipped>\"\\` when you ship, \\`npx splithub alerts\\` (rules, e.g.\n \\`alerts add usage --every 1000\\`), \\`npx splithub links\\` (short links), \\`npx splithub domains\\`. Humans: \\`npx splithub\\` opens the menu.\n- Apps (React Native / Expo / iOS / Android): new experiments start in the dashboard (the config is built into the binary);\n screens are page events. Details: .claude/skills/splithub-apps/SKILL.md\n- Config ships to the browser: no secrets in it. Full rules: .claude/skills/splithub/SKILL.md\n`;\n\nexport { SKILL_SPLITHUB as SKILL_MD } from './skills';\nimport { SKILL_SPLITHUB } from './skills';\n\nexport const CURSOR_RULE = `---\ndescription: sh2 A/B testing con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AAAA;AAAA;AAAA;AAQxB;AAEO,SAAS,yBAAyB,MAAc,YAAoB,SAAyB;AAClG,SAAO,eAAe,OAAO,oBAAoB,UAAU;AAAA,kBAC3C,IAAI;AAAA;AAAA;AAAA,YAGV,UAAU,SAAM,OAAO;AAAA;AAAA;AAAA;AAAA;AAKnC;AAEO,IAAM,iBAAiB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA8BvB,IAAM,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA,EAKzB,eAAe,QAAQ,qBAAqB,EAAE,CAAC;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/domains.ts"],"sourcesContent":["// splithub domains — which origins may send events, per test and per analytics property.\n//\n// splithub domains every allowed domain and where it applies\n// splithub domains set test <id> example.com [...] replace a test's list\n// splithub domains set property <id> example.com replace a property's list\n// splithub domains clear test|property <id> accept any origin again\n//\n// A test or property without domains accepts events from anywhere. sh2 Cloud only.\n\nimport { request, requireCloudToken } from '../api';\nimport { fail, printJson } from '../errors';\nimport { c, table } from '../ui';\nimport type { Flags } from './init';\n\ninterface DomainsData {\n entries: Array<{ kind: 'experiment' | 'property'; key: string; host: string }>;\n entities: Array<{ kind: 'experiment' | 'property'; key: string; name: string | null; status: string }>;\n observed: Array<{ host: string; events: number; lastSeen: number; allowedIn: Array<{ kind: string; key: string }> }>;\n}\n\nconst KINDS: Record<string, 'experiment' | 'property'> = { test: 'experiment', experiment: 'experiment', property: 'property' };\nconst label = (kind: string) => (kind === 'experiment' ? 'experiment' : 'property');\n\nexport async function domains(args: string[], flags: Flags): Promise<void> {\n const target = requireCloudToken(flags);\n const [action, kindArg, key, ...hosts] = args;\n if (!action) {\n const data = await request<DomainsData>(target, '/domains');\n if (flags.json) return printJson(data);\n const byHost = new Map<string, string[]>();\n for (const e of data.entries) byHost.set(e.host, [...(byHost.get(e.host) ?? []), `${label(e.kind)} ${e.key}`]);\n if (byHost.size === 0) console.log(c.dim('No experiment or property limits its origins: events are accepted from anywhere.'));\n else console.log(table(['DOMAIN', 'ALLOWED FOR'], [...byHost].map(([host, where]) => [c.bold(host), where.join(', ')])));\n const open = data.entities.filter((e) => !data.entries.some((x) => x.kind === e.kind && x.key === e.key));\n if (open.length && byHost.size) console.log(`\\n${c.dim(`Any origin: ${open.map((e) => `${label(e.kind)} ${e.key}`).join(', ')}`)}`);\n if (data.observed.length) {\n console.log(`\\n${c.bold('Seen sending events')}`);\n console.log(table(['ORIGIN', 'EVENTS', 'ALLOWED FOR'], data.observed.slice(0, 15).map((o) => [o.host, o.events.toLocaleString('en-US'), o.allowedIn.length ? o.allowedIn.map((a) => `${label(a.kind)} ${a.key}`).join(', ') : c.dim('–')])));\n }\n return;\n }\n if (action !== 'set' && action !== 'clear') fail('USAGE', `Unknown action \"${action}\". Use npx splithub domains set experiment <id> <domain...> or domains clear experiment <id>.`);\n const kind = KINDS[kindArg ?? ''];\n if (!kind || !key) fail('USAGE', `npx splithub domains ${action} experiment|property <id>${action === 'set' ? ' <domain...>' : ''}`);\n if (action === 'set' && hosts.length === 0) fail('USAGE', 'Which domains? npx splithub domains set experiment <id> example.com app.example.com (subdomains are included).');\n const out = await request<{ kind: string; key: string; hosts: string[] }>(target, `/domains/${kind}/${encodeURIComponent(key)}`, { method: 'PUT', body: JSON.stringify({ hosts: action === 'clear' ? [] : hosts }) });\n if (flags.json) return printJson(out);\n if (out.hosts.length === 0) console.log(`${c.green('✔')} ${label(kind)} ${c.bold(key)} accepts events from any origin`);\n else console.log(`${c.green('✔')} ${label(kind)} ${c.bold(key)} accepts events from ${out.hosts.join(', ')} ${c.dim('(and their subdomains; live within 60s)')}`);\n}\n"],"mappings":";;;;;;;;;;;;;AAoBA,IAAM,QAAmD,EAAE,MAAM,cAAc,YAAY,cAAc,UAAU,WAAW;AAC9H,IAA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\n// this project (.claude/skills/<name>/SKILL.md, .cursor/rules/splithub.mdc,\n// an AGENTS.md section) and, with --mcp, register the sh2 MCP server in\n// .mcp.json (Claude Code) and .cursor/mcp.json (Cursor). `init` calls this too.\n// The text comes from sh2 Cloud (GET /v1/skills) so it updates with a deploy;\n// the copies bundled here are the offline fallback.\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, join, relative } from 'node:path';\nimport { fetchSkills, type SkillFile } from '../api';\nimport { detectProject } from '../project';\nimport { AGENTS_SECTION, CURSOR_RULE } from '../templates';\nimport { MCP_SERVER_ENTRY, SKILLS } from '../skills';\nimport { c } from '../ui';\nimport type { Flags } from './init';\n\nexport interface SkillsResult {\n written: string[];\n skipped: string[];\n mcp: string[];\n /** Where the text came from: sh2 Cloud, or the copies bundled with the CLI. */\n source: 'cloud' | 'bundled';\n}\n\n/** The copies shipped with this CLI, in the shape GET /v1/skills serves. */\nexport const BUNDLED_SKILL_FILES: SkillFile[] = [\n ...SKILLS.map((s) => ({ path: `.claude/skills/${s.dir}/SKILL.md`, body: s.body })),\n { path: '.cursor/rules/splithub.mdc', body: CURSOR_RULE },\n { path: 'AGENTS.md', body: AGENTS_SECTION },\n];\n\n/** Only where skills belong: a server answer never writes anywhere else in the project. */\nconst SAFE_PATH = /^(\\.claude\\/skills\\/[a-z0-9][a-z0-9-]*\\/SKILL\\.md|\\.cursor\\/rules\\/[a-z0-9][a-z0-9-]*\\.mdc|AGENTS\\.md)$/;\n\n/** Fresh text from sh2 Cloud (1.5 s at most), else the bundled copies. */\nexport async function loadSkillFiles(flags: Record<string, unknown> = {}): Promise<{ files: SkillFile[]; source: 'cloud' | 'bundled' }> {\n const remote = (await fetchSkills(flags))?.filter((f) => SAFE_PATH.test(f.path));\n return remote?.length ? { files: remote, source: 'cloud' } : { files: BUNDLED_SKILL_FILES, source: 'bundled' };\n}\n\nfunction writeFile(file: string, content: string, force: boolean, out: SkillsResult): void {\n if (existsSync(file) && !force) {\n const current = readFileSync(file, 'utf8');\n if (current === content) {\n out.skipped.push(file);\n return;\n }\n // Skills we wrote earlier get refreshed; a user-edited file is left alone unless --force.\n if (!/SplitHub|splithub|\\bsh2\\b/.test(current)) {\n out.skipped.push(file);\n return;\n }\n }\n mkdirSync(dirname(file), { recursive: true });\n writeFileSync(file, content, 'utf8');\n out.written.push(file);\n}\n\n/** Merge our server into an MCP config file ({ mcpServers: {...} }) without touching other entries. */\nfunction registerMcp(file: string, out: SkillsResult): void {\n let json: { mcpServers?: Record<string, unknown> } = {};\n if (existsSync(file)) {\n try {\n json = JSON.parse(readFileSync(file, 'utf8')) as typeof json;\n } catch {\n out.skipped.push(`${file} (not valid JSON, left untouched)`);\n return;\n }\n }\n const servers = json.mcpServers ?? {};\n if (JSON.stringify(servers.splithub) === JSON.stringify(MCP_SERVER_ENTRY)) {\n out.skipped.push(file);\n return;\n }\n json.mcpServers = { ...servers, splithub: MCP_SERVER_ENTRY };\n mkdirSync(dirname(file), { recursive: true });\n writeFileSync(file, JSON.stringify(json, null, 2) + '\\n', 'utf8');\n out.mcp.push(file);\n}\n\nexport function installSkills(root: string, options: { mcp?: boolean; force?: boolean; files?: SkillFile[]; source?: 'cloud' | 'bundled' } = {}): SkillsResult {\n const out: SkillsResult = { written: [], skipped: [], mcp: [], source: options.source ?? (options.files ? 'cloud' : 'bundled') };\n const files = options.files ?? BUNDLED_SKILL_FILES;\n for (const f of files) if (f.path !== 'AGENTS.md') writeFile(join(root, ...f.path.split('/')), f.body, Boolean(options.force), out);\n\n const section = files.find((f) => f.path === 'AGENTS.md')?.body ?? AGENTS_SECTION;\n const agentsFile = ['AGENTS.md', 'CLAUDE.md'].map((f) => join(root, f)).find((f) => existsSync(f)) ?? join(root, 'AGENTS.md');\n if (!existsSync(agentsFile)) {\n writeFileSync(agentsFile, `# ${detectProject(root).name}\n${section}`, 'utf8');\n out.written.push(agentsFile);\n } else if (!/SplitHub|\\bsh2\\b/.test(readFileSync(agentsFile, 'utf8'))) {\n writeFileSync(agentsFile, readFileSync(agentsFile, 'utf8') + `\n${section}`, 'utf8');\n out.written.push(`${agentsFile} (section appended)`);\n } else {\n out.skipped.push(agentsFile);\n }\n\n if (options.mcp) {\n registerMcp(join(root, '.mcp.json'), out);\n registerMcp(join(root, '.cursor', 'mcp.json'), out);\n }\n return out;\n}\n\nexport async function skills(flags: Flags): Promise<void> {\n const project = detectProject();\n const result = installSkills(project.root, { mcp: Boolean(flags.mcp), force: Boolean(flags.force), ...(await loadSkillFiles(flags)) });\n if (flags.json) {\n console.log(JSON.stringify(result));\n return;\n }\n const rel = (f: string) => relative(project.root, f) || f;\n if (result.written.length) console.log(`${c.green('✔')} wrote\\n ${result.written.map(rel).join('\\n ')}`);\n if (result.mcp.length) console.log(`${c.green('✔')} MCP server registered in\\n ${result.mcp.map(rel).join('\\n ')}`);\n if (result.skipped.length) console.log(c.dim(`unchanged: ${result.skipped.map(rel).join(', ')}`));\n if (result.source === 'bundled') console.log(c.dim(\"couldn't reach sh2 Cloud, so these are the copies bundled with this CLI\"));\n if (!flags.mcp) console.log(c.dim(`add --mcp to register the sh2 MCP server (Claude Code .mcp.json, Cursor .cursor/mcp.json; Codex and Copilot read AGENTS.md)`));\n console.log(c.dim('skills: splithub (library + CLI), ab-testing (how to run experiments well), splithub-analytics (pageviews, events, reports), splithub-api (HTTP API), splithub-mcp (MCP tools), splithub-self-hosted (your own database), splithub-ship (keep the winner, remove the experiment), splithub-loop (the whole loop, tool by tool)'));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAMA,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,SAAS,MAAM,gBAAgB;AAiBjC,IAAM,sBAAmC;AAAA,EAC9C,GAAG,OAAO,IAAI,CAAC,OAAO,EAAE,MAAM,kBAAkB,EAAE,GAAG,aAAa,MAAM,EAAE,KAAK,EAAE;AAAA,EACjF,EAAE,MAAM,8BAA8B,MAAM,YAAY;AAAA,EACxD,EAAE,MAAM,aAAa,MAAM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M,UAAU,cAAc;AAC9B,QAAM,SAAS,cAAc,QAAQ,MAAM,EAAE,KAAK,QAAQ,MAAM,GAAG,GAAG,OAAO,QAAQ,MAAM,KAAK,GAAG,GAAI,MAAM,eAAe,KAAK,EAAG,CAAC;AACrI,MAAI,MAAM,MAAM;AACd,YAAQ,IAAI,KAAK,UAAU,MAAM,CAAC;AAClC;AAAA,EACF;AACA,QAAM,MAAM,CAAC,MAAc,SAAS,QAAQ,MAAM,CAAC,KAAK;AACxD,MAAI,OAAO,QAAQ,OAAQ,SAAQ,IAAI,GAAG,EAAE,MAAM,QAAG,CAAC;AAAA,IAAa,OAAO,QAAQ,IAAI,GAAG,EAAE,KAAK,MAAM,CAAC,EAAE;AACzG,MAAI,OAAO,IAAI,OAAQ,SAAQ,IAAI,GAAG,EAAE,MAAM,QAAG,CAAC;AAAA,IAAgC,OAAO,IAAI,IAAI,GAAG,EAAE,KAAK,MAAM,CAAC,EAAE;AACpH,MAAI,OAAO,QAAQ,OAAQ,SAAQ,IAAI,EAAE,IAAI,cAAc,OAAO,QAAQ,IAAI,GAAG,EAAE,KAAK,IAAI,CAAC,EAAE,CAAC;AAChG,MAAI,OAAO,WAAW,UAAW,SAAQ,IAAI,EAAE,IAAI,yEAAyE,CAAC;AAC7H,MAAI,CAAC,MAAM,IAAK,SAAQ,IAAI,EAAE,IAAI,6HAA6H,CAAC;AAChK,UAAQ,IAAI,EAAE,IAAI,gUAAgU,CAAC;AACrV;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/analytics-reports.ts"],"sourcesContent":["// Analytics reports past the summary and breakdowns, plus what people save around them.\n// sh2 Cloud only: a self-hosted endpoint answers raw counts (`splithub analytics <id>`).\n//\n// splithub analytics funnel <id> --steps \"page:/,event:Signup,goal:paid\" | --funnel <name|id> [--within visit|7d|30d] [--by <dimension>]\n// splithub analytics funnels <id> | --save <name> --steps \"...\" [--within 7d] | --delete <id|name>\n// splithub analytics paths <id> --page /pricing [--prev]\n// splithub analytics retention <id> [--start visit|event:<name>|goal:<key>] [--return visit|event:<name>] [--period day|week]\n// splithub analytics realtime <id>\n// splithub analytics props <id> --event <name> [--key <prop>]\n// splithub analytics export <id> [--by <dimension>|day] [--raw] > file.csv\n// splithub analytics segments [--property <id>] | --save <name> country=DE ... | --delete <id|name>\n//\n// Every report takes --days 7 | --from --to, --filter dimension=value and --segment <name|id>.\n\nimport { requestText, request, requireCloudToken, resolveTarget, type Target } from '../api';\nimport { fail, printJson } from '../errors';\nimport { detectProject } from '../project';\nimport { bar, c, table } from '../ui';\nimport type { Flags } from './init';\n\nexport const str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined);\n\nconst COMPARE_RANGE = /^(\\d{4}-\\d{2}-\\d{2})\\.\\.(\\d{4}-\\d{2}-\\d{2})$/;\n/** `--compare` (the period right before), `--compare year` (the same days a year earlier) or `--compare 2026-09-01..2026-09-30`. */\nexport function compareQuery(flags: Flags): Record<string, string> {\n const v = flags.compare;\n if (v === undefined || v === false) return {};\n if (v === true || v === '' || v === 'previous') return { compare: 'previous' };\n if (v === 'year') return { compare: 'year' };\n const m = typeof v === 'string' ? COMPARE_RANGE.exec(v) : null;\n if (!m || m[1]! > m[2]!) fail('INVALID_FLAG', `--compare ${String(v)}: use previous, year or a range like 2026-09-01..2026-09-30.`);\n return { compare: 'custom', cfrom: m[1]!, cto: m[2]! };\n}\nexport const n = (x: number) => x.toLocaleString('en-US');\nexport const rate = (part: number, whole: number) => (whole > 0 ? `${((part / whole) * 100).toFixed(1)}%` : '–');\nconst share = (x: number) => `${(x * 100).toFixed(1)}%`;\nconst enc = encodeURIComponent;\n\n/** Signed change against the period before: `+12%`, `-3%`, `new`, or `–` when both are zero. */\nexport function change(now: number, before: number | undefined): string {\n if (before === undefined) return c.dim('–');\n if (before === 0) return now > 0 ? c.green('new') : c.dim('–');\n const d = (now - before) / before;\n if (d === 0) return c.dim('0%');\n const text = `${d >= 0 ? '+' : ''}${(d * 100).toFixed(Math.abs(d) < 0.1 ? 1 : 0)}%`;\n return d > 0 ? c.green(text) : d < 0 ? c.red(text) : c.dim(text);\n}\n\n/** `--filter country=DE,FR` (repeatable) as `{ country: 'DE,FR' }`. */\nexport function filterFlags(flags: Flags): Record<string, string> {\n const out: Record<string, string> = {};\n for (const f of (Array.isArray(flags.filter) ? flags.filter : flags.filter ? [flags.filter] : []) as string[]) {\n const at = f.indexOf('=');\n const k = at > 0 ? f.slice(0, at).trim() : '';\n const v = at > 0 ? f.slice(at + 1).trim() : '';\n if (!k || !v) fail('INVALID_FLAG', `--filter ${f}: use dimension=value[,value], e.g. --filter country=DE`);\n out[k] = v;\n }\n return out;\n}\n\n/**\n * `?from=&to=` (or the last `--days`), a saved segment's filters, then `--filter` (which wins on the\n * same dimension), then the report's own parameters.\n */\nexport function reportQuery(flags: Flags, extra: Record<string, string> = {}, segment: Record<string, string> = {}): string {\n const q = new URLSearchParams();\n const from = str(flags.from);\n // --to is shared with redirect variants (`create --to b=/new`), so it may arrive as a list.\n const to = str(Array.isArray(flags.to) ? flags.to[0] : flags.to);\n if (from) q.set('from', from);\n if (to) q.set('to', to);\n const days = Number(flags.days);\n if (!from && Number.isFinite(days) && days > 0) {\n const d = (offset: number) => new Date(Date.now() - offset * 86_400_000).toISOString().slice(0, 10);\n q.set('from', d(Math.floor(days) - 1));\n if (!to) q.set('to', d(0));\n }\n for (const [k, v] of Object.entries({ ...segment, ...filterFlags(flags) })) q.set(k, v);\n for (const [k, v] of Object.entries(extra)) q.set(k, v);\n const s = q.toString();\n return s ? `?${s}` : '';\n}\n\ninterface Segment {\n id: string;\n name: string;\n propertyKey: string | null;\n filters: Record<string, string[]>;\n createdAt: string;\n}\n\nasync function listSegments(t: Target, property?: string): Promise<Segment[]> {\n return (await request<{ segments: Segment[] }>(t, `/segments${property ? `?property=${enc(property)}` : ''}`)).segments;\n}\n\nfunction findSegment(list: Segment[], want: string): Segment {\n const s = list.find((x) => x.id === want) ?? list.find((x) => x.name.toLowerCase() === want.toLowerCase());\n if (!s) fail('INVALID_FLAG', `There's no segment \"${want}\".`, 'See the saved ones with npx splithub analytics segments.');\n return s;\n}\n\n/** `--segment <name|id>`: the saved filters, as query values. */\nexport async function segmentFilters(t: Target, flags: Flags, property: string): Promise<Record<string, string>> {\n const want = str(flags.segment);\n if (!want) return {};\n const s = findSegment(await listSegments(t, property), want);\n return Object.fromEntries(Object.entries(s.filters).map(([k, v]) => [k, v.join(',')]));\n}\n\n/**\n * The cloud target for a cloud-only report. A self-hosted project gets NOT_CLOUD: its endpoint\n * keeps raw counts only. Outside a project, a saved login or SPLITHUB_API_KEY is enough.\n */\nexport function cloudOnly(flags: Flags, what: string, report = true, rawHint = 'Read the raw counts with npx splithub analytics <id>.'): Target {\n const project = detectProject();\n const t = resolveTarget(flags, project);\n if (t.cloud) return t;\n const explicit = (typeof flags.url === 'string' && flags.url) || process.env.SPLITHUB_URL;\n if (!project.configFile && !explicit) return requireCloudToken(flags);\n if (!report) return fail('NOT_CLOUD', `${what} come with sh2 Cloud.`, 'Connect this app with npx splithub init --mode cloud (or npx splithub login).');\n return fail('NOT_CLOUD', `${what} come with sh2 Cloud: a self-hosted endpoint keeps raw counts only.`, rawHint);\n}\n\nconst head = (key: string, parts: string[]) => console.log(`${c.bold(key)} ${c.dim(`· ${parts.join(' · ')}`)}\\n`);\nconst span = (r: { from: string; to: string }) => `${r.from} → ${r.to}`;\n\n// ---------------------------------------------------------------------------\n// Funnel\n// ---------------------------------------------------------------------------\n\ninterface FunnelData {\n range: { from: string; to: string };\n within: string;\n steps: Array<{ step: string; label: string; visitors: number; conversion: number; dropoff: number }>;\n byDimension?: string;\n by?: Array<{ value: string; steps: number[] }>;\n rolledUp?: boolean;\n}\n\nconst WITHIN: Record<string, string> = { visit: 'in one visit', '7d': 'within 7 days', '30d': 'within 30 days' };\n\nexport async function funnel(key: string, flags: Flags): Promise<void> {\n const steps = str(flags.steps);\n const want = str(flags.funnel);\n if (!want && (!steps || steps.split(',').filter((s) => s.trim()).length < 2)) fail('USAGE', 'Which steps? npx splithub analytics funnel <id> --steps \"page:/,event:Signup,goal:paid\" (2 or more), or a saved one: --funnel <name>.');\n const t = cloudOnly(flags, 'Funnels');\n // A saved funnel brings its steps and time limit; --steps and --within still win.\n const saved = want && !steps ? findFunnel(await listFunnels(t, key), want, key) : null;\n const within = str(flags.within) ?? (saved ? undefined : 'visit');\n const by = str(flags.by);\n const extra: Record<string, string> = { ...(saved ? { funnel: saved.id } : { steps: steps! }), ...(within ? { within } : {}), ...(by ? { by } : {}) };\n const data = await request<FunnelData>(t, `/properties/${enc(key)}/funnel${reportQuery(flags, extra, await segmentFilters(t, flags, key))}`);\n if (flags.json) return printJson(data);\n head(key, [...(saved ? [saved.name] : []), `funnel ${WITHIN[data.within] ?? data.within}`, span(data.range)]);\n const first = data.steps[0]?.visitors ?? 0;\n console.log(\n table(\n ['STEP', 'VISITORS', '', 'CONVERSION', 'DROP-OFF'],\n data.steps.map((s, i) => [`${i + 1}. ${s.label === s.step.slice(s.step.indexOf(':') + 1) ? s.step : `${s.label} ${c.dim(`(${s.step})`)}`}`, n(s.visitors), bar(s.visitors, Math.max(1, first), 16), share(s.conversion), i === 0 ? c.dim('–') : share(s.dropoff)])\n )\n );\n if (data.by?.length) {\n console.log(`\\n${c.bold(`By ${data.byDimension ?? by}`)}`);\n const rows = data.by.slice(0, Number(flags.limit) || 15);\n console.log(table([(data.byDimension ?? 'value').toUpperCase(), ...data.steps.map((_, i) => `STEP ${i + 1}`), 'CONVERSION'], rows.map((r) => [r.value, ...r.steps.map(n), rate(r.steps[r.steps.length - 1] ?? 0, r.steps[0] ?? 0)])));\n }\n if (data.rolledUp) console.log(c.dim('\\nDays older than 90 days keep no step order, so they count nothing here.'));\n if (first === 0) console.log(c.dim('Nobody reached the first step in this range.'));\n}\n\n// ---------------------------------------------------------------------------\n// Saved funnels\n// ---------------------------------------------------------------------------\n\ninterface SavedFunnel {\n id: string;\n name: string;\n steps: string[];\n within: string;\n updatedAt: string;\n}\n\nasync function listFunnels(t: Target, key: string): Promise<SavedFunnel[]> {\n return (await request<{ funnels: SavedFunnel[] }>(t, `/properties/${enc(key)}/funnels`)).funnels;\n}\n\nfunction findFunnel(list: SavedFunnel[], want: string, key: string): SavedFunnel {\n const f = list.find((x) => x.id === want) ?? list.find((x) => x.name.toLowerCase() === want.toLowerCase());\n if (!f) fail('INVALID_FLAG', `There's no funnel \"${want}\" on ${key}.`, `See the saved ones with npx splithub analytics funnels ${key}.`);\n return f;\n}\n\n/** List, save (a new name creates one, a saved name updates it) or delete the funnels of one property. */\nexport async function funnels(key: string, flags: Flags): Promise<void> {\n const t = cloudOnly(flags, 'Saved funnels');\n const save = str(flags.save);\n const del = str(flags.delete);\n if (save) {\n const steps = (str(flags.steps) ?? '').split(',').map((s) => s.trim()).filter(Boolean);\n const within = str(flags.within);\n const existing = (await listFunnels(t, key)).find((x) => x.name.toLowerCase() === save.toLowerCase());\n if (!existing && steps.length < 2) fail('USAGE', `Which steps? npx splithub analytics funnels ${key} --save \"${save}\" --steps \"page:/,event:Signup,goal:paid\"`);\n const body = JSON.stringify({ name: save, ...(steps.length ? { steps } : {}), ...(within ? { within } : {}) });\n const out = existing\n ? await request<{ funnel: SavedFunnel }>(t, `/properties/${enc(key)}/funnels/${enc(existing.id)}`, { method: 'PATCH', body })\n : await request<{ funnel: SavedFunnel }>(t, `/properties/${enc(key)}/funnels`, { method: 'POST', body });\n if (flags.json) return printJson(out);\n console.log(`${c.green('✔')} funnel ${c.bold(out.funnel.name)} ${existing ? 'updated' : 'saved'} ${c.dim(`(${out.funnel.steps.join(' → ')}, ${WITHIN[out.funnel.within] ?? out.funnel.within})`)}`);\n console.log(c.dim(`Run it: npx splithub analytics funnel ${key} --funnel \"${out.funnel.name}\"`));\n return;\n }\n if (del) {\n const f = findFunnel(await listFunnels(t, key), del, key);\n await request(t, `/properties/${enc(key)}/funnels/${enc(f.id)}`, { method: 'DELETE' });\n if (flags.json) return printJson({ ok: true, id: f.id, name: f.name });\n console.log(`${c.green('✔')} funnel ${c.bold(f.name)} deleted`);\n return;\n }\n const list = await listFunnels(t, key);\n if (flags.json) return printJson({ property: key, funnels: list });\n if (list.length === 0) return void console.log(c.dim(`No saved funnels on ${key} yet. Save one: npx splithub analytics funnels ${key} --save Signup --steps \"page:/,goal:signup\"`));\n console.log(table(['NAME', 'STEPS', 'COMPLETED', 'ID'], list.map((f) => [c.bold(f.name), f.steps.join(' → '), WITHIN[f.within] ?? f.within, c.dim(f.id)])));\n}\n\n// ---------------------------------------------------------------------------\n// Paths\n// ---------------------------------------------------------------------------\n\nexport async function paths(key: string, flags: Flags): Promise<void> {\n const page = str(flags.page);\n if (!page) fail('USAGE', 'Which page? npx splithub analytics paths <id> --page /pricing (add --prev for where visitors came from).');\n const t = cloudOnly(flags, 'Paths');\n const direction = flags.prev ? 'prev' : 'next';\n const data = await request<{ range: { from: string; to: string }; rows: Array<{ value: string; visits: number }> }>(t, `/properties/${enc(key)}/paths${reportQuery(flags, { page, direction }, await segmentFilters(t, flags, key))}`);\n if (flags.json) return printJson(data);\n head(key, [direction === 'next' ? `after ${page}` : `before ${page}`, span(data.range)]);\n if (data.rows.length === 0) return void console.log(c.dim(`No visits to ${page} in this range.`));\n const total = data.rows.reduce((s, r) => s + r.visits, 0);\n const label = (v: string) => (v === '(exit)' ? c.dim('left the site') : v === '(entrance)' ? c.dim('landed here') : v);\n console.log(table([direction === 'next' ? 'NEXT PAGE' : 'PREVIOUS PAGE', 'VISITS', 'SHARE'], data.rows.slice(0, Number(flags.limit) || 20).map((r) => [label(r.value), n(r.visits), rate(r.visits, total)])));\n}\n\n// ---------------------------------------------------------------------------\n// Retention\n// ---------------------------------------------------------------------------\n\ninterface RetentionData {\n range: { from: string; to: string };\n /** The range was cut to the last 90 days (day) or 26 weeks (week). */\n clamped?: boolean;\n start: string;\n return: string;\n period: 'day' | 'week';\n /** retained[n]: users of the cohort active in period n (0 = the cohort period). cohort / size / returned are the older names. */\n cohorts: Array<{ start?: string; users?: number; retained?: number[]; cohort?: string; size?: number; returned?: number[] }>;\n}\n\n/** Rows of the cohort table: start, users, then the share retained in each period. */\nexport function retentionRows(data: Pick<RetentionData, 'cohorts'>): { periods: number; rows: string[][] } {\n const cohorts = data.cohorts.map((r) => ({ start: r.start ?? r.cohort ?? '', users: r.users ?? r.size ?? 0, retained: r.retained ?? r.returned ?? [] }));\n const periods = Math.max(0, ...cohorts.map((r) => r.retained.length));\n return { periods, rows: cohorts.map((r) => [r.start, n(r.users), ...Array.from({ length: periods }, (_, i) => (i < r.retained.length ? rate(r.retained[i] ?? 0, r.users) : ''))]) };\n}\n\nexport async function retention(key: string, flags: Flags): Promise<void> {\n const t = cloudOnly(flags, 'Retention reports');\n const period = str(flags.period) ?? 'week';\n if (period !== 'day' && period !== 'week') fail('INVALID_FLAG', `--period ${period}: use day or week.`);\n const extra: Record<string, string> = { start: str(flags.start) ?? 'visit', return: str(flags.return) ?? 'visit', period };\n const data = await request<RetentionData>(t, `/properties/${enc(key)}/retention${reportQuery(flags, extra, await segmentFilters(t, flags, key))}`);\n if (flags.json) return printJson(data);\n head(key, [`retention by ${data.period}`, `start ${data.start}, back with ${data.return}`, span(data.range)]);\n if (data.clamped) console.log(c.dim(`Cut to the last ${data.period === 'day' ? '90 days' : '26 weeks'}.`));\n if (data.cohorts.length === 0) return void console.log(c.dim('No cohorts in this range.'));\n const { periods, rows } = retentionRows(data);\n const unit = data.period === 'day' ? 'DAY' : 'WEEK';\n console.log(table(['COHORT', 'USERS', ...Array.from({ length: periods }, (_, i) => `${unit} ${i}`)], rows));\n}\n\n// ---------------------------------------------------------------------------\n// Realtime\n// ---------------------------------------------------------------------------\n\ninterface RealtimeData {\n activeVisitors5m: number;\n pageviews: Array<{ minute: number; n: number }>;\n events: Array<{ minute: number; n: number }>;\n pages: Array<{ value: string; n: number }>;\n sources: Array<{ value: string; n: number }>;\n}\n\nexport async function realtime(key: string, flags: Flags): Promise<void> {\n const t = cloudOnly(flags, 'Realtime reports');\n const data = await request<RealtimeData>(t, `/properties/${enc(key)}/realtime`);\n if (flags.json) return printJson(data);\n const sum = (rows: Array<{ n: number }>) => rows.reduce((s, r) => s + r.n, 0);\n console.log(`${c.bold(key)} ${c.dim('· right now')}\\n`);\n console.log(`${c.bold(n(data.activeVisitors5m))} ${data.activeVisitors5m === 1 ? 'visitor' : 'visitors'} in the last 5 minutes ${c.dim(`· ${n(sum(data.pageviews))} pageviews and ${n(sum(data.events))} events in the last 30`)}`);\n if (data.pages.length) {\n console.log(`\\n${c.bold('Pages')}`);\n console.log(table(['PAGE', 'PAGEVIEWS'], data.pages.slice(0, 10).map((r) => [r.value, n(r.n)])));\n }\n if (data.sources.length) {\n console.log(`\\n${c.bold('Sources')}`);\n console.log(table(['SOURCE', 'VISITS'], data.sources.slice(0, 10).map((r) => [r.value === '(none)' ? c.dim('direct') : r.value, n(r.n)])));\n }\n}\n\n// ---------------------------------------------------------------------------\n// Event props\n// ---------------------------------------------------------------------------\n\ninterface PropRow {\n value: string;\n visitors: number;\n sessions: number;\n events: number;\n}\n\nexport async function props(key: string, flags: Flags): Promise<void> {\n const event = str(flags.event);\n if (!event) fail('USAGE', 'Which event? npx splithub analytics props <id> --event Signup [--key plan]');\n const t = cloudOnly(flags, 'Event props');\n const prop = str(flags.key);\n const data = await request<{ range: { from: string; to: string }; rows: PropRow[]; previous?: PropRow[] }>(\n t,\n `/properties/${enc(key)}/breakdown${reportQuery(flags, { by: 'prop', name: event, ...(prop ? { key: prop } : {}), ...compareQuery(flags) }, await segmentFilters(t, flags, key))}`\n );\n if (flags.json) return printJson(data);\n head(key, [prop ? `${event} by ${prop}` : `props of ${event}`, span(data.range)]);\n if (data.rows.length === 0) return void console.log(c.dim(`No ${event} events with props in this range.`));\n const before = new Map((data.previous ?? []).map((r) => [r.value, r.events]));\n const rows = data.rows.slice(0, Number(flags.limit) || 20);\n console.log(table([prop ? prop.toUpperCase() : 'PROP', 'EVENTS', 'VISITORS', 'VISITS', ...(data.previous ? ['CHANGE'] : [])], rows.map((r) => [r.value, n(r.events), n(r.visitors), n(r.sessions), ...(data.previous ? [change(r.events, before.get(r.value) ?? 0)] : [])])));\n if (!prop) console.log(c.dim(`\\nValues of one: --key ${rows[0]!.value}`));\n}\n\n// ---------------------------------------------------------------------------\n// CSV export\n// ---------------------------------------------------------------------------\n\nexport async function exportCsv(key: string, flags: Flags): Promise<void> {\n const t = cloudOnly(flags, 'Exports');\n const by = str(flags.by) ?? 'day';\n const goal = str(flags.goal);\n const extra: Record<string, string> = flags.raw ? { raw: '1' } : { by, ...(goal ? { goal } : {}) };\n const csv = await requestText(t, `/properties/${enc(key)}/export.csv${reportQuery(flags, extra, await segmentFilters(t, flags, key))}`);\n if (flags.json) return printJson({ property: key, ...(flags.raw ? { raw: true } : { by }), csv });\n process.stdout.write(csv.replace(/\\r\\n/g, '\\n'));\n}\n\n// ---------------------------------------------------------------------------\n// Segments\n// ---------------------------------------------------------------------------\n\n/** `country=DE,FR` positionals (and --filter) as saved filters. */\nfunction segmentBody(args: string[], flags: Flags): Record<string, string[]> {\n const out: Record<string, string[]> = {};\n const add = (k: string, v: string) => (out[k] = v.split(',').map((x) => x.trim()).filter(Boolean));\n for (const a of args) {\n const at = a.indexOf('=');\n if (at <= 0 || at === a.length - 1) fail('INVALID_FLAG', `\"${a}\": use dimension=value[,value], e.g. country=DE,FR`);\n add(a.slice(0, at).trim(), a.slice(at + 1).trim());\n }\n for (const [k, v] of Object.entries(filterFlags(flags))) add(k, v);\n return out;\n}\n\nconst describeFilters = (f: Record<string, string[]>) =>\n Object.entries(f)\n .map(([k, v]) => `${k}=${v.join(',')}`)\n .join(' ');\n\nexport async function segments(args: string[], flags: Flags): Promise<void> {\n const t = cloudOnly(flags, 'Saved segments');\n const property = str(flags.property);\n const save = str(flags.save);\n const del = str(flags.delete);\n if (save) {\n const filters = segmentBody(args, flags);\n if (Object.keys(filters).length === 0) fail('USAGE', `Which visits? npx splithub analytics segments --save \"${save}\" country=DE source=google`);\n const out = await request<{ segment: Segment }>(t, '/segments', { method: 'POST', body: JSON.stringify({ name: save, filters, ...(property ? { propertyKey: property } : {}) }) });\n if (flags.json) return printJson(out);\n console.log(`${c.green('✔')} segment ${c.bold(out.segment.name)} saved ${c.dim(`(${describeFilters(out.segment.filters)})`)}`);\n console.log(c.dim(`Use it on any report: --segment \"${out.segment.name}\"`));\n return;\n }\n if (del) {\n const s = findSegment(await listSegments(t), del);\n await request(t, `/segments/${enc(s.id)}`, { method: 'DELETE' });\n if (flags.json) return printJson({ ok: true, id: s.id, name: s.name });\n console.log(`${c.green('✔')} segment ${c.bold(s.name)} deleted`);\n return;\n }\n const list = await listSegments(t, property);\n if (flags.json) return printJson({ segments: list });\n if (list.length === 0) return void console.log(c.dim('No saved segments yet. Save one: npx splithub analytics segments --save \"Paid traffic\" channel=\"Paid Search\"'));\n console.log(table(['NAME', 'FILTERS', 'PROPERTY', 'ID'], list.map((s) => [c.bold(s.name), describeFilters(s.filters), s.propertyKey ?? c.dim('all'), c.dim(s.id)])));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAoBO,IAAM,MAAM,CAAC,MAAoC,OAAO,MAAM,YAAY,IAAI,IAAI;AAEzF,IAAM,gBAAgB;AAEf,SAAS,aAAa,OAAsC;AACjE,QAAM,IAAI,MAAM;AAChB,MAAI,MAAM,UAAa,MAAM,MAAO,QAAO,CAAC;AAC5C,MAAI,MAAM,QAAQ,MAAM,MAAM,MAAM,WAAY,QAAO,EAAE,SAAS,WAAW;AAC7E,MAAI,MAAM,OAAQ,QAAO,EAAE,SAAS,OAAO;AAC3C,QAAM,IAAI,OAAO,MAAM,WAAW,cAAc,KAAK,CAAC,IAAI;AAC1D,MAAI,CAAC,KAAK,EAAE,CAAC,IAAK,EAAE,CAAC,EAAI,MAAK,gBAAgB,aAAa,OAAO,CAAC,CAAC,8DAA8D;AAClI,SAAO,EAAE,SAAS,UAAU,OAAO,EAAE,CAAC,GAAI,KAAK,EAAE,CAAC,EAAG;AACvD;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AAI,KAAK,WAAW,EAAG,QAAO,KAAK,QAAQ,IAAI,EAAE,IAAI,8GAA8G,CAAC;AACpK,UAAQ,IAAI,MAAM,CAAC,QAAQ,WAAW,YAAY,IAAI,GAAG,KAAK,IAAI,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,IAAI,GAAG,gBAAgB,EAAE,OAAO,GAAG,EAAE,eAAe,EAAE,IAAI,KAAK,GAAG,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC;AACrK;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/credentials.ts","../src/api.ts"],"sourcesContent":["// Credentials saved by `splithub login`: ~/.config/splithub/credentials.json\n// { \"<api base>\": { \"<project root>\": { apiKey, projectId, projectName, savedAt } } }\n// `cloudTarget` falls back to the entry for the current directory when neither\n// --token nor SPLITHUB_API_KEY is set.\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\n\nexport interface SavedCredential {\n apiKey: string;\n projectId: string | null;\n projectName: string | null;\n /** Public key of the project (pk_...), written into splithub.config.ts by init. */\n publicKey?: string | null;\n savedAt: string;\n}\n\ntype Store = Record<string, Record<string, SavedCredential>>;\n\nexport function credentialsFile(): string {\n const base = process.env.XDG_CONFIG_HOME || (process.platform === 'win32' ? process.env.APPDATA || join(homedir(), 'AppData', 'Roaming') : join(homedir(), '.config'));\n return join(base, 'splithub', 'credentials.json');\n}\n\nfunction read(): Store {\n const file = credentialsFile();\n if (!existsSync(file)) return {};\n try {\n return JSON.parse(readFileSync(file, 'utf8')) as Store;\n } catch {\n return {};\n }\n}\n\nexport function loadCredential(api: string, root = process.cwd()): SavedCredential | null {\n return read()[api]?.[resolve(root)] ?? null;\n}\n\nexport function saveCredential(api: string, root: string, cred: SavedCredential): string {\n const file = credentialsFile();\n const store = read();\n store[api] = { ...(store[api] ?? {}), [resolve(root)]: cred };\n mkdirSync(join(file, '..'), { recursive: true });\n writeFileSync(file, JSON.stringify(store, null, 2) + '\\n', { mode: 0o600 });\n return file;\n}\n\n/** Every saved credential on this machine: which directory is connected to which project. */\nexport function listCredentials(api?: string): Array<{ api: string; root: string; cred: SavedCredential }> {\n const store = read();\n const out: Array<{ api: string; root: string; cred: SavedCredential }> = [];\n for (const [a, dirs] of Object.entries(store)) {\n if (api && a !== api) continue;\n for (const [root, cred] of Object.entries(dirs)) out.push({ api: a, root, cred });\n }\n return out.sort((x, y) => y.cred.savedAt.localeCompare(x.cred.savedAt));\n}\n\nexport function removeCredential(api: string, root = process.cwd()): boolean {\n const store = read();\n const key = resolve(root);\n if (!store[api]?.[key]) return false;\n delete store[api][key];\n writeFileSync(credentialsFile(), JSON.stringify(store, null, 2) + '\\n', { mode: 0o600 });\n return true;\n}\n","import type { RawResults, RawStatusRow } from '@splithub/node';\nimport { readFileSync } from 'node:fs';\nimport { loadCredential } from './credentials';\nimport { CliError, fail } from './errors';\nimport type { ProjectInfo } from './project';\n\nexport interface Target {\n url: string;\n token?: string;\n /** sh2 Cloud (verdicts computed there); false for a self-hosted endpoint or an explicit --url. */\n cloud?: boolean;\n}\n\nexport const CLOUD_API = 'https://go.sh2.uk/v1';\n\n/** Storage settings from splithub.config.ts, read textually to avoid loading the config. */\nfunction storageFromConfig(project?: ProjectInfo): { mode: 'self' | 'cloud'; endpoint: string } {\n const fallback = { mode: 'self' as const, endpoint: '/api/splithub' };\n if (!project?.configFile) return fallback;\n try {\n const src = readFileSync(project.configFile, 'utf8');\n const mode = /mode\\s*:\\s*['\"](cloud|self)['\"]/.exec(src)?.[1] as 'self' | 'cloud' | undefined;\n const endpoint = /endpoint\\s*:\\s*['\"]([^'\"]+)['\"]/.exec(src)?.[1];\n return { mode: mode ?? 'self', endpoint: endpoint ?? '/api/splithub' };\n } catch {\n return fallback;\n }\n}\n\n/** Cloud API base + project API key (sk_...). */\nexport function cloudTarget(flags: Record<string, unknown>): Target {\n const url = (typeof flags.api === 'string' && flags.api) || process.env.SPLITHUB_API || CLOUD_API;\n const base = url.replace(/\\/+$/, '');\n const token = (typeof flags.token === 'string' && flags.token) || process.env.SPLITHUB_API_KEY || loadCredential(base)?.apiKey || undefined;\n return { url: base, token, cloud: true };\n}\n\n/**\n * Where to read results from:\n * - --url / SPLITHUB_URL always win;\n * - cloud mode → the cloud API with the project API key;\n * - self mode → the local dev server (3000 for Next.js, 5173 for Vite) + the endpoint from the config.\n */\nexport function resolveTarget(flags: Record<string, unknown>, project?: ProjectInfo): Target {\n const explicit = (typeof flags.url === 'string' && flags.url) || process.env.SPLITHUB_URL;\n const storage = storageFromConfig(project);\n if (!explicit && storage.mode === 'cloud') return cloudTarget(flags);\n const port = project?.framework === 'next' ? 3000 : 5173;\n const url = explicit || `http://localhost:${port}${storage.endpoint}`;\n const token = (typeof flags.token === 'string' && flags.token) || process.env.SPLITHUB_ADMIN_TOKEN || undefined;\n return { url: url.replace(/\\/+$/, ''), token, cloud: false };\n}\n\n/**\n * Readable message from an API error body. /v1 answers `{ error: 'text', code, hint? }`; servers before\n * 0.4.0 sent auth errors as `{ success: false, error: { code, message } }`, still read here.\n */\nexport function apiErrorMessage(status: number, body: unknown, fallback: string): string {\n const error = (body as { error?: unknown } | null)?.error;\n const text = typeof error === 'string' ? error : typeof (error as { message?: unknown } | undefined)?.message === 'string' ? (error as { message: string }).message : fallback;\n return status === 401 ? `${text} This folder is not signed in: run npx splithub login (or set SPLITHUB_API_KEY).` : text;\n}\n\n/** CliError for a failed API response: 401 → NOT_LOGGED_IN, 404 on an experiment → EXPERIMENT_NOT_FOUND. The server's `hint` wins over ours. */\nexport function apiError(status: number, body: unknown, fallback: string, experiment?: string): CliError {\n const message = apiErrorMessage(status, body, fallback);\n const b = body as { code?: unknown; needed?: unknown; scope?: unknown; hint?: unknown } | null;\n const serverHint = typeof b?.hint === 'string' && b.hint ? b.hint : undefined;\n if (status === 401) return new CliError('NOT_LOGGED_IN', message, serverHint ?? 'Run npx splithub login (or set SPLITHUB_API_KEY), then retry.');\n if (status === 403 && b?.code === 'insufficient_scope') {\n // Older servers sent only `needed` (read | write); newer ones name the area too (`notes:write`).\n const scope = typeof b.scope === 'string' && b.scope ? b.scope : typeof b.needed === 'string' ? b.needed : 'write';\n return new CliError('INSUFFICIENT_SCOPE', message, serverHint ?? `This API key lacks the \"${scope}\" scope. Create one with it in the dashboard (Settings, API keys) or run npx splithub login --yes.`, scope);\n }\n if (status === 402 && b?.code === 'pro_required') return new CliError('PRO_REQUIRED', message, serverHint ?? 'Alert rules run on Pro: upgrade in the dashboard (Billing), then turn the rule on.');\n if (status === 404 && experiment) return new CliError('EXPERIMENT_NOT_FOUND', message, serverHint ?? 'Check the id with npx splithub status. In cloud mode, push the config first.');\n return new CliError('API_ERROR', message, serverHint);\n}\n\nexport async function request<T>(target: Target, path: string, init: RequestInit = {}, experiment?: string): Promise<T> {\n const headers: Record<string, string> = { ...((init.headers as Record<string, string> | undefined) ?? {}) };\n if (target.token) headers.authorization = `Bearer ${target.token}`;\n if (init.body) headers['content-type'] = 'application/json';\n let res: Response;\n try {\n res = await fetch(`${target.url}${path}`, { ...init, headers });\n } catch (error) {\n const hint = target.cloud ? 'Check your connection, or set --api / SPLITHUB_API.' : 'Is your app running? Set --url or SPLITHUB_URL.';\n throw new CliError('UNREACHABLE', `Can't reach ${target.url}: ${error instanceof Error ? error.message : String(error)}.`, hint);\n }\n const body: unknown = await res.json().catch(() => ({}));\n if (!res.ok) throw apiError(res.status, body, `${target.url}${path} responded ${res.status}`, experiment);\n return body as T;\n}\n\n/** A text answer (CSV exports); errors still arrive as JSON. */\nexport async function requestText(target: Target, path: string): Promise<string> {\n const headers: Record<string, string> = target.token ? { authorization: `Bearer ${target.token}` } : {};\n let res: Response;\n try {\n res = await fetch(`${target.url}${path}`, { headers });\n } catch (error) {\n throw new CliError('UNREACHABLE', `Can't reach ${target.url}: ${error instanceof Error ? error.message : String(error)}.`, 'Check your connection, or set --api / SPLITHUB_API.');\n }\n const text = await res.text();\n if (!res.ok) {\n let body: unknown = {};\n try {\n body = JSON.parse(text);\n } catch {\n // not JSON\n }\n throw apiError(res.status, body, `${target.url}${path} responded ${res.status}`);\n }\n return text;\n}\n\n/** Cloud target that must carry an API key. */\nexport function requireCloudToken(flags: Record<string, unknown>): Target & { token: string } {\n const target = cloudTarget(flags);\n if (!target.token) fail('NOT_LOGGED_IN', 'This folder is not connected to sh2 Cloud.', 'Run npx splithub login, or pass --token sk_... / SPLITHUB_API_KEY.');\n return target as Target & { token: string };\n}\n\n/** PUT /overrides/<experiment>: live status, traffic or weights without a deploy. */\nexport function putOverride(target: Target, experiment: string, body: Record<string, unknown>): Promise<unknown> {\n return request<unknown>(target, `/overrides/${encodeURIComponent(experiment)}`, { method: 'PUT', body: JSON.stringify(body) }, experiment);\n}\n\n/**\n * Apply a status live in cloud mode. Never throws: the config file already changed,\n * so a refused or unreachable cloud is reported, not fatal.\n */\nexport async function applyLiveStatus(flags: Record<string, unknown>, experiment: string, status: string): Promise<string> {\n const target = cloudTarget(flags);\n if (!target.token) return 'no API key (run npx splithub login or set SPLITHUB_API_KEY to apply it without a deploy)';\n try {\n await putOverride(target, experiment, { status });\n return 'applied';\n } catch (error) {\n return `cloud refused: ${error instanceof Error ? error.message : String(error)}`;\n }\n}\n\n/**\n * Archive an experiment in the cloud (PUT /archive/<id>): it stops, keeps its numbers and leaves the\n * active list. Older servers without the route get it finished instead. Never throws.\n */\nexport async function archiveLive(flags: Record<string, unknown>, experiment: string): Promise<string> {\n const target = cloudTarget(flags);\n if (!target.token) return 'no API key (run npx splithub login or set SPLITHUB_API_KEY to archive it in the cloud)';\n try {\n await request<unknown>(target, `/archive/${encodeURIComponent(experiment)}`, { method: 'PUT', body: '{}' });\n return 'archived';\n } catch (error) {\n // 404 from a server without the route (or any non-auth refusal): finishing still stops the test.\n if (error instanceof CliError && (error.code === 'EXPERIMENT_NOT_FOUND' || error.code === 'API_ERROR')) {\n const finished = await applyLiveStatus(flags, experiment, 'finished');\n return finished === 'applied' ? 'finished' : finished;\n }\n return `cloud refused: ${error instanceof Error ? error.message : String(error)}`;\n }\n}\n\n// Response shapes. Cloud answers carry the verdict and ready-to-print words; a self-hosted endpoint\n// (@splithub/node) answers raw counts with `analysis: { available: false }`. Only what the CLI reads is typed.\n\nexport interface Voice {\n scenario: string;\n line: string;\n advice: string;\n}\n\n/** Ready-to-print verdict label and lines, computed by the server. */\nexport interface Display {\n label: string;\n lines: string[];\n next?: string;\n}\n\nexport interface VariantCounts {\n variant: string;\n exposures: number;\n conversions: number;\n revenue?: number;\n}\n\nexport interface Interval {\n low: number;\n high: number;\n}\n\nexport interface Comparison {\n variant: string;\n relativeLift: number | null;\n probabilityToBeat: number;\n pValue: number;\n ci: Interval;\n sequential?: { pValue: number; ci: Interval };\n}\n\nexport interface MetricResult {\n metric: string;\n role: 'secondary' | 'guardrail';\n worse?: 'lower' | 'higher';\n variants: VariantCounts[];\n comparisons: Comparison[];\n}\n\nexport interface Verdict {\n status: string;\n message: string;\n winner: string | null;\n notes?: string[];\n comparisons: Comparison[];\n sample: { variants: VariantCounts[]; stars?: number; checks?: Array<{ met: boolean; label: string }> };\n metrics?: MetricResult[];\n guardrailBreached?: Array<{ metric: string; variant: string }>;\n}\n\nexport interface FactorResult {\n key: string;\n best: string | null;\n levels: Array<{ level: string; exposures: number; conversions: number; rate: number; relativeLift: number | null; pValue: number | null }>;\n}\n\n/** Cloud results. `display`, `voice` and `daysToVerdict` are optional: older servers omit them. */\nexport interface CloudResults {\n experiment: string;\n kind: string;\n status: string;\n goal: string | null;\n description: string | null;\n verdict: Verdict;\n daysToVerdict?: number | null;\n voice?: Voice | null;\n display?: Display;\n factors?: FactorResult[];\n /** Present when the results are a slice: first-exposure days and visitor filters. */\n scope?: { filtered: boolean; range: { from: string; to: string } | null; filters: Record<string, string | string[]>; note?: string };\n analysis?: undefined;\n}\n\nexport interface CloudStatusRow {\n experiment: string;\n kind: string;\n status: string;\n goal: string | null;\n visitors: number;\n days: number;\n verdict: string | null;\n headline: string | null;\n sample?: string | null;\n stars?: number | null;\n daysToVerdict?: number | null;\n voice?: Voice | null;\n display?: Display;\n}\n\nexport type { RawResults, RawStatusRow };\nexport type Analysis = RawResults['analysis'];\nexport type Results = CloudResults | RawResults;\nexport type StatusRow = CloudStatusRow | (RawStatusRow & { headline?: undefined; verdict?: undefined; sample?: undefined; stars?: undefined; daysToVerdict?: undefined; display?: undefined });\n/** One analytics property in `GET /v1/status` (sh2 Cloud): its last 7 days against the 7 before. */\nexport interface StatusProperty {\n property: string;\n name: string;\n status: string;\n visitors: number;\n previousVisitors: number;\n /** Relative change; null when the 7 days before had no visitors. */\n change: number | null;\n pageviews: number;\n conversions: Array<{ goal: string; conversions: number; change: number | null }>;\n}\n\nexport interface StatusData {\n project: string;\n experiments: StatusRow[];\n /** sh2 Cloud: analytics properties (archived left out); older servers and self-hosted omit it. */\n properties?: StatusProperty[];\n propertiesRange?: { from: string; to: string };\n /** Present (available: false) on self-hosted endpoints. */\n analysis?: Analysis;\n}\n\n/** Self-hosted answers: counts only, the verdict comes with sh2 Cloud. */\nexport const isRawResults = (r: Results): r is RawResults => (r as { analysis?: { available?: boolean } }).analysis?.available === false;\n\nexport const fetchStatus = (t: Target) => request<StatusData>(t, '/status');\nexport const fetchResults = (t: Target, key: string) => request<Results>(t, `/results/${encodeURIComponent(key)}`, {}, key);\nexport const fetchReport = (t: Target) => request<{ project: string; markdown: string }>(t, '/report');\n\nexport interface PlanResult {\n baseline: number;\n mde: number;\n variants: number;\n confidence: number;\n perVariant: number;\n total: number;\n}\n\n/** GET /plan on sh2 Cloud: public, no API key needed. */\nexport const fetchPlan = (t: Target, q: { baseline: number; mde: number; variants: number }) =>\n request<PlanResult>({ url: t.url, cloud: true }, `/plan?${new URLSearchParams({ baseline: String(q.baseline), mde: String(q.mde), variants: String(q.variants) }).toString()}`);\n\nexport interface SkillFile {\n /** Relative to the project root. `AGENTS.md` is a section to append, not a whole file. */\n path: string;\n body: string;\n}\n\n/** GET /skills on sh2 Cloud; null on any error or after `timeoutMs`, so the caller uses the bundled copies. */\nexport async function fetchSkills(flags: Record<string, unknown>, timeoutMs = 1500): Promise<SkillFile[] | null> {\n try {\n const res = await fetch(`${cloudTarget(flags).url}/skills`, { signal: AbortSignal.timeout(timeoutMs) });\n if (!res.ok) return null;\n const body = (await res.json()) as { files?: unknown };\n if (!Array.isArray(body.files)) return null;\n const files = body.files.filter((f): f is SkillFile => typeof (f as SkillFile | null)?.path === 'string' && typeof (f as SkillFile).body === 'string');\n return files.length ? files : null;\n } catch {\n return null;\n }\n}\n"],"mappings":";;;;;;;AAIA,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,eAAe;AACxB,SAAS,MAAM,eAAe;AAavB,SAAS,kBAA0B;AACxC,QAAM,OAAO,QAAQ,IAAI,oBAAoB,QAAQ,aAAa,UAAU,QAAQ,IAAI,WAAW,KAAK,QAAQ,GAAG,WAAW,SAAS,IAAI,KAAK,QAAQ,GAAG,SAAS;AACpK,SAAO,KAAK,MAAM,YAAY,kBAAkB;AAClD;AAEA,SAAS,OAAc;AACrB,QAAM,OAAO,gBAAgB;AAC7B,MAAI,CAAC,WAAW,IAAI,EAAG,QAAO,CAAC;AAC/B,MAAI;AACF,WAAO,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC;AAAA,EAC9C,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AACF;AAEO,SAAS,eAAe,KAAa,OAAO,QAAQ,IAAI,GAA2B;AACxF,SAAO,KAAK,EAAE,GAAG,IAAI,QAAQ,IAAI,CAAC,KAAK;AACzC;AAEO,SAAS,eAAe,KAAa,MAAc,MAA+B;AACvF,QAAM,OAAO,gBAAgB;AAC7B,QAAM,QAAQ,KAAK;AACnB,QAAM,GAAG,IAAI,EAAE,GAAI,MAAM,GAAG,KAAK,CAAC,GAAI,CAAC,QAAQ,IAAI,CAAC,GAAG,KAAK;AAC5D,YAAU,KAAK,MAAM,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;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AO,CAAC,MAAsB,OAAQ,GAAwB,SAAS,YAAY,OAAQ,EAAgB,SAAS,QAAQ;AACrJ,WAAO,MAAM,SAAS,QAAQ;AAAA,EAChC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":["readFileSync","readFileSync"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/alerts.ts"],"sourcesContent":["// splithub alerts — alert rules on sh2 Cloud (they run on Pro): a message on the project's\n// channels (email, Slack, Discord, webhook) when something happens, and for experiments optionally\n// pause / finish / drop the losing variant.\n//\n// splithub alerts rules (what, for what, progress, on/off) and recent alerts\n// splithub alerts add <condition> [flags] e.g. alerts add usage --every 1000, alerts add winner --experiment hero\n// splithub alerts enable|disable|delete|test <id> id, the start of it, or the rule's name\n//\n// Conditions and their flags:\n// experiments srm | winner [--min-visitors] | loser --lift 10 [--min-visitors] | exposures --visitors N\n// | conversions --conversions N | duration --days N | no_events [--hours 24] (--experiment <key>, else every running one)\n// account quota [--percent 80] | usage --every 1000\n// analytics traffic_drop|traffic_spike --property <id> [--percent 50] | goal_silent --property <id> --goal <key> [--hours 24]\n// | event_count --property <id> [--event <name>] --count N [--repeat]\n// any rule --name \"...\" --cooldown <hours> --disabled; experiment rules also --pause --finish --drop-loser\n\nimport { request, requireCloudToken, type Target } from '../api';\nimport { CliError, fail, printJson } from '../errors';\nimport { c, table } from '../ui';\nimport { cloudOnly, n, str } from './analytics-reports';\nimport type { Flags } from './init';\n\nexport const ALERT_CONDITIONS = ['srm', 'winner', 'loser', 'exposures', 'conversions', 'duration', 'no_events', 'quota', 'usage', 'traffic_drop', 'traffic_spike', 'goal_silent', 'event_count'] as const;\nexport type AlertCondition = (typeof ALERT_CONDITIONS)[number];\nconst ACCOUNT: readonly string[] = ['quota', 'usage'];\nconst PROPERTY: readonly string[] = ['traffic_drop', 'traffic_spike', 'goal_silent', 'event_count'];\n\nexport interface AlertParams {\n minVisitors?: number;\n lift?: number;\n visitors?: number;\n conversions?: number;\n days?: number;\n hours?: number;\n percent?: number;\n property?: string;\n goal?: string;\n every?: number;\n event?: string;\n count?: number;\n repeat?: boolean;\n progress?: { total: number; fired: number; month?: string };\n}\n\nexport interface AlertRule {\n id: string;\n experiment: string | null;\n name: string;\n condition: AlertCondition;\n params: AlertParams;\n actions: { channels: string[]; pause: boolean; finish: boolean; dropLoser: boolean };\n enabled: boolean;\n cooldownHours: number;\n lastFiredAt: string | null;\n}\n\ninterface AlertsData {\n plan: string;\n rules: AlertRule[];\n channels: Array<{ id: string; type: string; name: string }>;\n history: Array<{\n id: string;\n experiment: string | null;\n kind: string;\n message: string;\n createdAt: string;\n ruleId: string | null;\n }>;\n}\n\nconst enc = encodeURIComponent;\n\n/** `1000`, `1,000`, `10k`, `1.5m` → a number; NaN otherwise. */\nexport function parseCount(v: unknown): number {\n if (typeof v !== 'string' || !v.trim()) return Number.NaN;\n const m = /^(\\d+(?:\\.\\d+)?)\\s*([km]?)$/i.exec(v.trim().replace(/[,_\\s](?=\\d)/g, ''));\n if (!m) return Number.NaN;\n return Math.round(Number(m[1]) * (m[2]?.toLowerCase() === 'k' ? 1_000 : m[2]?.toLowerCase() === 'm' ? 1_000_000 : 1));\n}\n\n/** What the rule watches, in one plain line. */\nexport function describeRule(r: Pick<AlertRule, 'condition' | 'params'>): string {\n const p = r.params;\n switch (r.condition) {\n case 'srm':\n return 'The split breaks (SRM)';\n case 'winner':\n return 'A clear winner';\n case 'loser':\n return `A variant ${p.lift ?? 0}%+ worse than control`;\n case 'exposures':\n return `${n(p.visitors ?? 0)} visitors reached`;\n case 'conversions':\n return `${n(p.conversions ?? 0)} conversions reached`;\n case 'duration':\n return `Running for ${p.days ?? 0} days`;\n case 'no_events':\n return `No visitors for ${p.hours ?? 24}h`;\n case 'quota':\n return `${p.percent ?? 80}% of the monthly allowance used`;\n case 'usage':\n return `Every ${n(p.every ?? 0)} events used`;\n case 'traffic_drop':\n return `Visitors down ${p.percent ?? 50}%+ vs a week before`;\n case 'traffic_spike':\n return `Visitors up ${p.percent ?? 50}%+ vs a week before`;\n case 'goal_silent':\n return `No ${p.goal ?? 'goal'} for ${p.hours ?? 24}h`;\n case 'event_count':\n return `${p.event ?? 'Any event'} ${p.repeat ? 'every' : 'reaches'} ${n(p.count ?? 0)}`;\n default:\n return r.condition;\n }\n}\n\n/** What the rule applies to. */\nexport function ruleTarget(r: Pick<AlertRule, 'condition' | 'params' | 'experiment'>): string {\n if (ACCOUNT.includes(r.condition)) return 'this project';\n if (PROPERTY.includes(r.condition)) return `property ${r.params.property ?? '?'}`;\n return r.experiment ? `experiment ${r.experiment}` : 'every running experiment';\n}\n\n/** Milestone rules: how far the count got. */\nexport function ruleProgress(r: Pick<AlertRule, 'condition' | 'params'>): string {\n const pr = r.params.progress;\n if (!pr) return '';\n if (r.condition === 'usage' && r.params.every) return `${n(pr.total)} used this month, next at ${n((pr.fired + 1) * r.params.every)}`;\n if (r.condition === 'event_count' && r.params.count) {\n if (!r.params.repeat && pr.fired > 0) return `${n(pr.total)} counted, done`;\n return `${n(pr.total)} of ${n((pr.fired + 1) * r.params.count)}`;\n }\n return '';\n}\n\nfunction count(flags: Flags, flag: string, why: string): number {\n const v = parseCount(flags[flag]);\n if (!Number.isFinite(v) || v <= 0) fail('USAGE', `--${flag} N: ${why}.`);\n return v;\n}\nconst optional = (flags: Flags, flag: string): number | undefined => {\n if (flags[flag] === undefined) return undefined;\n const v = parseCount(flags[flag]);\n if (!Number.isFinite(v) || v < 0) fail('INVALID_FLAG', `--${flag} ${String(flags[flag])}: a number.`);\n return v;\n};\n\n/** POST body of a new rule from the typed condition and flags. */\nexport function ruleBody(condition: string, flags: Flags): Record<string, unknown> {\n if (!(ALERT_CONDITIONS as readonly string[]).includes(condition)) fail('USAGE', `Which condition? One of ${ALERT_CONDITIONS.join(', ')}.`, 'Example: npx splithub alerts add usage --every 1000');\n const params: AlertParams = {};\n const property = str(flags.property);\n const needProperty = () => {\n if (!property) fail('USAGE', `--property <id>: which analytics property to watch.`);\n params.property = property;\n };\n switch (condition as AlertCondition) {\n case 'winner':\n case 'loser':\n if (optional(flags, 'min-visitors') !== undefined) params.minVisitors = optional(flags, 'min-visitors');\n if (condition === 'loser') params.lift = optional(flags, 'lift') ?? 10;\n break;\n case 'exposures':\n params.visitors = count(flags, 'visitors', 'alert once the experiment reaches this many visitors');\n break;\n case 'conversions':\n params.conversions = count(flags, 'conversions', 'alert once the experiment reaches this many conversions');\n break;\n case 'duration':\n params.days = count(flags, 'days', 'alert once the experiment has run this many days');\n break;\n case 'no_events':\n case 'goal_silent':\n params.hours = optional(flags, 'hours') ?? 24;\n if (condition === 'goal_silent') {\n needProperty();\n const goal = str(flags.goal);\n if (!goal) fail('USAGE', '--goal <key>: the goal that should keep converting.');\n params.goal = goal;\n }\n break;\n case 'quota':\n params.percent = optional(flags, 'percent') ?? 80;\n break;\n case 'usage':\n params.every = count(flags, 'every', 'alert each time this many more events are used this month (100 or more)');\n if (params.every < 100) fail('INVALID_FLAG', '--every: 100 or more.');\n break;\n case 'traffic_drop':\n case 'traffic_spike':\n needProperty();\n params.percent = optional(flags, 'percent') ?? 50;\n break;\n case 'event_count':\n needProperty();\n if (str(flags.event)) params.event = str(flags.event);\n params.count = count(flags, 'count', 'alert when the event reaches this many');\n params.repeat = Boolean(flags.repeat);\n break;\n case 'srm':\n break;\n }\n const experiment = str(flags.experiment);\n if (experiment && (ACCOUNT.includes(condition) || PROPERTY.includes(condition))) fail('USAGE', `${condition} is not about one experiment: drop --experiment.`);\n const doing = {\n pause: Boolean(flags.pause),\n finish: Boolean(flags.finish),\n dropLoser: Boolean(flags['drop-loser']),\n };\n if ((doing.pause || doing.finish || doing.dropLoser) && (ACCOUNT.includes(condition) || PROPERTY.includes(condition))) fail('USAGE', 'This rule can only send a message: drop --pause / --finish / --drop-loser.');\n if (doing.dropLoser && condition !== 'loser' && condition !== 'winner') fail('USAGE', '--drop-loser goes with winner or loser.');\n const cooldown = optional(flags, 'cooldown');\n return {\n condition,\n params,\n actions: { notify: true, ...doing },\n ...(str(flags.name) ? { name: str(flags.name) } : {}),\n ...(experiment ? { experiment } : {}),\n ...(cooldown ? { cooldownHours: cooldown } : {}),\n enabled: !flags.disabled,\n };\n}\n\nasync function load(t: Target): Promise<AlertsData> {\n return request<AlertsData>(t, '/alerts');\n}\n\n/** A rule by id, the start of its id, or its name. */\nexport function pickRule(rules: AlertRule[], want: string): AlertRule {\n const w = want.toLowerCase();\n const rule = rules.find((r) => r.id === want) ?? rules.find((r) => w.length >= 4 && r.id.startsWith(w)) ?? rules.find((r) => r.name.toLowerCase() === w);\n if (!rule) fail('NOT_FOUND', `There's no alert rule \"${want}\".`, 'See them with npx splithub alerts.');\n return rule;\n}\n\nexport async function addRule(t: Target, body: Record<string, unknown>): Promise<{ rule: AlertRule; savedOff: boolean }> {\n try {\n return {\n ...(await request<{ rule: AlertRule }>(t, '/alerts/rules', {\n method: 'POST',\n body: JSON.stringify(body),\n })),\n savedOff: false,\n };\n } catch (error) {\n // Free plan: keep the rule, switched off, so upgrading is the only step left.\n if (error instanceof CliError && error.code === 'PRO_REQUIRED' && body.enabled !== false) {\n return {\n ...(await request<{ rule: AlertRule }>(t, '/alerts/rules', {\n method: 'POST',\n body: JSON.stringify({ ...body, enabled: false }),\n })),\n savedOff: true,\n };\n }\n throw error;\n }\n}\n\nexport async function alerts(args: string[], flags: Flags): Promise<void> {\n const t = cloudOnly(flags, 'Alerts', false);\n if (!t.token) requireCloudToken(flags);\n const [action, arg] = args;\n if (!action || action === 'list') return list(t, flags);\n if (action === 'add' || action === 'create') {\n if (!arg) fail('USAGE', `Which condition? npx splithub alerts add <condition>: ${ALERT_CONDITIONS.join(', ')}.`, 'Example: npx splithub alerts add usage --every 1000');\n const out = await addRule(t, ruleBody(arg, flags));\n if (flags.json) return printJson(out);\n console.log(`${c.green('✔')} ${c.bold(out.rule.name)} ${c.dim(`(${ruleTarget(out.rule)})`)}`);\n if (out.savedOff) console.log(c.yellow('! Saved, switched off: alert rules run on Pro. Upgrade in the dashboard (Billing), then npx splithub alerts enable ' + out.rule.id.slice(0, 8)));\n return;\n }\n if (!['enable', 'disable', 'delete', 'remove', 'test'].includes(action)) fail('USAGE', `Unknown \"alerts ${action}\". Use alerts, alerts add <condition>, alerts enable|disable|delete|test <id>.`);\n if (!arg) fail('USAGE', `Which rule? npx splithub alerts ${action} <id> (ids are in npx splithub alerts).`);\n const rule = pickRule((await load(t)).rules, arg);\n const path = `/alerts/rules/${enc(rule.id)}`;\n if (action === 'test') {\n const out = await request<{ matches: Array<{ experiment: string | null; message: string }> }>(t, `${path}/test`, { method: 'POST', body: '{}' });\n if (flags.json) return printJson({ rule: rule.id, ...out });\n if (out.matches.length === 0) return void console.log(c.dim(`${rule.name}: nothing matches right now, so it would stay quiet.`));\n console.log(`${c.bold(rule.name)} would fire now:`);\n for (const m of out.matches) console.log(` ${m.experiment ? c.dim(`${m.experiment}: `) : ''}${m.message}`);\n return;\n }\n if (action === 'delete' || action === 'remove') {\n await request(t, path, { method: 'DELETE' });\n if (flags.json) return printJson({ ok: true, id: rule.id });\n console.log(`${c.green('✔')} ${rule.name} deleted`);\n return;\n }\n const out = await request<{ rule: AlertRule }>(t, path, {\n method: 'PATCH',\n body: JSON.stringify({ enabled: action === 'enable' }),\n });\n if (flags.json) return printJson(out);\n console.log(`${c.green('✔')} ${rule.name} ${action === 'enable' ? 'is on' : 'is off'}`);\n}\n\nasync function list(t: Target, flags: Flags): Promise<void> {\n const data = await load(t);\n if (flags.json)\n return printJson({\n plan: data.plan,\n rules: data.rules,\n channels: data.channels,\n history: data.history,\n });\n if (data.rules.length === 0) console.log(c.dim('No alert rules yet. Add one: npx splithub alerts add usage --every 1000'));\n else {\n console.log(\n table(\n ['RULE', 'WHEN', 'FOR', 'PROGRESS', 'STATUS', 'ID'],\n data.rules.map((r) => [c.bold(r.name), describeRule(r), ruleTarget(r), ruleProgress(r) || c.dim('–'), r.enabled ? c.green('on') : c.dim('off'), c.dim(r.id.slice(0, 8))])\n )\n );\n }\n if (data.plan !== 'pro' && data.rules.length) console.log(c.dim('\\nAlert rules run on Pro: they fire once the project is on Pro (dashboard, Billing).'));\n if (data.channels.length === 0) console.log(c.dim('Where alerts go (email, Slack, Discord, webhook) is set in the dashboard, under Alerts.'));\n if (data.history.length) {\n console.log(`\\n${c.bold('Recent alerts')}`);\n for (const h of data.history.slice(0, 5)) console.log(`${c.dim(h.createdAt.slice(0, 16).replace('T', ' '))} ${h.message}`);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAsBO,IAAM,mBAAmB,CAAC,OAAO,UAAU,SAAS,aAAa,eAAe,YAAY,aAAa,SAAS,SAAS,gBAAgB,iBAAiB,eAAe,aAAa;AAE/L,IAAM,UAA6B,CAAC,SAAS,OAAO;AACpD,IAAM,WAA8B,CAAC,gBAAgB,iBAAiB,eAAe,aAAa;AA6ClG,IAAM,MAAM;AAGL,SAAS,WAAW,GAAoB;AAC7C,MAAI,OAAO,MAAM,YAAY,CAAC,EAAE,KAAK,EAAG,QAAO,OAAO;AACtD,QAAM,IAAI,+BAA+B,KAAK,EAAE,KAAK,EAAE,QAAQ,iBAAiB,EAAE,CAAC;AACnF,MAAI,CAAC,EAAG,QAAO,OAAO;AACtB,SAAO,KAAK,MAAM,OAAO,EAAE,CAAC,CAAC,KAAK,EAAE,CAAC,GAAG,YAAY,MAAM,MAAM,MAAQ,EAAE,CAAC,GAAG,YAAY,MAAM,MAAM,MAAY,EAAE;AACtH;AAGO,SAAS,aAAa,GAAoD;AAC/E,QAAM,IAAI,EAAE;AACZ,UAAQ,EAAE,WAAW;AAAA,IACnB,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO,aAAa,EAAE,QAAQ,CAAC;AAAA,IACjC,KAAK;AACH,aAAO,GAAG,EAAE,EAAE,YAAY,CAAC,CAAC;AAAA,IAC9B,KAAK;AACH,aAAO,GAAG,EAAE,EAAE,eAAe,CAAC,CAAC;AAAA,IACjC,KAAK;AACH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ClD,KAAK,MAAM,IAAI,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,IAAI,GAAG,aAAa,CAAC,GAAG,WAAW,CAAC,GAAG,aAAa,CAAC,KAAK,EAAE,IAAI,QAAG,GAAG,EAAE,UAAU,EAAE,MAAM,IAAI,IAAI,EAAE,IAAI,KAAK,GAAG,EAAE,IAAI,EAAE,GAAG,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC;AAAA,MAC1K;AAAA,IACF;AAAA,EACF;AACA,MAAI,KAAK,SAAS,SAAS,KAAK,MAAM,OAAQ,SAAQ,IAAI,EAAE,IAAI,sFAAsF,CAAC;AACvJ,MAAI,KAAK,SAAS,WAAW,EAAG,SAAQ,IAAI,EAAE,IAAI,yFAAyF,CAAC;AAC5I,MAAI,KAAK,QAAQ,QAAQ;AACvB,YAAQ,IAAI;AAAA,EAAK,EAAE,KAAK,eAAe,CAAC,EAAE;AAC1C,eAAW,KAAK,KAAK,QAAQ,MAAM,GAAG,CAAC,EAAG,SAAQ,IAAI,GAAG,EAAE,IAAI,EAAE,UAAU,MAAM,GAAG,EAAE,EAAE,QAAQ,KAAK,GAAG,CAAC,CAAC,KAAK,EAAE,OAAO,EAAE;AAAA,EAC5H;AACF;","names":["out"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/experiment-reports.ts"],"sourcesContent":["// One experiment, read closer (sh2 Cloud only: a self-hosted endpoint keeps raw counts).\n//\n// splithub results <id> [--from --to] [--filter country=DE ...] the verdict on a slice: first-exposure days, visitor filters\n// splithub results <id> --by <dimension> every segment's variants against the control there\n// splithub results <id> --timeline visitors and conversions per day and variant\n// splithub results <id> --engagement bounce, visit length, pages per visit per variant\n// splithub results <id> --events every goal and event per variant, lift vs control\n// splithub results <id> --export --by <dimension> > file.csv the breakdown as CSV\n// splithub events --experiment <id> [--type exposure|goal] [--limit 50] [--before <ms>] the raw tail\n//\n// Every view takes --from / --to (YYYY-MM-DD, first-exposure days in the project time zone) and --filter.\n\nimport { request, requestText, type Target } from '../api';\nimport { fail, printJson } from '../errors';\nimport { c, pct, table } from '../ui';\nimport { cloudOnly, filterFlags, n, reportQuery, str } from './analytics-reports';\nimport type { Flags } from './init';\nimport { noteKind } from './notes';\n\n/** Visitor columns an experiment report can be filtered by (`--filter <key>=a,b`); `page` is analytics' word for `landing`. */\nexport const EXPERIMENT_FILTERS = ['country', 'region', 'city', 'device', 'os', 'browser', 'language', 'host', 'platform', 'app_version', 'source', 'channel', 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'landing', 'page'] as const;\n/** Dimensions a breakdown splits visitors by (`--by`); `page` is analytics' word for `url`. */\nexport const EXPERIMENT_BY = ['country', 'region', 'city', 'device', 'os', 'browser', 'language', 'host', 'platform', 'app_version', 'page', 'url', 'referrer', 'source', 'channel', 'landing', 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'] as const;\n\n/** Column title of a dimension: `url` reads \"page\", as in analytics and the dashboard. */\nexport const dimensionLabel = (by: string): string => (by === 'url' ? 'page' : by);\n\nconst DAY = /^\\d{4}-\\d{2}-\\d{2}$/;\nconst enc = encodeURIComponent;\nconst RAW_HINT = 'Read the raw counts with npx splithub results <id>.';\n\nexport interface Scope {\n filtered: boolean;\n range: { from: string; to: string } | null;\n filters: Record<string, string | string[]>;\n note?: string;\n}\n\n/** True when the flags ask for more than the plain all-time results. */\nexport function wantsSlice(flags: Flags): boolean {\n return Boolean(str(flags.from) || str(Array.isArray(flags.to) ? flags.to[0] : flags.to) || Number(flags.days) > 0 || (Array.isArray(flags.filter) ? flags.filter.length : flags.filter));\n}\n\n/** `?from=&to=&country=DE…` for an experiment report; refuses dates and filters the server can't read. */\nexport function experimentQuery(flags: Flags, extra: Record<string, string> = {}): string {\n for (const [name, v] of [['from', flags.from], ['to', Array.isArray(flags.to) ? flags.to[0] : flags.to]] as const) {\n const day = str(v);\n if (day && !DAY.test(day)) fail('INVALID_FLAG', `--${name} ${day}: use a day like 2026-10-01.`);\n }\n for (const k of Object.keys(filterFlags(flags))) {\n if (!(EXPERIMENT_FILTERS as readonly string[]).includes(k)) fail('INVALID_FLAG', `--filter ${k}: experiments filter by ${EXPERIMENT_FILTERS.join(', ')}.`);\n }\n return reportQuery(flags, extra);\n}\n\n/** \"first seen 2026-10-01 → 2026-10-15 · country=DE\", or null for the whole experiment. */\nexport function describeScope(scope: Scope | undefined): string | null {\n if (!scope || (!scope.filtered && !scope.range)) return null;\n const parts: string[] = [];\n if (scope.range) parts.push(`first seen ${scope.range.from} → ${scope.range.to}`);\n for (const [k, v] of Object.entries(scope.filters ?? {})) parts.push(`${k}=${Array.isArray(v) ? v.join(',') : v}`);\n return parts.join(' · ');\n}\n\n/** The slice banner printed above a filtered or ranged report. */\nexport function printScope(scope: Scope | undefined): void {\n const what = describeScope(scope);\n if (!what) return;\n console.log(c.yellow(`Filtered slice: ${what}`));\n if (scope?.note) console.log(c.dim(scope.note));\n console.log();\n}\n\nconst target = (flags: Flags, what: string): Target => cloudOnly(flags, what, true, RAW_HINT);\n\n// ---------------------------------------------------------------------------\n// Results on a slice\n// ---------------------------------------------------------------------------\n\n/** GET /results/<id> with a range and filters; the caller prints it like the whole-experiment results. */\nexport async function fetchSlice<T>(key: string, flags: Flags): Promise<T> {\n const t = target(flags, 'Filtered results');\n return request<T>(t, `/results/${enc(key)}${experimentQuery(flags)}`, {}, key);\n}\n\n// ---------------------------------------------------------------------------\n// Breakdown\n// ---------------------------------------------------------------------------\n\ninterface SegmentRow {\n dim: string;\n cells: Array<{ variant: string; exposures: number; conversions: number } | null>;\n comparisons: Array<{ variant: string; lift: number | null; pValue: number; significant: boolean; better: boolean }>;\n total: number;\n small: boolean;\n}\nexport interface BreakdownData {\n experiment: string;\n by: string;\n goal: string | null;\n order: string[];\n segments: SegmentRow[];\n scope?: Scope;\n}\n\nfunction byFlag(flags: Flags): string {\n const by = str(flags.by);\n if (!by) return fail('USAGE', 'Split by what? Add --by country (or device, source, channel, landing, …).');\n if (!(EXPERIMENT_BY as readonly string[]).includes(by)) fail('INVALID_FLAG', `--by ${by}: use one of ${EXPERIMENT_BY.join(', ')}.`);\n return by;\n}\n\n/** A lift cell: green ✔ / red ✖ when the difference is clear, plain otherwise. */\nfunction liftCell(cmp: SegmentRow['comparisons'][number] | undefined): string {\n if (!cmp || cmp.lift === null) return c.dim('–');\n const text = pct(cmp.lift, true);\n if (!cmp.significant) return text;\n return cmp.better ? c.green(`${text} ✔`) : c.red(`${text} ✖`);\n}\n\nexport function breakdownTable(data: BreakdownData, limit = 20): string {\n const [control, ...others] = data.order;\n const rows = data.segments.slice(0, limit).map((s) => {\n const name = s.dim === '' || s.dim === '(none)' ? c.dim('(none)') : s.small ? c.dim(s.dim) : s.dim;\n const rates = data.order.map((_, i) => {\n const cell = s.cells[i];\n return cell && cell.exposures > 0 ? `${pct(cell.conversions / cell.exposures)} ${c.dim(`of ${n(cell.exposures)}`)}` : c.dim('–');\n });\n return [name, n(s.total), ...rates, ...others.map((v) => liftCell(s.comparisons.find((x) => x.variant === v)))];\n });\n const head = [dimensionLabel(data.by).toUpperCase(), 'VISITORS', ...data.order.map((v) => (v === control ? `${v} (control)` : v)), ...others.map((v) => `LIFT ${v}`)];\n return table(head, rows);\n}\n\nexport async function breakdown(key: string, flags: Flags): Promise<void> {\n const by = byFlag(flags);\n const t = target(flags, 'Breakdowns');\n const data = await request<BreakdownData>(t, `/experiments/${enc(key)}/breakdown/${enc(by)}${experimentQuery(flags)}`, {}, key);\n if (flags.json) return printJson({ ...data, experiment: key, view: 'breakdown' });\n console.log(`${c.bold(key)} ${c.dim(`· by ${dimensionLabel(by)} · goal: ${data.goal ?? 'none'}`)}\\n`);\n printScope(data.scope);\n if (data.segments.length === 0) return void console.log(c.dim('No visitors in this slice yet.'));\n console.log(breakdownTable(data, Number(flags.limit) || 20));\n console.log(c.dim(`\\nLift is against the control inside each segment; ✔ and ✖ mark a clear difference, dim rows have too few visitors.`));\n console.log(c.dim('Segments are for exploring: the verdict is on the whole experiment.'));\n}\n\nexport async function breakdownCsv(key: string, flags: Flags): Promise<void> {\n const by = byFlag(flags);\n const t = target(flags, 'Exports');\n const csv = await requestText(t, `/experiments/${enc(key)}/export.breakdown.csv${experimentQuery(flags, { by })}`);\n if (flags.json) return printJson({ experiment: key, by, csv });\n process.stdout.write(csv.replace(/\\r\\n/g, '\\n'));\n}\n\n// ---------------------------------------------------------------------------\n// Timeline\n// ---------------------------------------------------------------------------\n\ninterface DayRow {\n day: string;\n variant: string;\n n: number;\n}\nexport interface TimelineData {\n experiment: string;\n goal: string | null;\n mode?: string;\n exposures: DayRow[];\n conversions: DayRow[];\n notes?: Array<{ day: string; kind?: string; text: string }>;\n scope?: Scope;\n}\n\nexport function timelineTable(data: TimelineData): string {\n const variants = [...new Set([...data.exposures, ...data.conversions].map((r) => r.variant))];\n const days = [...new Set([...data.exposures, ...data.conversions].map((r) => r.day))].sort();\n const count = (rows: DayRow[]) => new Map(rows.map((r) => [`${r.day}|${r.variant}`, r.n]));\n const seen = count(data.exposures);\n const conv = count(data.conversions);\n const head = ['DAY', ...variants.flatMap((v) => [v, 'CONV', 'RATE'])];\n const rows = days.map((d) => [\n d,\n ...variants.flatMap((v) => {\n const x = seen.get(`${d}|${v}`) ?? 0;\n const y = conv.get(`${d}|${v}`) ?? 0;\n return [n(x), n(y), x > 0 ? pct(y / x) : c.dim('–')];\n }),\n ]);\n return table(head, rows);\n}\n\nexport async function timeline(key: string, flags: Flags): Promise<void> {\n const t = target(flags, 'Timelines');\n const data = await request<TimelineData>(t, `/experiments/${enc(key)}/timeline${experimentQuery(flags)}`, {}, key);\n if (flags.json) return printJson({ ...data, experiment: key, view: 'timeline' });\n console.log(`${c.bold(key)} ${c.dim(`· per day · goal: ${data.goal ?? 'none'}`)}\\n`);\n printScope(data.scope);\n if (data.exposures.length === 0) return void console.log(c.dim('No visitors in this slice yet.'));\n console.log(timelineTable(data));\n if (data.mode !== 'goal_day') console.log(c.dim(\"\\nA day counts the visitors first seen that day and how many of them converted, whenever they did.\"));\n if (data.notes?.length) {\n console.log(`\\n${c.bold('Notes')}`);\n for (const a of data.notes.slice(-5)) console.log(`${c.dim(a.day)} ${a.kind && a.kind !== 'note' ? `${noteKind(a.kind)} ` : ''}${a.text}`);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Engagement (from the analytics property collecting on the same visitors)\n// ---------------------------------------------------------------------------\n\nexport interface EngagementData {\n property: string | null;\n variants: Array<{ variant: string; visitors: number; sessions: number; pageviews: number; bounces: number; duration: number; pagesPerVisit: number; bounceRate: number; avgVisit: number }>;\n scope?: Scope;\n}\n\n/** Milliseconds as `42s` or `3m 05s`. */\nexport function visitLength(ms: number): string {\n if (!Number.isFinite(ms) || ms <= 0) return '0s';\n const s = Math.round(ms / 1000);\n return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${String(s % 60).padStart(2, '0')}s`;\n}\n\nexport async function engagement(key: string, flags: Flags): Promise<void> {\n const t = target(flags, 'Engagement by variant');\n const data = await request<EngagementData>(t, `/experiments/${enc(key)}/engagement${experimentQuery(flags, str(flags.property) ? { property: str(flags.property)! } : {})}`, {}, key);\n if (flags.json) return printJson({ ...data, experiment: key, view: 'engagement' });\n if (!data.property || data.variants.length === 0) {\n console.log(c.dim('No analytics on these visitors yet. Name a property on the provider (or sh.js) to see visits per variant.'));\n return;\n }\n console.log(`${c.bold(key)} ${c.dim(`· engagement from ${data.property}`)}\\n`);\n printScope(data.scope);\n console.log(\n table(\n ['VARIANT', 'VISITORS', 'VISITS', 'PAGES / VISIT', 'BOUNCE', 'AVG VISIT'],\n data.variants.map((v, i) => [i === 0 ? `${v.variant} ${c.dim('(control)')}` : v.variant, n(v.visitors), n(v.sessions), v.sessions ? v.pagesPerVisit.toFixed(2) : c.dim('–'), v.sessions ? pct(v.bounceRate) : c.dim('–'), v.sessions ? visitLength(v.avgVisit) : c.dim('–')])\n )\n );\n console.log(c.dim('\\nCounts to read next to the verdict, not a verdict.'));\n}\n\n// ---------------------------------------------------------------------------\n// Events by variant: every goal and event of the experiment's visitors\n// ---------------------------------------------------------------------------\n\nexport interface EventsByVariantData {\n experiment: string;\n goal: string | null;\n property: string | null;\n variants: string[];\n visitors: Record<string, number>;\n rows: Array<{\n name: string;\n goalKey: string | null;\n isGoal: boolean;\n measured: 'goal' | 'metric' | 'guardrail' | null;\n perVariant: Record<string, { visitors: number; count: number | null; rate: number | null; revenue: number }>;\n comparisons: SegmentRow['comparisons'];\n small: boolean;\n }>;\n scope?: Scope;\n}\n\nconst ROLE: Record<string, string> = { goal: 'goal', metric: 'metric', guardrail: 'guardrail' };\n\nexport function eventsTable(data: EventsByVariantData, limit = 30): string {\n const [control, ...others] = data.variants;\n const rows = data.rows.slice(0, limit).map((r) => {\n const role = r.measured ? ROLE[r.measured] : r.isGoal ? 'goal' : '';\n const label = r.goalKey && r.goalKey !== r.name ? `${r.name} ${c.dim(r.goalKey)}` : r.name;\n const cells = data.variants.map((v) => {\n const x = r.perVariant[v];\n return x && x.rate !== null ? `${n(x.visitors)} ${c.dim(`· ${pct(x.rate)}`)}` : c.dim('–');\n });\n return [r.small ? c.dim(r.name) : label, role ? c.dim(role) : '', ...cells, ...others.map((v) => (r.small ? c.dim('–') : liftCell(r.comparisons.find((x) => x.variant === v))))];\n });\n const head = ['EVENT', 'ROLE', ...data.variants.map((v) => (v === control ? `${v} (control)` : v)), ...others.map((v) => `LIFT ${v}`)];\n return table(head, rows);\n}\n\nexport async function eventsByVariant(key: string, flags: Flags): Promise<void> {\n const t = target(flags, 'Events by variant');\n const data = await request<EventsByVariantData>(t, `/experiments/${enc(key)}/events-summary${experimentQuery(flags, str(flags.property) ? { property: str(flags.property)! } : {})}`, {}, key);\n if (flags.json) return printJson({ ...data, experiment: key, view: 'events' });\n console.log(`${c.bold(key)} ${c.dim(`· events by variant${data.property ? ` · from ${data.property}` : ''}`)}\\n`);\n printScope(data.scope);\n if (data.rows.length === 0) return void console.log(c.dim('No goals or events from these visitors yet.'));\n console.log(eventsTable(data, Number(flags.limit) || 30));\n console.log(c.dim('\\nVisitors who did it · their rate; lift is against the control, ✔ and ✖ mark a clear difference, dim rows have too few visitors.'));\n if (!data.property) console.log(c.dim('Only goals so far: other events show up once an analytics property runs on the same site.'));\n console.log(c.dim('The verdict is on the experiment goal; the other rows are for exploring.'));\n}\n\nexport async function eventsByVariantCsv(key: string, flags: Flags): Promise<void> {\n const t = target(flags, 'Exports');\n const csv = await requestText(t, `/experiments/${enc(key)}/export.events-summary.csv${experimentQuery(flags)}`);\n if (flags.json) return printJson({ experiment: key, view: 'events', csv });\n process.stdout.write(csv.replace(/\\r\\n/g, '\\n'));\n}\n\n// ---------------------------------------------------------------------------\n// Raw events\n// ---------------------------------------------------------------------------\n\ninterface RawEvent {\n id: string;\n type: string;\n variant: string | null;\n goal: string | null;\n visitorId: string;\n ts: number;\n url: string | null;\n country: string | null;\n}\n\nexport async function experimentEvents(key: string | undefined, flags: Flags): Promise<void> {\n if (!key) fail('USAGE', 'Which experiment? npx splithub events --experiment <id>');\n const type = str(flags.type);\n if (type && type !== 'exposure' && type !== 'goal') fail('INVALID_FLAG', `--type ${type}: use exposure or goal.`);\n const before = str(flags.before);\n if (before && !(Number(before) > 0)) fail('INVALID_FLAG', `--before ${before}: use a time in milliseconds, like the nextBefore of the last page.`);\n const limit = Math.max(1, Math.min(200, Number(flags.limit) || 50));\n const t = target(flags, 'Raw experiment events');\n const extra: Record<string, string> = { limit: String(limit), ...(type ? { type } : {}), ...(before ? { before } : {}) };\n const data = await request<{ events: RawEvent[]; nextBefore: number | null; scope?: Scope }>(t, `/experiments/${enc(key)}/events${experimentQuery(flags, extra)}`, {}, key);\n if (flags.json) return printJson({ ...data, experiment: key });\n if (data.events.length === 0) return void console.log(c.dim('No events in this slice. Raw events stay 7 days (30 on Pro).'));\n console.log(\n table(\n ['TIME', 'TYPE', 'VARIANT / GOAL', 'VISITOR', 'URL', 'COUNTRY'],\n data.events.map((e) => [new Date(Number(e.ts)).toISOString().replace('T', ' ').slice(0, 19), e.type, (e.type === 'exposure' ? e.variant : e.goal) ?? '', String(e.visitorId ?? '').slice(0, 12), e.url ?? '', e.country ?? ''])\n )\n );\n if (data.nextBefore) console.log(c.dim(`\\nOlder: --before ${data.nextBefore}`));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAoBO,IAAM,qBAAqB,CAAC,WAAW,UAAU,QAAQ,UAAU,MAAM,WAAW,YAAY,QAAQ,YAAY,eAAe,UAAU,WAAW,cAAc,cAAc,gBAAgB,YAAY,eAAe,WAAW,MAAM;AAEhP,IAAM,gBAAgB,CAAC,WAAW,UAAU,QAAQ,UAAU,MAAM,WAAW,YAAY,QAAQ,YAAY,eAAe,QAAQ,OAAO,YAAY,UAAU,WAAW,WAAW,cAAc,cAAc,gBAAgB,YAAY,aAAa;AAG9P,IAAM,iBAAiB,CAAC,OAAwB,OAAO,QAAQ,SAAS;AAE/E,IAAM,MAAM;AACZ,IAAM,MAAM;AACZ,IAAM,WAAW;AAUV,SAAS,WAAW,OAAuB;AAChD,SAAO,QAAQ,IAAI,MAAM,IAAI,KAAK,IAAI,MAAM,QAAQ,MAAM,EAAE,IAAI,MAAM,GAAG,CAAC,IAAI,MAAM,EAAE,KAAK,OAAO,MAAM,IAAI,IAAI,MAAM,MAAM,QAAQ,MAAM,MAAM,IAAI,MAAM,OAAO,SAAS,MAAM,OAAO;AACzL;AAGO,SAAS,gBAAgB,OAAc,QAAgC,CAAC,GAAW;AACxF,aAAW,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,QAAQ,MAAM,IAAI,GAAG,CAAC,MAAM,MAAM,QAAQ,MAAM,EAAE,IAAI,MAAM,GAAG,CAAC,IAAI,MAAM,EAAE,CAAC,GAAY;AACjH,UAAM,MAAM,IAAI,CAAC;AACjB,QAAI,OAAO,CAAC,IAAI,KAAK,GAAG,EAAG,MAAK,gBAAgB,KAAK,IAAI,IAAI,GAAG,8BAA8B;AAAA,EAChG;AACA,aAAW,KAAK,OAAO,KAAK,YAAY,K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AAE,KAAK,IAAI,CAAC,GAAI,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC,EAAG;AACvH,QAAM,OAAO,MAAM,QAA0E,GAAG,gBAAgB,IAAI,GAAG,CAAC,UAAU,gBAAgB,OAAO,KAAK,CAAC,IAAI,CAAC,GAAG,GAAG;AAC1K,MAAI,MAAM,KAAM,QAAO,UAAU,EAAE,GAAG,MAAM,YAAY,IAAI,CAAC;AAC7D,MAAI,KAAK,OAAO,WAAW,EAAG,QAAO,KAAK,QAAQ,IAAI,EAAE,IAAI,8DAA8D,CAAC;AAC3H,UAAQ;AAAA,IACN;AAAA,MACE,CAAC,QAAQ,QAAQ,kBAAkB,WAAW,OAAO,SAAS;AAAA,MAC9D,KAAK,OAAO,IAAI,CAAC,MAAM,CAAC,IAAI,KAAK,OAAO,EAAE,EAAE,CAAC,EAAE,YAAY,EAAE,QAAQ,KAAK,GAAG,EAAE,MAAM,GAAG,EAAE,GAAG,EAAE,OAAO,EAAE,SAAS,aAAa,EAAE,UAAU,EAAE,SAAS,IAAI,OAAO,EAAE,aAAa,EAAE,EAAE,MAAM,GAAG,EAAE,GAAG,EAAE,OAAO,IAAI,EAAE,WAAW,EAAE,CAAC;AAAA,IAChO;AAAA,EACF;AACA,MAAI,KAAK,WAAY,SAAQ,IAAI,EAAE,IAAI;AAAA,kBAAqB,KAAK,UAAU,EAAE,CAAC;AAChF;","names":["rows"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/notes.ts"],"sourcesContent":["// splithub notes — what happened on a day (\"launched the new pricing page\", \"checkout broke on\n// Safari\"). One list for the project: a note belongs to one experiment, one analytics property, or\n// the whole project (shown on every chart). sh2 Cloud only.\n//\n// splithub notes [--experiment <key> | --property <id>] [--kind note|issue|win] [--days 30 | --from --to]\n// splithub notes add \"<text>\" [--kind issue|win|note] [--experiment <key> | --property <id>] [--day YYYY-MM-DD]\n// splithub notes edit <id> [\"<new text>\"] [--kind ...] [--day ...]\n// splithub notes delete <id>\n\nimport { request } from '../api';\nimport { fail, printJson } from '../errors';\nimport { c, table } from '../ui';\nimport { cloudOnly, reportQuery, str } from './analytics-reports';\nimport type { Flags } from './init';\n\nexport const NOTE_KINDS = ['note', 'issue', 'win'] as const;\nconst DAY = /^\\d{4}-\\d{2}-\\d{2}$/;\nconst enc = encodeURIComponent;\n\nexport interface Note {\n id: string;\n day: string;\n kind: (typeof NOTE_KINDS)[number];\n text: string;\n experimentKey: string | null;\n propertyKey: string | null;\n createdAt: string;\n author: { name: string | null; email: string | null } | null;\n}\n\nconst KIND_MARK: Record<string, (s: string) => string> = {\n note: c.dim,\n issue: c.red,\n win: c.green,\n};\nexport const noteKind = (k: string) => (KIND_MARK[k] ?? c.dim)(k);\nexport const noteScope = (n: Pick<Note, 'experimentKey' | 'propertyKey'>) => (n.experimentKey ? `experiment ${n.experimentKey}` : n.propertyKey ? `property ${n.propertyKey}` : c.dim('whole project'));\n\nfunction kindFlag(flags: Flags): string | undefined {\n const kind = str(flags.kind);\n if (kind && !(NOTE_KINDS as readonly string[]).includes(kind)) fail('INVALID_FLAG', `--kind ${kind}: use note, issue or win.`);\n return kind;\n}\n\nfunction dayFlag(flags: Flags): string | undefined {\n const day = str(flags.day);\n if (day && !DAY.test(day)) fail('INVALID_FLAG', `--day ${day}: use a day like 2026-10-01.`);\n return day;\n}\n\nexport async function notes(args: string[], flags: Flags): Promise<void> {\n const [action, ...rest] = args;\n const t = cloudOnly(flags, 'Notes', false);\n if (action === 'add') {\n const text = rest.join(' ').trim();\n if (!text) fail('USAGE', 'What happened? npx splithub notes add \"Launched the new pricing page\" [--kind win] [--experiment <key> | --property <id>]');\n const experiment = str(flags.experiment);\n const property = str(flags.property);\n if (experiment && property) fail('USAGE', 'A note belongs to one experiment or one property, not both.');\n const kind = kindFlag(flags);\n const day = dayFlag(flags);\n const body = {\n text,\n ...(kind ? { kind } : {}),\n ...(day ? { day } : {}),\n ...(experiment ? { experimentKey: experiment } : {}),\n ...(property ? { propertyKey: property } : {}),\n };\n const out = await request<{ note: Note }>(t, '/notes', {\n method: 'POST',\n body: JSON.stringify(body),\n });\n if (flags.json) return printJson(out);\n console.log(`${c.green('✔')} noted on ${out.note.day} ${c.dim(`(${out.note.kind}, ${noteScope(out.note)})`)}`);\n return;\n }\n if (action === 'edit') {\n const [id, ...words] = rest;\n if (!id) fail('USAGE', 'Which note? npx splithub notes edit <id> \"New text\" [--kind win] [--day 2026-10-01]');\n const text = words.join(' ').trim();\n const kind = kindFlag(flags);\n const day = dayFlag(flags);\n if (!text && !kind && !day) fail('USAGE', 'Nothing to change: give new text, --kind or --day.');\n const out = await request<{ note: Note }>(t, `/notes/${enc(id)}`, {\n method: 'PATCH',\n body: JSON.stringify({\n ...(text ? { text } : {}),\n ...(kind ? { kind } : {}),\n ...(day ? { day } : {}),\n }),\n });\n if (flags.json) return printJson(out);\n console.log(`${c.green('✔')} note updated ${c.dim(`(${out.note.day}, ${out.note.kind})`)}`);\n return;\n }\n if (action === 'delete' || action === 'remove') {\n const id = rest[0];\n if (!id) fail('USAGE', 'Which note? npx splithub notes delete <id> (ids are in npx splithub notes).');\n await request(t, `/notes/${enc(id)}`, { method: 'DELETE' });\n if (flags.json) return printJson({ ok: true, id });\n console.log(`${c.green('✔')} note deleted`);\n return;\n }\n if (action && action !== 'list') fail('USAGE', `Unknown \"notes ${action}\". Use notes, notes add \"<text>\", notes edit <id> or notes delete <id>.`);\n return listNotes(flags);\n}\n\nasync function listNotes(flags: Flags): Promise<void> {\n const t = cloudOnly(flags, 'Notes', false);\n const q = new URLSearchParams(reportQuery(flags).slice(1));\n for (const k of [...q.keys()]) if (k !== 'from' && k !== 'to') q.delete(k);\n const experiment = str(flags.experiment);\n const property = str(flags.property);\n const kind = kindFlag(flags);\n if (experiment) q.set('experiment', experiment);\n else if (property) q.set('property', property);\n if (kind) q.set('kind', kind);\n const s = q.toString();\n const data = await request<{ notes: Note[] }>(t, `/notes${s ? `?${s}` : ''}`);\n if (flags.json) return printJson(data);\n if (data.notes.length === 0) return void console.log(c.dim('No notes yet. Add one when you ship something: npx splithub notes add \"Launched the new pricing page\"'));\n const rows = data.notes.slice(0, Number(flags.limit) || 50);\n console.log(\n table(\n ['DAY', 'KIND', 'NOTE', 'FOR', 'BY', 'ID'],\n rows.map((n) => [n.day, noteKind(n.kind), n.text.length > 80 ? `${n.text.slice(0, 79)}…` : n.text, noteScope(n), n.author?.name ?? n.author?.email ?? c.dim('–'), c.dim(n.id)])\n )\n );\n if (data.notes.length > rows.length) console.log(c.dim(`\\n${data.notes.length - rows.length} more: --limit ${data.notes.length}, or narrow with --days, --experiment, --property, --kind.`));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAeO,IAAM,aAAa,CAAC,QAAQ,SAAS,KAAK;AACjD,IAAM,MAAM;AACZ,IAAM,MAAM;AAaZ,IAAM,YAAmD;AAAA,EACvD,MAAM,EAAE;AAAA,EACR,OAAO,EAAE;AAAA,EACT,KAAK,EAAE;AACT;AACO,IAAM,WAAW,CAAC,OAAe,UAAU,CAAC,KAAK,EAAE,KAAK,CAAC;AACzD,IAAM,YAAY,CAAC,MAAoD,EAAE,gBAAgB,cAAc,EAAE,aAAa,KAAK,EAAE,cAAc,YAAY,EAAE,WAAW,KAAK,EAAE,IAAI,eAAe;AAErM,SAAS,SAAS,OAAkC;AAClD,QAAM,OAAO,IAAI,MAAM,IAAI;AAC3B,MAAI,QAAQ,CAAE,WAAiC,SAAS,IAAI,EAAG,MAAK,gBAAgB,UAAU,IAAI,2BAA2B;AAC7H,SAAO;AACT;AAEA,SAAS,QAAQ,OAAkC;AACjD,QAAM,MAAM,IAAI,MAAM,GAAG;AACzB,MAAI,OAAO,CAAC,IAAI,KAAK,GAAG,EAAG,MAAK,gBAAgB,SAAS,GAAG,8BAA8B;AAC1F,SAAO;AACT;AAEA,eAAsB,MAAM,MAAgB,OAA6B;AACvE,QAAM,CAAC,QAAQ,GAAG,IAAI,IAAI;AAC1B,QAAM,IAAI,UAAU,OAAO,SAAS,KAAK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