splithub 0.1.7 → 0.1.9
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.
- package/dist/index.js +19 -15
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -410,15 +410,17 @@ combinations and, below them, each factor summed over its combinations). With li
|
|
|
410
410
|
2. Goal: pick an existing key or add one to \`goals\`:
|
|
411
411
|
\`{ type: 'event' }\` + \`track('<goal>')\` where the conversion happens; \`{ type: 'pageview', path: '/thanks' }\`;
|
|
412
412
|
\`{ type: 'click', selector: '#buy' }\` (tracked automatically by the SDK and the script).
|
|
413
|
-
3. Wire it in code
|
|
413
|
+
3. Wire it in code. \`create\` writes \`status: 'running'\`: the test goes live for every visitor, first page view
|
|
414
|
+
included, as soon as this code is deployed. Use \`--status draft\` only when the user asks to hold it.
|
|
414
415
|
4. Cloud mode: \`npx splithub push\` after any config change.
|
|
415
|
-
5. Hand-off, always: end your reply by saying the test is
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
416
|
+
5. Hand-off, always: end your reply by saying the test is **running in the config** and goes live when the user deploys
|
|
417
|
+
this code; nothing is recorded before that, and local development never sends events to the cloud. Tell them how to
|
|
418
|
+
check it locally (\`?sh_force=<id>:<variant>\`) and that Pause in the dashboard or \`npx splithub pause <id>\` holds it.
|
|
419
|
+
In cloud mode a status set in the dashboard wins over the file for every visitor, first page included.
|
|
420
|
+
For a draft (only if asked): say visitors do not see it and nothing is recorded until \`npx splithub start <id>\`.
|
|
421
|
+
|
|
422
|
+
A draft is invisible to visitors. To check one before starting: \`runDraftsInDev: true\` at the top level of the config
|
|
423
|
+
serves drafts like running tests in development only (\`NODE_ENV=development\`: \`next dev\`, \`vite\`);
|
|
422
424
|
\`?sh_force=<id>:<variant>\` shows one variant on any page, draft or not, without recording an exposure;
|
|
423
425
|
\`?sh_debug=1\` (or \`npx splithub dev\`) logs every decision and opens a panel to switch variants.
|
|
424
426
|
In development the SDK explains drafts, paused tests and held-back events in one line each. Vite apps: add \`splithub()\`
|
|
@@ -618,8 +620,8 @@ Env: \`SPLITHUB_PROJECT_DIR\` (defaults to the MCP client's working directory),
|
|
|
618
620
|
|
|
619
621
|
## Working rules
|
|
620
622
|
|
|
621
|
-
- Create \u2192 wire in code \u2192 \`doctor\` \u2192 \`push\` (cloud mode) \u2192 tell the user
|
|
622
|
-
and
|
|
623
|
+
- Create (running by default) \u2192 wire in code \u2192 \`doctor\` \u2192 \`push\` (cloud mode) \u2192 tell the user it goes live when they
|
|
624
|
+
deploy this code and that \`set_status paused\` or Pause in the dashboard holds it.
|
|
623
625
|
- Results: never call a winner from raw rates; quote the verdict. \`srm_detected\` = fix the setup first.
|
|
624
626
|
- Running experiments are frozen: no weight / variant / seed edits; create a new one.
|
|
625
627
|
- If a tool answers that the folder is not connected, call \`splithub_login\`, show the link to the user, wait for them, then retry.
|
|
@@ -727,8 +729,8 @@ This project uses SplitHub (\`@splithub/react\`). Experiments are declared in
|
|
|
727
729
|
- Lifecycle: \`npx splithub start|pause|finish <id>\`. Check setup: \`npx splithub doctor\`.
|
|
728
730
|
- A \`finished\` test still has all its variants in the code: report the verdict, ask which variant to keep and whether to
|
|
729
731
|
remove the test from the code, then follow .claude/skills/splithub-ship/SKILL.md. Never delete test code unasked.
|
|
730
|
-
-
|
|
731
|
-
|
|
732
|
+
- \`create\` writes \`status: 'running'\`: the test goes live when the code is deployed. Always tell the user that, and that
|
|
733
|
+
\`npx splithub pause <id>\` or Pause in the dashboard holds it. Never change \`seed\` of a running experiment.
|
|
732
734
|
- Config ships to the browser: no secrets in it. Full rules: .claude/skills/splithub/SKILL.md
|
|
733
735
|
`;
|
|
734
736
|
var CURSOR_RULE = `---
|
|
@@ -962,7 +964,7 @@ async function create(flags) {
|
|
|
962
964
|
}
|
|
963
965
|
}
|
|
964
966
|
if (goal && !goals.includes(goal)) throw new Error(`goal "${goal}" is not declared in splithub.config.ts goals: ${goals.join(", ") || "none"}`);
|
|
965
|
-
const status2 = str(flags.status) ?? "
|
|
967
|
+
const status2 = str(flags.status) ?? "running";
|
|
966
968
|
const description = str(flags.description);
|
|
967
969
|
const experiment = {
|
|
968
970
|
key: id,
|
|
@@ -1000,8 +1002,9 @@ ${variantKeys.map((k2) => ` <Variant name="${k2}"><${componentNames[k2]} /></Va
|
|
|
1000
1002
|
const result = { experiment: id, kind, status: status2, variants: experiment.variants, goal: goal ?? null, configFile: relative(project.root, project.configFile), files, snippet };
|
|
1001
1003
|
if (json) {
|
|
1002
1004
|
const cloudMode = /mode\s*:\s*['"]cloud['"]/.test(readSource(project.configFile));
|
|
1003
|
-
const handoff = status2 === "draft" ? `${id} is a draft: visitors do not see it and nothing is recorded until it is started. Tell the user and ask whether to start it now (npx splithub start ${id}).` :
|
|
1004
|
-
|
|
1005
|
+
const handoff = status2 === "draft" ? `${id} is a draft: visitors do not see it and nothing is recorded until it is started. Tell the user and ask whether to start it now (npx splithub start ${id}).` : `${id} is running in the config: it goes live for visitors when this code is deployed${cloudMode ? " and pushed; local development never sends events to the cloud" : ""}. Tell the user, and that npx splithub pause ${id} or Pause in the dashboard holds it.`;
|
|
1006
|
+
const nextStep = cloudMode ? `npx splithub push # the cloud does not know about ${id} until you push` : status2 === "draft" ? `npx splithub start ${id}` : "deploy the app";
|
|
1007
|
+
console.log(JSON.stringify({ ...result, nextStep, handoff }, null, 2));
|
|
1005
1008
|
return;
|
|
1006
1009
|
}
|
|
1007
1010
|
p.note(snippet, kind === "redirect" ? "Nothing to wire" : "Wire it in your code");
|
|
@@ -1009,6 +1012,7 @@ ${variantKeys.map((k2) => ` <Variant name="${k2}"><${componentNames[k2]} /></Va
|
|
|
1009
1012
|
const cloud = /mode\s*:\s*['"]cloud['"]/.test(readSource(project.configFile));
|
|
1010
1013
|
if (cloud) p.log.warn(`Cloud mode: the cloud does not know about it until you run ${c.cyan("npx splithub push")}.`);
|
|
1011
1014
|
if (status2 === "draft") p.log.warn(`${c.bold(id)} is a draft: visitors do not see it and nothing is recorded until you start it.`);
|
|
1015
|
+
if (status2 === "running") p.log.info(`${c.bold(id)} goes live when you deploy this code. Check it first with ${c.cyan(`?sh_force=${id}:<variant>`)}; ${c.cyan(`npx splithub pause ${id}`)} holds it.`);
|
|
1012
1016
|
if (status2 === "draft") p.log.info(`See it before you start it: ${c.cyan("runDraftsInDev: true")} in the config serves drafts in development, ${c.cyan(`?sh_force=${id}:<variant>`)} shows one variant anywhere.`);
|
|
1013
1017
|
p.outro(`Added ${c.bold(id)} (${status2}) to ${relative(project.root, project.configFile)}. ${status2 === "running" ? "" : `Start it with ${c.cyan(`npx splithub start ${id}`)}. `}${cloud ? `Then ${c.cyan("npx splithub push")}.` : ""}`);
|
|
1014
1018
|
}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/commands/create.ts","../src/config-file.ts","../src/project.ts","../src/skills-self-hosted.ts","../src/skills-ship.ts","../src/skills.ts","../src/templates.ts","../src/ui.ts","../src/commands/dev.ts","../src/api.ts","../src/credentials.ts","../src/commands/doctor.ts","../src/commands/init.ts","../src/commands/login.ts","../src/templates-store.ts","../src/commands/skills.ts","../src/commands/lifecycle.ts","../src/commands/menu.ts","../src/commands/push.ts","../src/commands/results.ts","../src/commands/status.ts","../src/commands/review.ts"],"sourcesContent":["import { parseArgs } from 'node:util';\nimport { create } from './commands/create';\nimport { dev } from './commands/dev';\nimport { doctor } from './commands/doctor';\nimport { init } from './commands/init';\nimport { lifecycle } from './commands/lifecycle';\nimport { login, logout, projects, whoami } from './commands/login';\nimport { menu } from './commands/menu';\nimport { skills } from './commands/skills';\nimport { pull, push } from './commands/push';\nimport { results } from './commands/results';\nimport { review } from './commands/review';\nimport { status } from './commands/status';\nimport { c } from './ui';\n\nconst HELP = `\n${c.bold('splithub')} — A/B testing for agent-built apps\n\nUsage\n splithub interactive menu: set up, create, results, start/pause, push — step by step\n splithub init set up config, framework files, agent docs\n splithub create add an experiment (wizard, or flags for agents)\n splithub start|pause|finish <id>\n splithub status all experiments with a verdict headline\n splithub results <id> full verdict for one experiment\n splithub review [<id>] AI reviews stored in the cloud (Pro: at start, on verdict changes, on finish, or on demand)\n splithub dev [--url] [--hold] open the app with ?sh_debug=1 (console + panel: variants, reasons, events) and watch results\n splithub doctor check the installation\n splithub skills [--mcp] install / refresh agent skills (library, A/B testing, API, MCP, self-hosting, ship the winner); --mcp registers the MCP server\n splithub login [--project <name|id>] connect this directory to a SplitHub Cloud project (sign-in link, no secrets typed)\n splithub projects every directory connected on this machine and its project; --json for agents\n splithub whoami the project this directory is connected to\n splithub logout disconnect this directory\n splithub push upload splithub.config.ts to SplitHub Cloud\n splithub pull show the config stored in the cloud\n\ncreate flags\n --kind value|component|redirect --id <key> --variants control,b --weights 50,50\n --goal <goal> --value k=text (repeatable) --match /path --to k=/url (repeatable)\n --status draft|running --description \"...\" --traffic 50 (percent) --max-visitors 10000 --start/--end <ISO date> --yes\n\ninit flags\n --mode self|cloud --db sqlite|postgres|mysql|custom (self mode) --key pk_... --no-install --no-login --no-mcp --yes\n (cloud mode without a saved login prints a link; approve it in the browser and init continues)\n\nGlobal\n --url <url> results endpoint (default: $SPLITHUB_URL, the cloud API in cloud mode, else the local dev server)\n --token <token> admin token (self: $SPLITHUB_ADMIN_TOKEN) or project API key (cloud: $SPLITHUB_API_KEY, else the key saved by \"splithub login\")\n --api <url> cloud API base (default: https://go.splithub.io/v1 or $SPLITHUB_API)\n --json machine-readable output (for agents)\n -h, --help\n`;\n\nasync function main(): Promise<void> {\n const { values, positionals } = parseArgs({\n allowPositionals: true,\n options: {\n url: { type: 'string' },\n api: { type: 'string' },\n token: { type: 'string' },\n json: { type: 'boolean', default: false },\n yes: { type: 'boolean', short: 'y', default: false },\n help: { type: 'boolean', short: 'h', default: false },\n mode: { type: 'string' },\n db: { type: 'string' },\n key: { type: 'string' },\n 'no-install': { type: 'boolean', default: false },\n 'no-login': { type: 'boolean', default: false },\n 'no-mcp': { type: 'boolean', default: false },\n mcp: { type: 'boolean', default: false },\n force: { type: 'boolean', default: false },\n kind: { type: 'string' },\n id: { type: 'string' },\n variants: { type: 'string' },\n weights: { type: 'string' },\n goal: { type: 'string' },\n value: { type: 'string', multiple: true },\n match: { type: 'string' },\n to: { type: 'string', multiple: true },\n factor: { type: 'string', multiple: true },\n status: { type: 'string' },\n description: { type: 'string' },\n traffic: { type: 'string' },\n 'max-visitors': { type: 'string' },\n start: { type: 'string' },\n end: { type: 'string' },\n project: { type: 'string' },\n },\n });\n const [command, arg] = positionals;\n if (values.help) {\n console.log(HELP.trimEnd());\n return;\n }\n if (!command) {\n // A terminal → the interactive menu; a pipe or an agent → the help text.\n if (process.stdin.isTTY && process.stdout.isTTY && !values.json) return menu(values);\n console.log(HELP.trimEnd());\n return;\n }\n switch (command) {\n case 'init':\n return init(values);\n case 'create':\n return create(values);\n case 'start':\n case 'pause':\n case 'finish':\n return lifecycle(command, arg, values);\n case 'status':\n return status(values);\n case 'results':\n return results(arg, values);\n case 'review':\n return review(arg, values);\n case 'dev':\n return dev(values);\n case 'doctor':\n return doctor(values);\n case 'skills':\n return skills(values);\n case 'push':\n return push(values);\n case 'pull':\n return pull(values);\n case 'login':\n return login(values);\n case 'logout':\n return logout(values);\n case 'whoami':\n return whoami(values);\n case 'projects':\n return projects(values);\n default:\n throw new Error(`unknown command \"${command}\"\\n${HELP}`);\n }\n}\n\nmain().catch((error: unknown) => {\n console.error(c.red(`error: ${error instanceof Error ? error.message : String(error)}`));\n process.exit(1);\n});\n","import * as p from '@clack/prompts';\nimport { mvtVariants, type ExperimentKind, type ExperimentStatus } from '@splithub/core';\nimport { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport { hasExperiment, insertExperiment, loadConfig, readSource, writeSource, type NewExperiment } from '../config-file';\nimport { detectProject } from '../project';\nimport { componentVariantTemplate } from '../templates';\nimport { c } from '../ui';\nimport type { Flags } from './init';\n\nconst KEY = /^[a-z0-9][a-z0-9_-]{0,63}$/;\n\nfunction str(v: unknown): string | undefined {\n return typeof v === 'string' && v.length > 0 ? v : undefined;\n}\nfunction list(v: unknown): string[] {\n if (Array.isArray(v)) return v.map(String);\n if (typeof v === 'string') return [v];\n return [];\n}\nfunction parsePairs(items: string[]): Record<string, string> {\n const out: Record<string, string> = {};\n for (const item of items) {\n const i = item.indexOf('=');\n if (i > 0) out[item.slice(0, i).trim()] = item.slice(i + 1);\n }\n return out;\n}\nfunction pascal(s: string): string {\n return s.replace(/(^|[-_])([a-z0-9])/g, (_, __, ch: string) => ch.toUpperCase());\n}\n\nasync function ask<T>(promise: Promise<T | symbol>): Promise<T> {\n const v = await promise;\n if (p.isCancel(v)) {\n p.cancel('Cancelled.');\n process.exit(0);\n }\n return v as T;\n}\n\nexport async function create(flags: Flags): Promise<void> {\n const json = Boolean(flags.json);\n const yes = Boolean(flags.yes);\n const project = detectProject();\n if (!project.configFile) throw new Error('splithub.config.ts not found. Run `npx splithub init` first.');\n const config = await loadConfig(project.configFile);\n const source = readSource(project.configFile);\n const interactive = !yes && !json;\n\n if (interactive) p.intro(c.bold('splithub create'));\n\n let kind = str(flags.kind) as ExperimentKind | undefined;\n if (!kind) {\n if (!interactive) throw new Error('--kind value|component|redirect|mvt is required with --yes');\n kind = await ask(\n p.select<ExperimentKind>({\n message: 'What changes between variants?',\n options: [\n { value: 'value', label: 'Text, image URL, number', hint: 'no new components' },\n { value: 'component', label: 'Layout / structure', hint: 'one component per variant' },\n { value: 'redirect', label: 'A whole page', hint: 'needs @splithub/next middleware' },\n { value: 'mvt', label: 'Several things at once', hint: 'multivariate: every combination, each factor read on its own' },\n ],\n })\n );\n }\n\n let id = str(flags.id);\n if (!id) {\n if (!interactive) throw new Error('--id is required with --yes');\n id = await ask(\n p.text({\n message: 'Experiment id',\n placeholder: 'hero-title',\n validate: (v) => (!KEY.test(v) ? 'lowercase a-z 0-9 - _ only' : hasExperiment(source, v) ? 'already exists' : undefined),\n })\n );\n }\n if (!KEY.test(id)) throw new Error(`invalid id \"${id}\" (lowercase a-z 0-9 - _, max 64)`);\n if (hasExperiment(source, id)) throw new Error(`experiment \"${id}\" already exists`);\n\n // Multivariate: --factor headline=old:Old,new:New (repeatable); the variants are the combinations.\n const factors: Record<string, Record<string, string>> = {};\n if (kind === 'mvt') {\n for (const raw of list(flags.factor)) {\n const eq = raw.indexOf('=');\n if (eq <= 0) throw new Error(`--factor expects name=level:value,level:value, got \"${raw}\"`);\n const name = raw.slice(0, eq).trim();\n const levels: Record<string, string> = {};\n for (const part of raw.slice(eq + 1).split(',')) {\n const colon = part.indexOf(':');\n const level = (colon >= 0 ? part.slice(0, colon) : part).trim();\n if (!level) continue;\n levels[level] = colon >= 0 ? part.slice(colon + 1).trim() : level;\n }\n factors[name] = levels;\n }\n while (interactive && Object.keys(factors).length === 0) {\n const name = await ask(p.text({ message: 'Factor name (what changes), e.g. headline', validate: (v) => (!KEY.test(v) ? 'lowercase a-z 0-9 - _ only' : undefined) }));\n const levelsRaw = await ask(p.text({ message: `Levels of \"${name}\" as key:value, comma separated (first = control)`, placeholder: 'old:Old headline, new:New headline' }));\n const levels: Record<string, string> = {};\n for (const part of levelsRaw.split(',')) {\n const colon = part.indexOf(':');\n const level = (colon >= 0 ? part.slice(0, colon) : part).trim();\n if (level) levels[level] = colon >= 0 ? part.slice(colon + 1).trim() : level;\n }\n factors[name] = levels;\n while (await ask(p.confirm({ message: 'Add another factor?', initialValue: false }))) {\n const more = await ask(p.text({ message: 'Factor name', validate: (v) => (!KEY.test(v) ? 'lowercase a-z 0-9 - _ only' : undefined) }));\n const moreRaw = await ask(p.text({ message: `Levels of \"${more}\" as key:value, comma separated`, placeholder: 'blue:#2563eb, green:#16a34a' }));\n const moreLevels: Record<string, string> = {};\n for (const part of moreRaw.split(',')) {\n const colon = part.indexOf(':');\n const level = (colon >= 0 ? part.slice(0, colon) : part).trim();\n if (level) moreLevels[level] = colon >= 0 ? part.slice(colon + 1).trim() : level;\n }\n factors[more] = moreLevels;\n }\n }\n if (Object.keys(factors).length === 0) throw new Error('--factor name=level:value,level:value is required for mvt experiments (repeat it per factor)');\n }\n const mvt = kind === 'mvt' ? mvtVariants(id, factors) : null;\n\n let variantKeys = mvt ? mvt.variants.map((v) => v.key) : str(flags.variants)?.split(',').map((s) => s.trim()).filter(Boolean);\n if (!variantKeys || variantKeys.length < 2) {\n if (!interactive) variantKeys = ['control', 'b'];\n else {\n const v = await ask(p.text({ message: 'Variant keys, comma separated (first = control)', initialValue: 'control, b' }));\n variantKeys = v.split(',').map((s) => s.trim()).filter(Boolean);\n }\n }\n for (const k of variantKeys) if (!KEY.test(k)) throw new Error(`invalid variant key \"${k}\"`);\n if (variantKeys.length < 2) throw new Error('need at least 2 variants');\n\n const weightsRaw = str(flags.weights)?.split(',').map(Number);\n const weights = weightsRaw && weightsRaw.length === variantKeys.length && weightsRaw.every((w) => Number.isFinite(w) && w >= 0) ? weightsRaw : variantKeys.map(() => 1);\n\n const values = parsePairs(list(flags.value));\n const tos = parsePairs(list(flags.to));\n if (kind === 'value' && interactive) {\n for (const k of variantKeys) {\n if (values[k] === undefined) values[k] = await ask(p.text({ message: `Value for \"${k}\"`, placeholder: k === variantKeys[0] ? 'current text' : 'new text' }));\n }\n }\n let match = str(flags.match);\n if (kind === 'redirect') {\n if (!match) {\n if (!interactive) throw new Error('--match /path is required for redirect experiments');\n match = await ask(p.text({ message: 'Path to run the redirect test on', initialValue: '/' }));\n }\n for (const k of variantKeys) {\n if (tos[k] === undefined) {\n if (!interactive) tos[k] = k === variantKeys[0] ? match : `${match.replace(/\\/$/, '')}/${k}`;\n else tos[k] = await ask(p.text({ message: `URL for \"${k}\"`, initialValue: k === variantKeys[0] ? match : '' }));\n }\n }\n }\n\n let goal = str(flags.goal);\n const goals = config.goals.map((g) => g.key);\n if (!goal) {\n if (!interactive) goal = goals[0];\n else if (goals.length > 0) {\n goal = await ask(\n p.select<string>({\n message: 'Goal (conversion) to optimise',\n options: [...goals.map((g) => ({ value: g, label: g })), { value: '', label: 'none yet (add later)' }],\n })\n );\n if (!goal) goal = undefined;\n }\n }\n if (goal && !goals.includes(goal)) throw new Error(`goal \"${goal}\" is not declared in splithub.config.ts goals: ${goals.join(', ') || 'none'}`);\n\n const status = (str(flags.status) as ExperimentStatus | undefined) ?? 'draft';\n const description = str(flags.description);\n\n const experiment: NewExperiment = {\n key: id,\n kind,\n status,\n goal,\n match,\n description,\n variants: mvt ? mvt.variants.map((v) => ({ key: v.key, weight: v.weight })) : variantKeys.map((k, i) => ({ key: k, weight: weights[i]!, value: values[k], to: tos[k] })),\n ...(mvt ? { factors } : {}),\n // limits: --traffic 50 (percent), --max-visitors 10000, --start / --end ISO dates\n traffic: typeof flags.traffic === 'string' && flags.traffic !== '' ? Math.min(1, Math.max(0, Number(flags.traffic) / 100)) : undefined,\n maxExposures: typeof flags['max-visitors'] === 'string' && Number(flags['max-visitors']) > 0 ? Math.floor(Number(flags['max-visitors'])) : undefined,\n schedule: typeof flags.start === 'string' || typeof flags.end === 'string' ? { startAt: typeof flags.start === 'string' ? flags.start : null, endAt: typeof flags.end === 'string' ? flags.end : null } : undefined,\n };\n\n writeSource(project.configFile, insertExperiment(source, experiment));\n\n const files: string[] = [];\n const componentNames: Record<string, string> = {};\n if (kind === 'component') {\n const dir = join(project.root, project.hasSrc ? 'src/splithub' : 'splithub', id);\n mkdirSync(dir, { recursive: true });\n for (const k of variantKeys) {\n const name = `${pascal(id)}${pascal(k)}`;\n componentNames[k] = name;\n const file = join(dir, `${pascal(k)}.tsx`);\n if (!existsSync(file)) {\n writeFileSync(file, componentVariantTemplate(name, id, k), 'utf8');\n files.push(relative(project.root, file));\n }\n }\n }\n\n const snippet =\n kind === 'mvt'\n ? `const { ${Object.keys(factors).join(', ')} } = useValue<{ ${Object.keys(factors).map((f) => `${f}: string`).join('; ')} }>('${id}');`\n : kind === 'value'\n ? `const value = useValue<string>('${id}');`\n : kind === 'component'\n ? `<Experiment id=\"${id}\">\\n${variantKeys.map((k) => ` <Variant name=\"${k}\"><${componentNames[k]} /></Variant>`).join('\\n')}\\n</Experiment>`\n : `// handled by @splithub/next middleware on ${match}; no code needed`;\n\n const result = { experiment: id, kind, status, variants: experiment.variants, goal: goal ?? null, configFile: relative(project.root, project.configFile), files, snippet };\n if (json) {\n const cloudMode = /mode\\s*:\\s*['\"]cloud['\"]/.test(readSource(project.configFile));\n // Agents read this JSON: the hand-off line makes sure the human learns the test is not live yet.\n const handoff = status === 'draft' ? `${id} is a draft: visitors do not see it and nothing is recorded until it is started. Tell the user and ask whether to start it now (npx splithub start ${id}).` : undefined;\n console.log(JSON.stringify({ ...result, nextStep: cloudMode ? `npx splithub push # the cloud does not know about ${id} until you push` : `npx splithub start ${id}`, ...(handoff ? { handoff } : {}) }, null, 2));\n return;\n }\n p.note(snippet, kind === 'redirect' ? 'Nothing to wire' : 'Wire it in your code');\n if (files.length) p.note(files.join('\\n'), 'Scaffolded');\n const cloud = /mode\\s*:\\s*['\"]cloud['\"]/.test(readSource(project.configFile));\n if (cloud) p.log.warn(`Cloud mode: the cloud does not know about it until you run ${c.cyan('npx splithub push')}.`);\n if (status === 'draft') p.log.warn(`${c.bold(id)} is a draft: visitors do not see it and nothing is recorded until you start it.`);\n if (status === 'draft') p.log.info(`See it before you start it: ${c.cyan('runDraftsInDev: true')} in the config serves drafts in development, ${c.cyan(`?sh_force=${id}:<variant>`)} shows one variant anywhere.`);\n p.outro(`Added ${c.bold(id)} (${status}) to ${relative(project.root, project.configFile)}. ${status === 'running' ? '' : `Start it with ${c.cyan(`npx splithub start ${id}`)}. `}${cloud ? `Then ${c.cyan('npx splithub push')}.` : ''}`);\n}\n","import { isSplitHubConfig, type ExperimentKind, type ExperimentStatus, type SplitHubConfig } from '@splithub/core';\nimport { readFileSync, writeFileSync } from 'node:fs';\nimport { pathToFileURL } from 'node:url';\n\n/** Load splithub.config.ts (TypeScript or JS) through jiti. */\nexport async function loadConfig(file: string): Promise<SplitHubConfig> {\n const { createJiti } = await import('jiti');\n const jiti = createJiti(pathToFileURL(file).href, { fsCache: false, moduleCache: false });\n const mod = (await jiti.import(file, { default: true })) as unknown;\n if (!isSplitHubConfig(mod)) {\n throw new Error(`${file} must \\`export default defineConfig({...})\\` from @splithub/core.`);\n }\n return mod;\n}\n\nfunction keyPattern(key: string): RegExp {\n const esc = key.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp(`(^|\\\\n)([ \\\\t]*)(['\"]?)${esc}\\\\3[ \\\\t]*:[ \\\\t]*\\\\{`);\n}\n\n/** Index of the `}` closing the object that opens at `open`. Skips strings and `//` comments. */\nfunction findObjectEnd(source: string, open: number): number | null {\n let depth = 0;\n let inStr: string | null = null;\n let inLineComment = false;\n for (let i = open; i < source.length; i++) {\n const ch = source[i]!;\n if (inLineComment) {\n if (ch === '\\n') inLineComment = false;\n continue;\n }\n if (inStr) {\n if (ch === '\\\\') i++;\n else if (ch === inStr) inStr = null;\n continue;\n }\n if (ch === '/' && source[i + 1] === '/') {\n inLineComment = true;\n continue;\n }\n if (ch === \"'\" || ch === '\"' || ch === '`') inStr = ch;\n else if (ch === '{') depth++;\n else if (ch === '}') {\n depth--;\n if (depth === 0) return i;\n }\n }\n return null;\n}\n\n/** Find the `{ ... }` body of an experiment entry. Returns [openIndex, closeIndex]. */\nfunction findExperimentBlock(source: string, key: string): [number, number] | null {\n const expIdx = source.search(/experiments\\s*:\\s*\\{/);\n if (expIdx < 0) return null;\n const m = keyPattern(key).exec(source.slice(expIdx));\n if (!m) return null;\n const open = expIdx + m.index + m[0].length - 1;\n const close = findObjectEnd(source, open);\n return close === null ? null : [open, close];\n}\n\nexport function hasExperiment(source: string, key: string): boolean {\n return findExperimentBlock(source, key) !== null;\n}\n\nexport interface NewExperiment {\n key: string;\n kind: ExperimentKind;\n status: ExperimentStatus;\n variants: Array<{ key: string; weight: number; value?: string; to?: string }>;\n /** Multivariate: factor → level → value; the variants are derived and not written. */\n factors?: Record<string, Record<string, string>>;\n goal?: string;\n match?: string;\n description?: string;\n /** Targeting graph from the dashboard, written verbatim as JSON. */\n flow?: unknown;\n traffic?: number;\n maxExposures?: number;\n schedule?: { startAt?: string | null; endAt?: string | null };\n}\n\n/** Single-quoted string literal. */\nfunction q(s: string): string {\n return `'${s.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`;\n}\n\n/** Object key: bare when it is a valid identifier, quoted otherwise. */\nfunction k(s: string): string {\n return /^[a-z_$][\\w$]*$/i.test(s) ? s : q(s);\n}\n\n/** Render an experiment entry. Every line after the first carries its own indentation. */\nexport function renderExperiment(e: NewExperiment, indent = ' '): string {\n const i2 = indent + ' ';\n const i3 = i2 + ' ';\n const lines: string[] = [`${k(e.key)}: {`];\n lines.push(`${i2}kind: ${q(e.kind)},`);\n lines.push(`${i2}status: ${q(e.status)},`);\n if (e.match) lines.push(`${i2}match: ${q(e.match)},`);\n if (e.kind === 'mvt') {\n lines.push(`${i2}factors: {`);\n for (const [factor, levels] of Object.entries(e.factors ?? {})) {\n lines.push(`${i3}${k(factor)}: { ${Object.entries(levels).map(([l, v]) => `${k(l)}: ${q(v)}`).join(', ')} },`);\n }\n lines.push(`${i2}},`);\n } else if (e.kind === 'component') {\n lines.push(`${i2}variants: { ${e.variants.map((v) => `${k(v.key)}: ${v.weight}`).join(', ')} },`);\n } else {\n lines.push(`${i2}variants: {`);\n for (const v of e.variants) {\n const extra = e.kind === 'value' ? `value: ${q(v.value ?? '')}` : `to: ${q(v.to ?? '/')}`;\n lines.push(`${i3}${k(v.key)}: { weight: ${v.weight}, ${extra} },`);\n }\n lines.push(`${i2}},`);\n }\n if (e.goal) lines.push(`${i2}goal: ${q(e.goal)},`);\n if (e.traffic !== undefined && e.traffic !== 1) lines.push(`${i2}traffic: ${e.traffic},`);\n if (e.maxExposures) lines.push(`${i2}maxExposures: ${e.maxExposures},`);\n if (e.schedule && (e.schedule.startAt || e.schedule.endAt)) lines.push(`${i2}schedule: { ${[e.schedule.startAt ? `startAt: ${q(e.schedule.startAt)}` : null, e.schedule.endAt ? `endAt: ${q(e.schedule.endAt)}` : null].filter(Boolean).join(', ')} },`);\n if (e.description) lines.push(`${i2}description: ${q(e.description)},`);\n if (e.flow) {\n const json = JSON.stringify(e.flow, null, 2).split('\\n');\n lines.push(`${i2}// targeting graph from the dashboard; edit it there or by hand\\n${i2}flow: ${json.map((l, n) => (n === 0 ? l : i2 + l)).join('\\n')},`);\n }\n lines.push(`${indent}}`);\n return lines.join('\\n');\n}\n\n/** Append a new experiment at the end of the `experiments: { ... }` object. */\nexport function insertExperiment(source: string, e: NewExperiment): string {\n const m = /experiments\\s*:\\s*\\{/.exec(source);\n if (!m) throw new Error('could not find `experiments: {` in the config file.');\n const open = m.index + m[0].length - 1;\n const close = findObjectEnd(source, open);\n if (close === null) throw new Error('unbalanced braces after `experiments: {`.');\n\n const lineStart = source.lastIndexOf('\\n', close) + 1;\n const closeIndent = /^[ \\t]*/.exec(source.slice(lineStart, close))?.[0] ?? ' ';\n const indent = closeIndent + ' ';\n\n // Does the previous entry end with a comma? Ignore whitespace and // comments.\n const before = source\n .slice(open + 1, lineStart)\n .replace(/\\/\\/[^\\n]*/g, '')\n .trimEnd();\n const needsComma = before.length > 0 && !before.endsWith(',');\n\n const block = `${indent}${renderExperiment(e, indent)},\\n`;\n const head = source.slice(0, lineStart);\n return `${needsComma ? addTrailingComma(head) : head}${block}${source.slice(lineStart)}`;\n}\n\n/** Append a comma to the last code line of `head`, skipping blank and `//` comment lines. */\nfunction addTrailingComma(head: string): string {\n const lines = head.split('\\n');\n for (let i = lines.length - 1; i >= 0; i--) {\n const line = lines[i]!;\n const trimmed = line.trim();\n if (trimmed === '' || trimmed.startsWith('//')) continue;\n const commentAt = line.indexOf('//');\n const code = commentAt >= 0 ? line.slice(0, commentAt) : line;\n const rest = commentAt >= 0 ? line.slice(commentAt) : '';\n const codeTrimmed = code.trimEnd();\n lines[i] = `${codeTrimmed},${code.slice(codeTrimmed.length)}${rest}`;\n break;\n }\n return lines.join('\\n');\n}\n\nexport function setExperimentStatus(source: string, key: string, status: ExperimentStatus): string {\n const block = findExperimentBlock(source, key);\n if (!block) throw new Error(`experiment \"${key}\" not found in the config file.`);\n const [open, close] = block;\n const body = source.slice(open, close + 1);\n const re = /(status\\s*:\\s*)(['\"])[a-z]+\\2/;\n if (!re.test(body)) throw new Error(`experiment \"${key}\" has no \\`status\\` field.`);\n const updated = body.replace(re, `$1$2${status}$2`);\n return source.slice(0, open) + updated + source.slice(close + 1);\n}\n\nexport function readSource(file: string): string {\n return readFileSync(file, 'utf8');\n}\n\nexport function writeSource(file: string, source: string): void {\n writeFileSync(file, source, 'utf8');\n}\n","import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\n\nexport type Framework = 'next' | 'vite' | 'unknown';\nexport type PackageManager = 'pnpm' | 'yarn' | 'bun' | 'npm';\n\nexport interface ProjectInfo {\n root: string;\n name: string;\n framework: Framework;\n packageManager: PackageManager;\n /** Next.js app directory (`app` or `src/app`), when present. */\n appDir: string | null;\n /** Whether sources live under `src/`. */\n hasSrc: boolean;\n configFile: string | null;\n typescript: boolean;\n}\n\nconst CONFIG_NAMES = ['splithub.config.ts', 'splithub.config.mts', 'splithub.config.js', 'splithub.config.mjs'];\n\nexport function findConfigFile(root: string): string | null {\n for (const name of CONFIG_NAMES) {\n const p = join(root, name);\n if (existsSync(p)) return p;\n }\n return null;\n}\n\nexport function detectProject(cwd = process.cwd()): ProjectInfo {\n const root = resolve(cwd);\n let name = 'my-app';\n let deps: Record<string, string> = {};\n try {\n const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { name?: string; dependencies?: Record<string, string>; devDependencies?: Record<string, string> };\n name = pkg.name ?? name;\n deps = { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) };\n } catch {\n // no package.json: still usable\n }\n const has = (file: string) => existsSync(join(root, file));\n const framework: Framework = deps.next || has('next.config.js') || has('next.config.mjs') || has('next.config.ts')\n ? 'next'\n : deps.vite || has('vite.config.ts') || has('vite.config.js') || has('vite.config.mjs')\n ? 'vite'\n : 'unknown';\n const packageManager: PackageManager = has('pnpm-lock.yaml') ? 'pnpm' : has('yarn.lock') ? 'yarn' : has('bun.lockb') || has('bun.lock') ? 'bun' : 'npm';\n const appDir = has('src/app') ? 'src/app' : has('app') ? 'app' : null;\n return {\n root,\n name: name.replace(/^@[^/]+\\//, ''),\n framework,\n packageManager,\n appDir,\n hasSrc: has('src'),\n configFile: findConfigFile(root),\n typescript: has('tsconfig.json'),\n };\n}\n\nexport function installCommand(pm: PackageManager, packages: string[], dev = false): string {\n const flag = dev ? (pm === 'npm' ? ' -D' : ' -D') : '';\n switch (pm) {\n case 'pnpm':\n return `pnpm add${flag} ${packages.join(' ')}`;\n case 'yarn':\n return `yarn add${flag} ${packages.join(' ')}`;\n case 'bun':\n return `bun add${dev ? ' -d' : ''} ${packages.join(' ')}`;\n default:\n return `npm install${flag} ${packages.join(' ')}`;\n }\n}\n\nconst SKIP_DIRS = new Set(['node_modules', '.next', 'dist', 'build', '.git', 'coverage', 'out', '.turbo']);\nconst CODE_EXT = /\\.(tsx?|jsx?|mjs|cjs|mts|cts)$/;\n\n/** Source files of the project (shallow enough for a doctor run). */\nexport function listSourceFiles(root: string, maxFiles = 5000): string[] {\n const out: string[] = [];\n const walk = (dir: string, depth: number) => {\n if (out.length >= maxFiles || depth > 8) return;\n let entries: string[];\n try {\n entries = readdirSync(dir);\n } catch {\n return;\n }\n for (const entry of entries) {\n if (SKIP_DIRS.has(entry)) continue;\n const full = join(dir, entry);\n let st;\n try {\n st = statSync(full);\n } catch {\n continue;\n }\n if (st.isDirectory()) walk(full, depth + 1);\n else if (CODE_EXT.test(entry)) out.push(full);\n }\n };\n walk(root, 0);\n return out;\n}\n\nexport function grepFiles(files: string[], needle: string): string[] {\n const hits: string[] = [];\n for (const f of files) {\n try {\n if (readFileSync(f, 'utf8').includes(needle)) hits.push(f);\n } catch {\n // unreadable file\n }\n }\n return hits;\n}\n","// Skill: SplitHub with the user's own database (self mode) and reporting from the cloud.\nexport const SKILL_SELF_HOSTED = `---\nname: splithub-self-hosted\ndescription: Keep SplitHub 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# SplitHub 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 SplitHub 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- 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- Compute winners from raw rates in SQL; use \\`npx splithub results\\` (or \\`@splithub/stats\\`) for the verdict.\n`;\n","// Skill: ship the winner and take the experiment out of the code. Installed\n// next to the other skills by `splithub init` / `splithub skills`.\n\nexport const SKILL_SHIP = `---\nname: splithub-ship\ndescription: Ship the winner of an A/B test and remove the test 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 a test has a verdict and the user says ship it, roll out the winner, remove the test, or clean up; and whenever a test 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 winning variant did, with no experiment left in the code or in the config.\n\n## Before touching code\n\n1. Read the verdict: \\`npx splithub results <id> --json\\`. Act on \\`verdict.status\\`:\n - \\`winner_found\\`: ship \\`verdict.winner\\`.\n - \\`no_significant_difference\\` with enough sample: keep the control, or the simpler variant if the user agrees.\n - \\`insufficient_sample\\`: do not ship. Say roughly how many more visitors are needed (\\`sample.neededPerVariant\\`).\n - \\`srm_detected\\`: do not ship. The split is broken; fix the setup first.\n2. Finish the experiment first so new visitors stop entering: \\`npx splithub finish <id>\\`. Results stay readable afterwards.\n\n## Per kind\n\n- **value** (\\`useValue('<id>')\\`, \\`sh.value('<id>')\\`, \\`getValue\\`): replace every call with the winning literal (text, number, JSON).\n Remove imports that become unused.\n- **component** (\\`<Experiment id=\"<id>\">\\` with \\`<Variant>\\` children, or a \\`useVariant('<id>')\\` switch): keep the winning branch\n inline where the wrapper was, delete the other branches and the wrapper. Delete components, files and styles only the losing\n variants used.\n- **redirect** (the winner is a URL): if a new page won, make it the real page: serve the winning content at the original path\n (move the route, or add a permanent redirect from the old path), delete the losing page, update internal links and the sitemap.\n If the control won, delete the new page and its route. Remove the experiment's \\`match\\`.\n- **drop-in script sites** (no SDK): nothing to change in code; remove the test from the config or the dashboard.\n\n## Config and cloud\n\n3. Remove the experiment from \\`experiments\\` in \\`splithub.config.ts\\`. Keep the goal if another test uses it. Cloud mode:\n \\`npx splithub push\\`. Tests created in the dashboard (\"cloud\" badge): finished is enough, or delete them there.\n4. Keep \\`track('<goal>')\\` calls when the goal is still in use; remove them only if nothing else measures that goal.\n\n## Verify and report\n\n5. \\`npx splithub doctor\\`, then the project's typecheck and tests. Grep for the experiment id: nothing should reference it.\n6. Report what changed (files, the winning content) and the verdict in one line with its numbers.\n7. Never reuse the experiment id for a new test: the history belongs to the old one.\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// 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 A/B experiments in an app that uses SplitHub (@splithub/react, splithub.config.ts, the splithub CLI, SplitHub 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 a test.\n---\n\n# SplitHub 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 SplitHub 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; \\`npx splithub pull\\` writes dashboard-created experiments into the file.\n- Results: \\`npx splithub status --json\\`, \\`npx splithub results <id> --json\\`.\n- Everything interactive: \\`npx splithub\\` (menu). Everything scriptable: subcommands + \\`--json\\`.\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.splithub.io/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 an A/B test: 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, test one thing with \\`value\\`.\n\n## Create an experiment\n\n1. \\`npx splithub create --kind <value|component|redirect|mvt> --id <key> … --goal <goal> --yes --json\\` (see the table).\n2. Goal: pick an existing key or add one to \\`goals\\`:\n \\`{ type: 'event' }\\` + \\`track('<goal>')\\` where the conversion happens; \\`{ type: 'pageview', path: '/thanks' }\\`;\n \\`{ type: 'click', selector: '#buy' }\\` (tracked automatically by the SDK and the script).\n3. Wire it in code, keep \\`status: 'draft'\\` until the user confirms, then \\`npx splithub start <id>\\`.\n4. Cloud mode: \\`npx splithub push\\` after any config change.\n5. Hand-off, always: end your reply by saying the test is a **draft**: visitors do not see it and nothing is recorded\n until it is started. Then ask: \"Start it now?\" On yes run \\`npx splithub start <id>\\` (live at once in cloud mode;\n self mode needs a deploy); otherwise tell them it starts with Start in the dashboard or that command. Never let the\n user believe a draft is collecting data.\n\nA draft is invisible to visitors. To check it before starting: \\`runDraftsInDev: true\\` at the top level of the config\nserves drafts like running tests in development only (\\`NODE_ENV=development\\`: \\`next dev\\`, \\`vite\\`; nothing is billed);\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 tests 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, p-value, CI).\nNever declare a winner from raw rates. \\`srm_detected\\` means the split is broken: fix the setup before anything else.\n\n## Finish, and what to do when a test is finished\n\n\\`npx splithub finish <id>\\` stops the test (live within a minute in cloud mode). A finished test 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 a test 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 test from the code now**.\n3. On yes, follow the \\`splithub-ship\\` skill: keep only the chosen variant's content, delete the other variants' code and\n files, remove the entry from \\`splithub.config.ts\\`, \\`push\\` in cloud mode, run \\`doctor\\` and the project's checks.\n4. On no, leave everything: a finished test costs nothing and the user may come back to it.\n\nA \\`paused\\` test is not over: say so and ask whether to resume (\\`start\\`) or finish it.\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 A/B test 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 A/B test 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 a test\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, test a bigger change or a higher-traffic page.\n4. **Few tests per page.** Interactions between simultaneous tests 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 test.\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 test, 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 test.\n- The business moved on → finish; do not leave tests 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 SplitHub Cloud HTTP API directly: public key event ingest, API-key endpoints for config, status, results and overrides, hosted experiments. Use when writing a server, a script, a non-JS client, or when the CLI is not available.\n---\n\n# SplitHub Cloud API\n\nBase URL: \\`https://go.splithub.io\\`. 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.\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- \\`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. \\`403 origin_not_allowed\\` when the project restricts domains.\n- Exposures for experiments that are not running are dropped and not billed. Goals are never billed.\n\n## Live config for clients (public key)\n\n\\`GET /v1/overrides/<pk>.json\\` → \\`{ 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\nGET /v1/config the config stored in the cloud (file + dashboard experiments)\nPUT /v1/config { config } push a normalized config (what defineConfig returns); answers cloudOnly experiments to adopt\nGET /v1/overrides live overrides\nPUT /v1/overrides/<experiment> { status | traffic | weights | values } pause / resume / reweight without a deploy\nDELETE /v1/overrides/<experiment>\n\\`\\`\\`\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\\`, \\`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.splithub.io/sh.js\" data-key=\"pk_live_…\"></script>\\` in \\`<head>\\`: redirect experiments, page-visit and\nclick goals from the cloud config, \\`window.splithub.track('goal')\\` for custom events,\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, \\`404\\` unknown experiment/project, \\`409\\` state\n(e.g. \\`config_not_pushed\\`, \\`file_owned\\`), \\`429\\` gate or rate limit. Bodies: \\`{ error, code? }\\`.\n`;\n\nexport const SKILL_SPLITHUB_MCP = `---\nname: splithub-mcp\ndescription: Use or set up the SplitHub MCP server (@splithub/mcp) so an agent can create experiments, read verdicts, start/pause/finish tests and push config through tools instead of shelling out. Use when the user asks to connect SplitHub to Claude Code, Cursor, Codex or another MCP client.\n---\n\n# SplitHub 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 | report \\`verdict.message\\` verbatim |\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_create_experiment\\` | adds an experiment to splithub.config.ts | kind value / component / redirect / mvt, id, variants (or factors for mvt), goal, values/to; starts as draft |\n| \\`splithub_set_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\n## Working rules\n\n- Create → wire in code → \\`doctor\\` → \\`push\\` (cloud mode) → tell the user the test is a draft that collects nothing until started,\n and ask whether to start it now → on yes \\`set_status running\\`.\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- If a tool answers that the folder is not connected, call \\`splithub_login\\`, show the link to the user, wait for them, then retry.\n- A \\`finished\\` experiment in \\`splithub_status\\` or \\`splithub_results\\` means the test is over but its code is still there: report\n the verdict, ask which variant to keep and whether to remove the test 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_SHIP } from './skills-ship';\nimport { SKILL_SHIP } from './skills-ship';\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];\n\nexport const MCP_SERVER_ENTRY = { command: 'npx', args: ['-y', '@splithub/mcp'] };\n","export function configTemplate(project: string, mode: 'self' | 'cloud', key?: string): string {\n const storage = mode === 'self' ? `{ mode: 'self', endpoint: '/api/splithub' }` : `{ mode: 'cloud', key: ${key ? `'${key}'` : \"process.env.NEXT_PUBLIC_SPLITHUB_KEY ?? ''\"} }`;\n return `import { defineConfig } from '@splithub/core';\n\n// SplitHub 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.\nexport default defineConfig({\n project: '${project}',\n storage: ${storage},\n // Drafts behave like running tests while you develop (next dev, vite); production ignores them.\n runDraftsInDev: true,\n\n goals: {\n // call track('signup') where the conversion happens\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 (SplitHub)\n\nThis project uses SplitHub (\\`@splithub/react\\`). Experiments are declared in\n\\`splithub.config.ts\\` and rendered with \\`<Experiment id>\\` / \\`useVariant(id)\\` /\n\\`useValue(id)\\`. Conversions: \\`useTrack()\\` then \\`track('<goal>')\\`.\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 <goal> --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\\` test still has all its variants in the code: report the verdict, ask which variant to keep and whether to\n remove the test from the code, then follow .claude/skills/splithub-ship/SKILL.md. Never delete test code unasked.\n- Keep \\`status: 'draft'\\` until the user confirms. After creating a test, always tell the user it is a draft that visitors\n do not see and that records nothing, and ask whether to start it (\\`npx splithub start <id>\\`). Never change \\`seed\\` of a running experiment.\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: SplitHub A/B testing conventions\nglobs: [\"splithub.config.ts\", \"splithub/**\", \"**/*.tsx\"]\nalwaysApply: false\n---\n${SKILL_SPLITHUB.replace(/^---[\\s\\S]*?---\\n/, '')}`;\n","const enabled = process.stdout.isTTY && !process.env.NO_COLOR;\nconst wrap = (open: number, close: number) => (s: string) => (enabled ? `\\u001b[${open}m${s}\\u001b[${close}m` : s);\n\nexport const c = {\n bold: wrap(1, 22),\n dim: wrap(2, 22),\n red: wrap(31, 39),\n green: wrap(32, 39),\n yellow: wrap(33, 39),\n blue: wrap(34, 39),\n magenta: wrap(35, 39),\n cyan: wrap(36, 39),\n};\n\nexport function table(headers: string[], rows: string[][]): string {\n const widths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) => strip(r[i] ?? '').length)));\n const line = (cells: string[]) => cells.map((cell, i) => cell + ' '.repeat(widths[i]! - strip(cell).length)).join(' ');\n return [c.dim(line(headers)), ...rows.map(line)].join('\\n');\n}\n\nexport function strip(s: string): string {\n // eslint-disable-next-line no-control-regex\n return s.replace(/\\u001b\\[\\d+m/g, '');\n}\n\nexport function pct(x: number | null | undefined, signed = false): string {\n if (x === null || x === undefined || !Number.isFinite(x)) return '–';\n const v = (x * 100).toFixed(1);\n return signed && x >= 0 ? `+${v}%` : `${v}%`;\n}\n\nexport function statusColor(status: string): string {\n switch (status) {\n case 'running':\n return c.green(status);\n case 'paused':\n return c.yellow(status);\n case 'finished':\n return c.blue(status);\n default:\n return c.dim(status);\n }\n}\n\n/** One plain glyph per verdict (no emoji: terminals and CI logs render these everywhere). */\nexport function verdictIcon(status: string | null | undefined): string {\n switch (status) {\n case 'winner_found':\n return '★';\n case 'srm_detected':\n return '!';\n case 'insufficient_sample':\n return '…';\n case 'no_significant_difference':\n return '=';\n default:\n return '·';\n }\n}\n\n/** A horizontal bar: filled blocks for value / max, dim blocks for the rest. */\nexport function bar(value: number, max: number, width = 20, paint: (s: string) => string = c.green): string {\n const n = max > 0 ? Math.max(0, Math.min(width, Math.round((value / max) * width))) : 0;\n return paint('█'.repeat(n)) + c.dim('░'.repeat(width - n));\n}\n\nexport function verdictColor(status: string | null, text: string): string {\n switch (status) {\n case 'winner_found':\n return c.green(text);\n case 'srm_detected':\n return c.red(text);\n case 'insufficient_sample':\n return c.yellow(text);\n case 'no_significant_difference':\n return c.cyan(text);\n default:\n return c.dim(text);\n }\n}\n","// splithub dev — test experiments locally with full visibility.\n//\n// splithub dev opens the app (localhost:3000 for Next.js, 5173 for Vite) with ?sh_debug=1\n// splithub dev --url http://… a different page\n// splithub dev --hold redirect experiments log the target instead of navigating\n// splithub dev --no-open only print the link and watch\n//\n// With ?sh_debug the SDK and the drop-in script log every decision (which\n// variant and why), every exposure and goal with its payload, and the remote\n// overrides they applied, in the browser console and in a floating panel that\n// can force a variant, start a new visitor or hold redirects. Meanwhile this\n// command polls `status` and prints new visitors / conversions as they land.\n\nimport { spawn } from 'node:child_process';\nimport { fetchStatus, resolveTarget } from '../api';\nimport { detectProject } from '../project';\nimport { c } from '../ui';\n\nfunction openBrowser(url: string): void {\n const [cmd, args] = process.platform === 'win32' ? ['cmd', ['/c', 'start', '', url]] : process.platform === 'darwin' ? ['open', [url]] : ['xdg-open', [url]];\n try {\n spawn(cmd, args, { stdio: 'ignore', detached: true }).unref();\n } catch {\n // no browser available: the link is printed anyway\n }\n}\n\nexport async function dev(flags: Record<string, unknown>): Promise<void> {\n const project = detectProject();\n const port = project?.framework === 'next' ? 3000 : 5173;\n const page = (typeof flags.url === 'string' && flags.url) || `http://localhost:${port}/`;\n const u = new URL(page);\n u.searchParams.set('sh_debug', flags.hold ? 'hold' : '1');\n const link = u.toString();\n\n console.log(`${c.bold('SplitHub dev mode')}\\n`);\n console.log(` ${c.cyan(link)}\\n`);\n console.log(c.dim(' In the browser: the console shows every assignment (variant + reason), exposure and goal; the panel'));\n console.log(c.dim(' in the corner forces variants, starts a new visitor and can hold redirects. Add ?sh_debug=0 to stop.\\n'));\n if (!flags['no-open']) openBrowser(link);\n\n const target = resolveTarget(flags, project);\n console.log(c.dim(` Watching ${target.url} every 5 s. Ctrl+C to stop.\\n`));\n const seen = new Map<string, { visitors: number; headline: string | null }>();\n let first = true;\n const poll = async () => {\n let data: Awaited<ReturnType<typeof fetchStatus>>;\n try {\n data = await fetchStatus(target);\n } catch (e) {\n if (first) console.log(c.yellow(` results endpoint not reachable yet (${e instanceof Error ? e.message : String(e)}); is the dev server running?`));\n first = false;\n return;\n }\n const now = new Date().toLocaleTimeString();\n for (const e of data.experiments) {\n const prev = seen.get(e.experiment);\n if (!prev) console.log(` ${c.dim(now)} ${c.bold(e.experiment)} ${c.dim(e.status)} · ${e.visitors} visitors${e.headline ? ` · ${e.headline}` : ''}`);\n else if (prev.visitors !== e.visitors || prev.headline !== (e.headline ?? null)) console.log(` ${c.dim(now)} ${c.bold(e.experiment)} ${c.green(`+${e.visitors - prev.visitors}`)} → ${e.visitors} visitors${e.headline ? ` · ${e.headline}` : ''}`);\n seen.set(e.experiment, { visitors: e.visitors, headline: e.headline ?? null });\n }\n first = false;\n };\n await poll();\n await new Promise<void>((resolve) => {\n const t = setInterval(() => void poll(), 5000);\n process.on('SIGINT', () => {\n clearInterval(t);\n resolve();\n });\n });\n}\n","import type { ExperimentResults, StatusRow } from '@splithub/node';\nimport { readFileSync } from 'node:fs';\nimport { loadCredential } from './credentials';\nimport type { ProjectInfo } from './project';\n\nexport interface Target {\n url: string;\n token?: string;\n}\n\nexport const CLOUD_API = 'https://go.splithub.io/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 };\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 };\n}\n\n/**\n * Readable message from an API error body. Most routes answer `{ error: 'text' }`; the auth layer\n * answers `{ success: false, error: { code, message } }`. Without this the CLI printed \"[object Object]\".\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\nasync function get<T>(target: Target, path: string): Promise<T> {\n const headers: Record<string, string> = {};\n if (target.token) headers.authorization = `Bearer ${target.token}`;\n let res: Response;\n try {\n res = await fetch(`${target.url}${path}`, { headers });\n } catch (error) {\n throw new Error(`cannot reach ${target.url}: ${error instanceof Error ? error.message : String(error)}. Is your app running? Set --url or SPLITHUB_URL.`);\n }\n if (!res.ok) {\n const body: unknown = await res.json().catch(() => ({}));\n throw new Error(apiErrorMessage(res.status, body, `${target.url}${path} responded ${res.status}`));\n }\n return (await res.json()) as T;\n}\n\nexport const fetchStatus = (t: Target) => get<{ project: string; experiments: StatusRow[] }>(t, '/status');\nexport const fetchResults = (t: Target, key: string) => get<ExperimentResults>(t, `/results/${encodeURIComponent(key)}`);\n","// 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 { existsSync, readFileSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport { resolveTarget } from '../api';\nimport { loadConfig } from '../config-file';\nimport { detectProject, grepFiles, listSourceFiles } from '../project';\nimport { c } from '../ui';\nimport type { Flags } from './init';\n\ntype Level = 'ok' | 'warn' | 'error';\ninterface Check {\n level: Level;\n message: string;\n}\n\nexport async function doctor(flags: Flags): Promise<void> {\n const checks: Check[] = [];\n const add = (level: Level, message: string) => checks.push({ level, message });\n const project = detectProject();\n\n add('ok', `project \"${project.name}\" · ${project.framework} · ${project.packageManager}`);\n\n if (!project.configFile) {\n add('error', 'splithub.config.ts not found. Run `npx splithub init`.');\n return report(checks, flags);\n }\n add('ok', `config: ${relative(project.root, project.configFile)}`);\n\n let config;\n try {\n config = await loadConfig(project.configFile);\n add('ok', `config loads · ${config.experiments.length} experiment(s) · storage ${config.storage.mode}`);\n } catch (error) {\n add('error', `config does not load: ${error instanceof Error ? error.message : String(error)}`);\n return report(checks, flags);\n }\n\n const files = listSourceFiles(project.root);\n const providerHits = grepFiles(files, 'SplitHubProvider').concat(grepFiles(files, 'SplitHubNextProvider'));\n if (providerHits.length === 0) add('error', 'no <SplitHubProvider> found in source. Wrap your app once.');\n else add('ok', `provider in ${relative(project.root, providerHits[0]!)}`);\n\n if (project.framework === 'next') {\n const mw = ['middleware.ts', 'src/middleware.ts', 'middleware.js', 'src/middleware.js'].map((f) => join(project.root, f)).find((f) => existsSync(f));\n const hasRedirects = config.experiments.some((e) => e.kind === 'redirect');\n if (!mw) add(hasRedirects ? 'error' : 'warn', 'no middleware.ts: visitor cookie is not set on the server (SSR may flicker)' + (hasRedirects ? '; redirect experiments will not run' : ''));\n else if (!readFileSync(mw, 'utf8').includes('splithubMiddleware')) add('warn', `${relative(project.root, mw)} does not call splithubMiddleware()`);\n else add('ok', `middleware: ${relative(project.root, mw)}`);\n if (config.storage.mode === 'self' && project.appDir) {\n const catchAll = join(project.root, project.appDir, 'api/splithub/[[...path]]/route.ts');\n const plain = join(project.root, project.appDir, 'api/splithub/route.ts');\n if (existsSync(catchAll)) add('ok', `ingest route: ${relative(project.root, catchAll)}`);\n else if (existsSync(plain)) add('error', `${relative(project.root, plain)} only serves POST /api/splithub; move it to api/splithub/[[...path]]/route.ts so /status and /results work`);\n else add('error', `self mode but ${relative(project.root, catchAll)} is missing (ingest endpoint)`);\n }\n }\n\n for (const exp of config.experiments) {\n const label = `${exp.key} (${exp.kind}, ${exp.status})`;\n if (!exp.goal) add(exp.status === 'running' ? 'error' : 'warn', `${label}: no goal; the verdict cannot be computed`);\n if (exp.kind !== 'redirect') {\n const used = grepFiles(files.filter((f) => !f.endsWith('splithub.config.ts')), `'${exp.key}'`).length + grepFiles(files, `\"${exp.key}\"`).length;\n if (used === 0) add(exp.status === 'running' ? 'error' : 'warn', `${label}: not referenced in code (useValue/useVariant/<Experiment id>)`);\n }\n if (exp.status === 'running' && exp.variants.every((v) => v.weight === 0)) add('error', `${label}: all weights are 0`);\n }\n for (const goal of config.goals) {\n if (goal.type === 'event' && grepFiles(files, `'${goal.key}'`).length + grepFiles(files, `\"${goal.key}\"`).length === 0) {\n add('warn', `goal \"${goal.key}\": track('${goal.key}') is never called`);\n }\n }\n\n const target = resolveTarget(flags, project);\n try {\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), 2500);\n const res = await fetch(`${target.url}/health`, { signal: ctrl.signal });\n clearTimeout(t);\n add(res.ok ? 'ok' : 'warn', `endpoint ${target.url}/health → ${res.status}`);\n } catch {\n add('warn', `endpoint ${target.url} not reachable (is the dev server running?)`);\n }\n\n return report(checks, flags);\n}\n\nfunction report(checks: Check[], flags: Flags): void {\n const errors = checks.filter((x) => x.level === 'error').length;\n if (flags.json) {\n console.log(JSON.stringify({ ok: errors === 0, checks }, null, 2));\n } else {\n for (const x of checks) {\n const icon = x.level === 'ok' ? c.green('✔') : x.level === 'warn' ? c.yellow('!') : c.red('✖');\n console.log(`${icon} ${x.message}`);\n }\n console.log();\n console.log(errors === 0 ? c.green('All good.') : c.red(`${errors} problem(s) to fix.`));\n }\n if (errors > 0) process.exitCode = 1;\n}\n","import * as p from '@clack/prompts';\nimport { execSync } from 'node:child_process';\nimport { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, join, relative } from 'node:path';\nimport { cloudTarget } from '../api';\nimport { loadCredential } from '../credentials';\nimport { detectProject, installCommand } from '../project';\nimport { deviceLogin } from './login';\nimport { configTemplate, nextMiddlewareTemplate, nextRouteTemplate } from '../templates';\nimport { DB_KINDS, runtimePackages, storeTemplate, storeUsage, type DbKind } from '../templates-store';\nimport { installSkills } from './skills';\nimport { c } from '../ui';\n\nexport type Flags = Record<string, string | boolean | string[] | undefined>;\n\nfunction str(v: unknown): string | undefined {\n return typeof v === 'string' ? v : undefined;\n}\n\nfunction writeIfMissing(file: string, content: string, created: string[], skipped: string[]): void {\n if (existsSync(file)) {\n skipped.push(file);\n return;\n }\n mkdirSync(dirname(file), { recursive: true });\n writeFileSync(file, content, 'utf8');\n created.push(file);\n}\n\nfunction importPath(fromFile: string, toFile: string): string {\n let rel = relative(dirname(fromFile), toFile).replace(/\\\\/g, '/').replace(/\\.(ts|mts|js|mjs)$/, '');\n if (!rel.startsWith('.')) rel = `./${rel}`;\n return rel;\n}\n\n// Vite apps run the SDK in the browser; this plugin prints what each experiment does in the dev server's terminal.\nconst VITE_PLUGIN_HINT = `// vite.config.ts\nimport { splithub } from '@splithub/core/vite';\n\nexport default defineConfig({ plugins: [react(), splithub()] });`;\n\nexport async function init(flags: Flags): Promise<void> {\n const yes = Boolean(flags.yes);\n const json = Boolean(flags.json);\n const project = detectProject();\n const created: string[] = [];\n const skipped: string[] = [];\n\n if (!json) p.intro(c.bold('splithub init'));\n\n let mode = str(flags.mode) as 'self' | 'cloud' | undefined;\n if (!mode) {\n if (yes) mode = 'self';\n else {\n const picked = await p.select({\n message: 'Where should events be stored?',\n options: [\n { value: 'self', label: 'My own database (self-hosted)', hint: 'free forever, nothing leaves your infra' },\n { value: 'cloud', label: 'SplitHub Cloud', hint: 'hosted dashboard, no server code' },\n ],\n });\n if (p.isCancel(picked)) return cancel();\n mode = picked as 'self' | 'cloud';\n }\n }\n\n // Cloud: connect this directory to a project. A saved login or SPLITHUB_API_KEY\n // is enough; otherwise run the device flow — print a link, the human signs in\n // and picks (or creates) the project, the CLI gets the keys. Works when an\n // agent runs init: it relays the link, the user clicks it.\n // Self mode: which database keeps the events. sqlite needs nothing; postgres / mysql\n // get a ready Store in splithub/store.ts; custom gets a documented stub.\n let db: DbKind = (DB_KINDS as string[]).includes(str(flags.db) ?? '') ? (str(flags.db) as DbKind) : 'sqlite';\n if (mode === 'self' && !flags.db && !yes) {\n const picked = await p.select({\n message: 'Where should events be stored?',\n options: [\n { value: 'sqlite', label: 'SQLite file (zero setup)', hint: './splithub.db via node:sqlite' },\n { value: 'postgres', label: 'Postgres', hint: 'pg + DATABASE_URL, table splithub_events' },\n { value: 'mysql', label: 'MySQL / MariaDB / PlanetScale', hint: 'mysql2 + DATABASE_URL' },\n { value: 'custom', label: 'My own store (Prisma, Drizzle, Supabase, Mongo…)', hint: 'a stub with the three methods to fill in' },\n ],\n });\n if (p.isCancel(picked)) return cancel();\n db = picked as DbKind;\n }\n\n let key = str(flags.key);\n let connected: { projectName: string | null; projectId: string | null } | null = null;\n if (mode === 'cloud') {\n const api = cloudTarget(flags).url;\n const saved = loadCredential(api, project.root);\n if (saved) {\n key ??= saved.publicKey ?? undefined;\n connected = { projectName: saved.projectName, projectId: saved.projectId };\n } else if (!process.env.SPLITHUB_API_KEY && !flags['no-login']) {\n if (!json) p.log.step('Connect to SplitHub Cloud');\n try {\n const cred = await deviceLogin({\n api,\n root: project.root,\n json,\n onCode: json\n ? (s) => console.log(JSON.stringify({ step: 'approve', verifyUrl: s.verifyUrl, userCode: s.userCode, expiresIn: s.expiresIn, hint: 'Show this link to the user and wait; init continues once approved.' }))\n : (s) => p.note(`${c.cyan(s.verifyUrl)}\\n\\nCode ${c.green(s.userCode)} · sign in, pick or create the project, approve.`, 'Open this link'),\n });\n key ??= cred.publicKey ?? undefined;\n connected = { projectName: cred.projectName, projectId: cred.projectId };\n if (!json) p.log.success(`connected to ${c.cyan(cred.projectName ?? cred.projectId ?? 'project')}`);\n } catch (error) {\n if (!json) p.log.warn(`not connected: ${error instanceof Error ? error.message : String(error)}. Run ${c.cyan('npx splithub login')} later.`);\n }\n }\n // An API key in the environment (CI, agents) identifies the project: ask the cloud for its public key.\n if (!key && process.env.SPLITHUB_API_KEY) {\n try {\n const res = await fetch(`${api}/config`, { headers: { authorization: `Bearer ${process.env.SPLITHUB_API_KEY}` } });\n const body = (await res.json().catch(() => ({}))) as { publicKey?: string };\n if (typeof body.publicKey === 'string' && body.publicKey.startsWith('pk_')) {\n key = body.publicKey;\n connected ??= { projectName: null, projectId: null };\n }\n } catch {\n // offline: the first push writes the key into the config anyway\n }\n }\n if (!key && !yes) {\n const k = await p.text({ message: 'Cloud public key (pk_...), leave empty to set later via NEXT_PUBLIC_SPLITHUB_KEY', placeholder: 'pk_' });\n if (p.isCancel(k)) return cancel();\n key = k || undefined;\n }\n }\n\n // 1. config\n const configFile = project.configFile ?? join(project.root, 'splithub.config.ts');\n writeIfMissing(configFile, configTemplate(project.name, mode, key), created, skipped);\n\n // 2a. store for self mode (postgres / mysql / custom); sqlite needs no file.\n const storeBody = mode === 'self' ? storeTemplate(db) : null;\n const storeFile = storeBody ? join(project.root, 'splithub', 'store.ts') : null;\n if (storeFile && storeBody) writeIfMissing(storeFile, storeBody, created, skipped);\n\n // 2. framework files\n if (project.framework === 'next') {\n const mwFile = join(project.root, project.hasSrc ? 'src/middleware.ts' : 'middleware.ts');\n writeIfMissing(mwFile, nextMiddlewareTemplate(importPath(mwFile, configFile)), created, skipped);\n if (mode === 'self' && project.appDir) {\n const routeFile = join(project.root, project.appDir, 'api/splithub/[[...path]]/route.ts');\n writeIfMissing(routeFile, nextRouteTemplate(importPath(routeFile, configFile), storeUsage(db, storeFile ? importPath(routeFile, storeFile) : '')), created, skipped);\n }\n }\n\n // 3. agent skills (+ MCP server registration): the agent learns the library, how to test\n // well, the API and the MCP tools from .claude/skills/*; Cursor gets the rule file.\n let mcp = !flags['no-mcp'];\n if (!yes && !json && mcp) {\n const want = await p.confirm({ message: 'Register the SplitHub MCP server for Claude Code / Cursor (.mcp.json, .cursor/mcp.json)?', initialValue: true });\n if (p.isCancel(want)) return cancel();\n mcp = want;\n }\n const skillsResult = installSkills(project.root, { mcp });\n created.push(...skillsResult.written, ...skillsResult.mcp.map((f) => `${f} (MCP server)`));\n skipped.push(...skillsResult.skipped);\n\n // 4. dependencies\n const runtime = ['@splithub/react', '@splithub/core'];\n if (project.framework === 'next') runtime.push('@splithub/next');\n if (mode === 'self') runtime.push('@splithub/node', ...runtimePackages(db));\n const installRuntime = installCommand(project.packageManager, runtime);\n const installDev = installCommand(project.packageManager, ['splithub'], true);\n let installed = false;\n if (!flags['no-install']) {\n const go = yes ? true : await p.confirm({ message: `Install packages now? (${installRuntime})` });\n if (p.isCancel(go)) return cancel();\n if (go) {\n const s = json ? null : p.spinner();\n s?.start('Installing');\n try {\n execSync(installRuntime, { cwd: project.root, stdio: json ? 'ignore' : 'inherit' });\n execSync(installDev, { cwd: project.root, stdio: json ? 'ignore' : 'inherit' });\n installed = true;\n s?.stop('Installed');\n } catch (error) {\n s?.stop('Install failed; run it manually');\n if (!json) p.log.error(error instanceof Error ? error.message : String(error));\n }\n }\n }\n\n const providerHint =\n project.framework === 'next'\n ? `// ${project.appDir ?? 'app'}/layout.tsx\\nimport { SplitHubNextProvider } from '@splithub/next/client';\\nimport { getSplitHub } from '@splithub/next/server';\\nimport config from '${importPath(join(project.root, project.appDir ?? 'app', 'layout.tsx'), configFile)}';\\n\\nexport default async function RootLayout({ children }) {\\n const sh = await getSplitHub(config);\\n return <html><body><SplitHubNextProvider config={config} visitorId={sh.visitorId ?? undefined} remoteOverrides={sh.overrides}>{children}</SplitHubNextProvider></body></html>;\\n}`\n : `// main.tsx\\nimport { SplitHubProvider } from '@splithub/react';\\nimport config from './splithub.config';\\n\\n<SplitHubProvider config={config}><App /></SplitHubProvider>`;\n\n const warning = mode === 'cloud' && !key ? 'No public key yet: storage.key falls back to process.env.NEXT_PUBLIC_SPLITHUB_KEY. It is written into the config by the first `npx splithub push`, by `npx splithub login` (saved with the credentials), or pass --key pk_… (dashboard → Setup); SPLITHUB_API_KEY in the environment also resolves it.' : null;\n const summary = { project: project.name, framework: project.framework, mode, db: mode === 'self' ? db : null, connected, publicKey: key ?? null, warning, created, skipped, installed, installCommands: installed ? [] : [installRuntime, installDev], nextStep: providerHint, ...(project.framework === 'vite' ? { vitePlugin: VITE_PLUGIN_HINT } : {}) };\n\n if (json) {\n console.log(JSON.stringify(summary, null, 2));\n return;\n }\n if (warning) p.log.warn(warning);\n if (mode === 'self' && db !== 'sqlite') p.note(db === 'custom' ? 'Fill in the three methods in splithub/store.ts (the comments say what each must return).' : `Set DATABASE_URL and run the SCHEMA_SQL from splithub/store.ts once (or add it to your migrations).`, `Database: ${db}`);\n if (created.length) p.note(created.map((f) => relative(project.root, f) || f).join('\\n'), 'Created');\n if (skipped.length) p.note(skipped.map((f) => relative(project.root, f)).join('\\n'), 'Already present, left untouched');\n if (!installed) p.note(`${installRuntime}\\n${installDev}`, 'Install');\n p.note(providerHint, 'Wrap your app once');\n if (project.framework === 'vite') p.note(VITE_PLUGIN_HINT, 'Notes in your dev terminal');\n p.outro(`Next: ${c.cyan('npx splithub create')} to add your first experiment, ${c.cyan('npx splithub push')} to sync it, ${c.cyan('npx splithub doctor')} to verify.`);\n}\n\n\nfunction cancel(): void {\n p.cancel('Cancelled.');\n process.exit(0);\n}\n","// `splithub login`: device-code sign-in. The CLI prints a short code and a\n// URL; the user opens it, picks (or creates) a project and approves; the CLI\n// receives a project API key and saves it for this directory. No browser\n// automation, no secrets typed into the terminal — works over SSH and when a\n// coding agent runs it: the agent shows the link, the human clicks it.\nimport { hostname } from 'node:os';\nimport { basename } from 'node:path';\nimport { apiErrorMessage, cloudTarget } from '../api';\nimport { credentialsFile, listCredentials, loadCredential, removeCredential, saveCredential, type SavedCredential } from '../credentials';\nimport { c } from '../ui';\nimport type { Flags } from './init';\n\ninterface Start {\n deviceCode: string;\n userCode: string;\n verifyUrl: string;\n interval: number;\n expiresIn: number;\n}\ninterface Poll {\n status: 'pending' | 'approved' | 'denied' | 'expired' | 'consumed';\n apiKey?: string;\n projectId?: string | null;\n projectName?: string | null;\n publicKey?: string | null;\n}\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\nexport interface DeviceLoginOptions {\n api: string;\n root?: string;\n json?: boolean;\n /** Project name or id to preselect on the approval page. */\n project?: string;\n /** Called with the link and code as soon as they exist (default: print them). */\n onCode?: (start: { verifyUrl: string; userCode: string; expiresIn: number }) => void;\n}\n\n/** Run the device flow and save the credential. Resolves with what was saved. */\nexport async function deviceLogin(options: DeviceLoginOptions): Promise<SavedCredential> {\n const { api } = options;\n const root = options.root ?? process.cwd();\n const label = `cli · ${basename(root)} @ ${hostname()}`.slice(0, 80);\n const startRes = await fetch(`${api}/auth/device`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ label }) });\n if (!startRes.ok) throw new Error(`${api}/auth/device responded ${startRes.status}`);\n const start = (await startRes.json()) as Start;\n if (options.project) start.verifyUrl += `${start.verifyUrl.includes('?') ? '&' : '?'}project=${encodeURIComponent(options.project)}`;\n\n if (options.onCode) options.onCode(start);\n else if (options.json) console.log(JSON.stringify({ step: 'approve', userCode: start.userCode, verifyUrl: start.verifyUrl, expiresIn: start.expiresIn }));\n else {\n console.log(`\\n${c.bold('Open this link to connect:')} ${c.cyan(start.verifyUrl)}`);\n console.log(`${c.dim('Code')} ${c.green(start.userCode)} ${c.dim(`(expires in ${Math.round(start.expiresIn / 60)} min)`)}`);\n console.log(c.dim('Sign in, pick or create the project, approve. Waiting…'));\n }\n\n const deadline = Date.now() + start.expiresIn * 1000;\n while (Date.now() < deadline) {\n await sleep(Math.max(2, start.interval) * 1000);\n const res = await fetch(`${api}/auth/device/${start.deviceCode}`);\n if (!res.ok) throw new Error(`${api}/auth/device responded ${res.status}`);\n const poll = (await res.json()) as Poll;\n if (poll.status === 'pending') continue;\n if (poll.status === 'denied') throw new Error('login was denied in the dashboard');\n if (poll.status === 'expired') throw new Error('the code expired. Run `splithub login` again.');\n if (poll.status === 'consumed' || !poll.apiKey) throw new Error('the key for this code was already collected. Run `splithub login` again.');\n const cred: SavedCredential = { apiKey: poll.apiKey, projectId: poll.projectId ?? null, projectName: poll.projectName ?? null, publicKey: poll.publicKey ?? null, savedAt: new Date().toISOString() };\n saveCredential(api, root, cred);\n return cred;\n }\n throw new Error('the code expired. Run `splithub login` again.');\n}\n\nexport async function login(flags: Flags): Promise<void> {\n const api = cloudTarget({ api: flags.api }).url;\n const root = process.cwd();\n const existing = loadCredential(api, root);\n if (existing && !flags.yes) {\n const msg = `already logged in for ${c.cyan(existing.projectName ?? existing.projectId ?? 'a project')} (${credentialsFile()}). Use --yes to replace.`;\n if (flags.json) console.log(JSON.stringify({ ok: true, alreadyLoggedIn: true, projectId: existing.projectId, projectName: existing.projectName, publicKey: existing.publicKey ?? null }));\n else console.log(msg);\n return;\n }\n const cred = await deviceLogin({ api, root, json: Boolean(flags.json), ...(typeof flags.project === 'string' ? { project: flags.project } : {}) });\n if (flags.json) console.log(JSON.stringify({ ok: true, projectId: cred.projectId, projectName: cred.projectName, publicKey: cred.publicKey, credentials: credentialsFile() }));\n else {\n console.log(`${c.green('✔')} logged in to ${c.cyan(cred.projectName ?? cred.projectId ?? 'project')}`);\n console.log(c.dim(`key saved for ${root} in ${credentialsFile()}`));\n console.log(c.dim('next: npx splithub push'));\n }\n}\n\nexport async function logout(flags: Flags): Promise<void> {\n const api = cloudTarget({ api: flags.api }).url;\n const removed = removeCredential(api, process.cwd());\n if (flags.json) console.log(JSON.stringify({ ok: true, removed }));\n else console.log(removed ? `${c.green('✔')} removed the saved key for this directory` : c.dim('nothing saved for this directory'));\n}\n\nexport async function whoami(flags: Flags): Promise<void> {\n const target = cloudTarget(flags);\n if (!target.token) throw new Error('not logged in. Run `splithub login` or set SPLITHUB_API_KEY.');\n const res = await fetch(`${target.url}/status`, { headers: { authorization: `Bearer ${target.token}` } });\n const data = (await res.json().catch(() => ({}))) as { project?: string };\n if (!res.ok) throw new Error(apiErrorMessage(res.status, data, `${target.url}/status responded ${res.status}`));\n const saved = loadCredential(target.url);\n if (flags.json) console.log(JSON.stringify({ ok: true, api: target.url, project: data.project, projectId: saved?.projectId ?? null, publicKey: saved?.publicKey ?? null }));\n else console.log(`${c.bold('api')} ${target.url}\\n${c.bold('project')} ${c.cyan(data.project ?? '?')}\\n${c.bold('public key')} ${saved?.publicKey ?? c.dim('unknown (log in again to fetch it)')}\\n${c.bold('api key')} ${target.token.slice(0, 11)}…`);\n}\n\n/** `splithub projects`: what this machine is connected to, the current directory first. */\nexport async function projects(flags: Flags): Promise<void> {\n const api = cloudTarget({ api: flags.api }).url;\n const here = process.cwd();\n const rows = listCredentials(api).map((r) => ({ root: r.root, current: r.root === here, projectId: r.cred.projectId, projectName: r.cred.projectName, publicKey: r.cred.publicKey ?? null, savedAt: r.cred.savedAt }));\n if (flags.json) {\n console.log(JSON.stringify({ api, credentials: credentialsFile(), projects: rows }, null, 2));\n return;\n }\n if (rows.length === 0) {\n console.log(c.dim('no directory on this machine is connected yet. Run `splithub login` in your app.'));\n return;\n }\n for (const r of rows) console.log(`${r.current ? c.green('▸') : ' '} ${c.cyan(r.projectName ?? r.projectId ?? '?')} ${c.dim(`· ${r.root}`)}`);\n console.log(c.dim('\\nswitch: run `splithub login --yes --project <name>` in that directory · disconnect: `splithub logout`'));\n}\n","// Store templates for self-hosted mode: `splithub init --mode self --db postgres|mysql|custom`\n// writes splithub/store.ts from one of these. Each implements the Store interface\n// from @splithub/node (insertEvents, variantCounts, summaries) with the same\n// attribution rule as the cloud: a visitor counts once per experiment, in the\n// variant of their earliest exposure, and converts when a goal happened at or\n// after that exposure.\n\nexport type DbKind = 'sqlite' | 'postgres' | 'mysql' | 'custom';\nexport const DB_KINDS: DbKind[] = ['sqlite', 'postgres', 'mysql', 'custom'];\n\nexport const PG_STORE = `import type { ExperimentSummary, Store, StoredEvent } from '@splithub/node';\nimport type { VariantCounts } from '@splithub/stats';\nimport { Pool } from 'pg';\n\n// SplitHub events in your Postgres. Run once (or add to your migrations):\nexport const SCHEMA_SQL = \\`\nCREATE TABLE IF NOT EXISTS splithub_events (\n id text PRIMARY KEY,\n type text NOT NULL, -- exposure | goal\n experiment text,\n variant text,\n goal text,\n visitor_id text NOT NULL,\n session_id text NOT NULL,\n ts bigint NOT NULL, -- client clock, unix ms\n url text,\n props jsonb,\n received_at bigint NOT NULL, -- server clock, unix ms\n host text,\n country text,\n device text,\n browser text\n);\nCREATE INDEX IF NOT EXISTS splithub_events_exp ON splithub_events (type, experiment, visitor_id, ts);\nCREATE INDEX IF NOT EXISTS splithub_events_goal ON splithub_events (type, goal, visitor_id, ts);\n\\`;\n\nexport function pgStore(pool: Pool = new Pool({ connectionString: process.env.DATABASE_URL })): Store {\n return {\n async insertEvents(events: StoredEvent[]) {\n if (events.length === 0) return 0;\n const cols = 15;\n const values: unknown[] = [];\n const rows = events.map((e, i) => {\n values.push(e.id, e.type, e.experiment, e.variant, e.goal, e.visitorId, e.sessionId, e.ts, e.url, e.props ? JSON.stringify(e.props) : null, e.receivedAt, e.host ?? null, e.country ?? null, e.device ?? null, e.browser ?? null);\n return '(' + Array.from({ length: cols }, (_, j) => '$' + (i * cols + j + 1)).join(', ') + ')';\n });\n const r = await pool.query(\n 'INSERT INTO splithub_events (id, type, experiment, variant, goal, visitor_id, session_id, ts, url, props, received_at, host, country, device, browser) VALUES ' + rows.join(', ') + ' ON CONFLICT (id) DO NOTHING',\n values\n );\n return r.rowCount ?? 0;\n },\n async variantCounts(experiment: string, goal: string): Promise<VariantCounts[]> {\n const r = await pool.query(\n \\`WITH fv AS (\n SELECT visitor_id, MIN(ts) AS first_ts FROM splithub_events\n WHERE type = 'exposure' AND experiment = $1 GROUP BY visitor_id),\n first_exposure AS (\n SELECT MIN(e.variant) AS variant, fv.visitor_id, fv.first_ts\n FROM fv JOIN splithub_events e\n ON e.type = 'exposure' AND e.experiment = $1 AND e.visitor_id = fv.visitor_id AND e.ts = fv.first_ts\n GROUP BY fv.visitor_id, fv.first_ts),\n converted AS (\n SELECT fe.variant, fe.visitor_id, SUM(COALESCE((g.props->>'revenue')::numeric, 0)) AS revenue\n FROM first_exposure fe JOIN splithub_events g\n ON g.type = 'goal' AND g.goal = $2 AND g.visitor_id = fe.visitor_id AND g.ts >= fe.first_ts\n GROUP BY fe.variant, fe.visitor_id)\n SELECT fe.variant, COUNT(*)::int AS exposures,\n (SELECT COUNT(*)::int FROM converted c WHERE c.variant = fe.variant) AS conversions,\n (SELECT COALESCE(SUM(revenue), 0)::float FROM converted c WHERE c.variant = fe.variant) AS revenue\n FROM first_exposure fe GROUP BY fe.variant\\`,\n [experiment, goal]\n );\n return r.rows.map((x) => ({ variant: String(x.variant), exposures: Number(x.exposures), conversions: Number(x.conversions), revenue: Number(x.revenue) }));\n },\n async summaries(): Promise<ExperimentSummary[]> {\n const r = await pool.query(\n \\`SELECT experiment, COUNT(*)::int AS exposures, COUNT(DISTINCT visitor_id)::int AS visitors, MIN(ts)::bigint AS first_ts, MAX(ts)::bigint AS last_ts\n FROM splithub_events WHERE type = 'exposure' GROUP BY experiment\\`\n );\n return r.rows.map((x) => ({ experiment: String(x.experiment), exposures: Number(x.exposures), visitors: Number(x.visitors), firstExposureAt: x.first_ts == null ? null : Number(x.first_ts), lastExposureAt: x.last_ts == null ? null : Number(x.last_ts) }));\n },\n close: () => pool.end(),\n };\n}\n`;\n\nexport const MYSQL_STORE = `import type { ExperimentSummary, Store, StoredEvent } from '@splithub/node';\nimport type { VariantCounts } from '@splithub/stats';\nimport mysql, { type Pool } from 'mysql2/promise';\n\n// SplitHub events in your MySQL / MariaDB / PlanetScale. Run once (or add to your migrations):\nexport const SCHEMA_SQL = \\`\nCREATE TABLE IF NOT EXISTS splithub_events (\n id VARCHAR(64) PRIMARY KEY,\n type VARCHAR(16) NOT NULL,\n experiment VARCHAR(64) NULL,\n variant VARCHAR(64) NULL,\n goal VARCHAR(64) NULL,\n visitor_id VARCHAR(64) NOT NULL,\n session_id VARCHAR(64) NOT NULL,\n ts BIGINT NOT NULL,\n url VARCHAR(512) NULL,\n props JSON NULL,\n received_at BIGINT NOT NULL,\n host VARCHAR(255) NULL,\n country VARCHAR(8) NULL,\n device VARCHAR(16) NULL,\n browser VARCHAR(32) NULL,\n INDEX splithub_events_exp (type, experiment, visitor_id, ts),\n INDEX splithub_events_goal (type, goal, visitor_id, ts)\n);\n\\`;\n\nexport function mysqlStore(pool: Pool = mysql.createPool(process.env.DATABASE_URL ?? '')): Store {\n return {\n async insertEvents(events: StoredEvent[]) {\n if (events.length === 0) return 0;\n const values = events.map((e) => [e.id, e.type, e.experiment, e.variant, e.goal, e.visitorId, e.sessionId, e.ts, e.url, e.props ? JSON.stringify(e.props) : null, e.receivedAt, e.host ?? null, e.country ?? null, e.device ?? null, e.browser ?? null]);\n const [r] = await pool.query(\n 'INSERT IGNORE INTO splithub_events (id, type, experiment, variant, goal, visitor_id, session_id, ts, url, props, received_at, host, country, device, browser) VALUES ?',\n [values]\n );\n return (r as { affectedRows: number }).affectedRows;\n },\n async variantCounts(experiment: string, goal: string): Promise<VariantCounts[]> {\n const [rows] = await pool.query(\n // Derived tables only (no CTEs, no window functions) so this runs on MySQL 5.7.\n \\`SELECT v.variant, COUNT(*) AS exposures, SUM(v.converted) AS conversions, COALESCE(SUM(v.revenue), 0) AS revenue\n FROM (\n SELECT fe.variant, fe.visitor_id,\n CASE WHEN COUNT(g.id) > 0 THEN 1 ELSE 0 END AS converted,\n SUM(COALESCE(JSON_EXTRACT(g.props, '$.revenue'), 0)) AS revenue\n FROM (\n SELECT MIN(e.variant) AS variant, fv.visitor_id, fv.first_ts\n FROM (SELECT visitor_id, MIN(ts) AS first_ts FROM splithub_events WHERE type = 'exposure' AND experiment = ? GROUP BY visitor_id) fv\n JOIN splithub_events e ON e.type = 'exposure' AND e.experiment = ? AND e.visitor_id = fv.visitor_id AND e.ts = fv.first_ts\n GROUP BY fv.visitor_id, fv.first_ts) fe\n LEFT JOIN splithub_events g ON g.type = 'goal' AND g.goal = ? AND g.visitor_id = fe.visitor_id AND g.ts >= fe.first_ts\n GROUP BY fe.variant, fe.visitor_id) v\n GROUP BY v.variant\\`,\n [experiment, experiment, goal]\n );\n return (rows as Array<Record<string, unknown>>).map((x) => ({ variant: String(x.variant), exposures: Number(x.exposures), conversions: Number(x.conversions), revenue: Number(x.revenue) }));\n },\n async summaries(): Promise<ExperimentSummary[]> {\n const [rows] = await pool.query(\n \\`SELECT experiment, COUNT(*) AS exposures, COUNT(DISTINCT visitor_id) AS visitors, MIN(ts) AS first_ts, MAX(ts) AS last_ts\n FROM splithub_events WHERE type = 'exposure' GROUP BY experiment\\`\n );\n return (rows as Array<Record<string, unknown>>).map((x) => ({ experiment: String(x.experiment), exposures: Number(x.exposures), visitors: Number(x.visitors), firstExposureAt: x.first_ts == null ? null : Number(x.first_ts), lastExposureAt: x.last_ts == null ? null : Number(x.last_ts) }));\n },\n close: () => pool.end(),\n };\n}\n`;\n\nexport const CUSTOM_STORE = `import type { ExperimentSummary, Store, StoredEvent } from '@splithub/node';\nimport type { VariantCounts } from '@splithub/stats';\n\n/**\n * Your own store (Prisma, Drizzle, Supabase, Mongo, anything). Three methods.\n * Attribution rule (keep it, so results match the dashboard):\n * a visitor counts once per experiment, in the variant of their earliest\n * exposure (same ts: smallest variant key), and converts when they sent the\n * goal at or after that exposure; count unique visitors, not events.\n * Columns worth keeping: id (unique, dedupe on it), type, experiment, variant,\n * goal, visitor_id, session_id, ts, url, props (json), received_at, host,\n * country, device, browser.\n */\nexport function customStore(): Store {\n return {\n async insertEvents(events: StoredEvent[]): Promise<number> {\n // Insert, skipping ids that already exist. Return how many were inserted.\n throw new Error('implement insertEvents ' + events.length);\n },\n async variantCounts(experiment: string, goal: string): Promise<VariantCounts[]> {\n // For each variant: exposures = visitors whose earliest exposure in this experiment was to it;\n // conversions = those visitors with a goal event (goal === goal) at ts >= that earliest exposure;\n // revenue = sum of props.revenue over those goal events.\n throw new Error('implement variantCounts ' + experiment + ' ' + goal);\n },\n async summaries(): Promise<ExperimentSummary[]> {\n // Per experiment: exposures, unique visitors, first and last exposure ts (unix ms).\n throw new Error('implement summaries');\n },\n };\n}\n`;\n\nexport function storeTemplate(db: DbKind): string | null {\n return db === 'postgres' ? PG_STORE : db === 'mysql' ? MYSQL_STORE : db === 'custom' ? CUSTOM_STORE : null;\n}\n\n/** Import line + factory call used by the route template. */\nexport function storeUsage(db: DbKind, storeImport: string): { imports: string; factory: string } {\n switch (db) {\n case 'postgres':\n return { imports: `import { pgStore } from '${storeImport}';`, factory: 'pgStore()' };\n case 'mysql':\n return { imports: `import { mysqlStore } from '${storeImport}';`, factory: 'mysqlStore()' };\n case 'custom':\n return { imports: `import { customStore } from '${storeImport}';`, factory: 'customStore()' };\n default:\n return { imports: `import { sqliteStore } from '@splithub/adapter-sqlite';`, factory: `sqliteStore({ file: process.env.SPLITHUB_DB ?? './splithub.db' })` };\n }\n}\n\nexport function runtimePackages(db: DbKind): string[] {\n return db === 'postgres' ? ['pg'] : db === 'mysql' ? ['mysql2'] : db === 'sqlite' ? ['@splithub/adapter-sqlite'] : [];\n}\n","// `splithub skills [--mcp] [--force]`: install or refresh the agent skills in\n// this project (.claude/skills/<name>/SKILL.md, .cursor/rules/splithub.mdc,\n// an AGENTS.md section) and, with --mcp, register the SplitHub MCP server in\n// .mcp.json (Claude Code) and .cursor/mcp.json (Cursor). `init` calls this too.\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, join, relative } from 'node:path';\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}\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/.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 } = {}): SkillsResult {\n const out: SkillsResult = { written: [], skipped: [], mcp: [] };\n for (const s of SKILLS) writeFile(join(root, '.claude', 'skills', s.dir, 'SKILL.md'), s.body, Boolean(options.force), out);\n writeFile(join(root, '.cursor', 'rules', 'splithub.mdc'), CURSOR_RULE, Boolean(options.force), out);\n\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${AGENTS_SECTION}`, 'utf8');\n out.written.push(agentsFile);\n } else if (!/SplitHub/.test(readFileSync(agentsFile, 'utf8'))) {\n writeFileSync(agentsFile, readFileSync(agentsFile, 'utf8') + `\\n${AGENTS_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) });\n if (flags.json) {\n console.log(JSON.stringify(result, null, 2));\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 (!flags.mcp) console.log(c.dim(`add --mcp to register the SplitHub 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 test well), splithub-api (HTTP API), splithub-mcp (MCP tools), splithub-self-hosted (your own database), splithub-ship (keep the winner, remove the test)'));\n}\n","import type { ExperimentStatus } from '@splithub/core';\nimport { relative } from 'node:path';\nimport { apiErrorMessage, cloudTarget } from '../api';\nimport { loadConfig, readSource, setExperimentStatus, writeSource } from '../config-file';\nimport { detectProject } from '../project';\nimport { c } from '../ui';\nimport type { Flags } from './init';\n\nconst MAP: Record<string, ExperimentStatus> = { start: 'running', pause: 'paused', finish: 'finished' };\n\nexport async function lifecycle(command: string, id: string | undefined, flags: Flags): Promise<void> {\n const status = MAP[command];\n if (!status) throw new Error(`unknown command \"${command}\"`);\n if (!id) throw new Error(`usage: splithub ${command} <experiment>`);\n const project = detectProject();\n if (!project.configFile) throw new Error('splithub.config.ts not found. Run `npx splithub init` first.');\n const updated = setExperimentStatus(readSource(project.configFile), id, status);\n writeSource(project.configFile, updated);\n const file = relative(project.root, project.configFile);\n\n // Cloud mode: also apply it live through a remote override, so no deploy is needed.\n let live: 'applied' | 'skipped' | string = 'skipped';\n try {\n const config = await loadConfig(project.configFile);\n if (config.storage.mode === 'cloud') {\n const target = cloudTarget(flags);\n if (!target.token) live = 'no API key (set SPLITHUB_API_KEY to apply without a deploy)';\n else {\n const res = await fetch(`${target.url}/overrides/${encodeURIComponent(id)}`, {\n method: 'PUT',\n headers: { authorization: `Bearer ${target.token}`, 'content-type': 'application/json' },\n body: JSON.stringify({ status }),\n });\n const body: unknown = await res.json().catch(() => ({}));\n live = res.ok ? 'applied' : `cloud refused: ${apiErrorMessage(res.status, body, String(res.status))}`;\n }\n }\n } catch (error) {\n live = `could not apply live: ${error instanceof Error ? error.message : String(error)}`;\n }\n\n // A finished test keeps its numbers, but every variant is still in the code until someone decides.\n const next = status === 'finished' ? `Read the verdict (npx splithub results ${id}), decide which variant to keep, then remove the test from the code and the config: the splithub-ship skill walks an agent through it.` : null;\n if (flags.json) console.log(JSON.stringify({ experiment: id, status, configFile: file, live, ...(next ? { next } : {}) }));\n else {\n console.log(`${c.green('✔')} ${c.bold(id)} → ${status} ${c.dim(`(${file})`)}`);\n if (live === 'applied') console.log(`${c.green('✔')} live in the cloud within 60s, no deploy needed (the config change ships with your next deploy)`);\n else if (live !== 'skipped') console.log(c.yellow(`! ${live}`));\n if (next) console.log(c.dim(`Next: ${next}`));\n }\n}\n","// `npx splithub` with no arguments: a menu that walks through everything step\n// by step (like an interactive assistant), so nobody has to learn the flags.\n// Agents and scripts keep using the subcommands + --json.\nimport * as p from '@clack/prompts';\nimport { readFileSync } from 'node:fs';\nimport { cloudTarget, fetchStatus, resolveTarget } from '../api';\nimport { loadCredential } from '../credentials';\nimport { detectProject } from '../project';\nimport { c } from '../ui';\nimport { create } from './create';\nimport { dev } from './dev';\nimport { doctor } from './doctor';\nimport { init, type Flags } from './init';\nimport { lifecycle } from './lifecycle';\nimport { login, logout } from './login';\nimport { pull, push } from './push';\nimport { results } from './results';\nimport { skills } from './skills';\nimport { status } from './status';\n\ntype Action = 'init' | 'create' | 'status' | 'results' | 'start' | 'pause' | 'finish' | 'push' | 'pull' | 'login' | 'logout' | 'dev' | 'doctor' | 'skills' | 'exit';\n\nfunction state(flags: Flags) {\n const project = detectProject();\n const api = cloudTarget({ api: flags.api }).url;\n const cred = loadCredential(api, project.root);\n const mode = project.configFile ? (/mode\\s*:\\s*['\"]cloud['\"]/.test(readSafe(project.configFile)) ? 'cloud' : 'self') : null;\n return { project, cred, mode, connected: Boolean(cred || process.env.SPLITHUB_API_KEY) };\n}\n\nfunction readSafe(file: string): string {\n try {\n return readFileSync(file, 'utf8');\n } catch {\n return '';\n }\n}\n\nasync function pickExperiment(flags: Flags, message: string): Promise<string | null> {\n try {\n const data = await fetchStatus(resolveTarget(flags, detectProject()));\n if (data.experiments.length === 0) {\n p.log.warn('no experiments yet');\n return null;\n }\n const picked = await p.select({ message, options: data.experiments.map((e) => ({ value: e.experiment, label: e.experiment, hint: `${e.status} · ${e.visitors} visitors${e.headline ? ` · ${e.headline}` : ''}` })) });\n if (p.isCancel(picked)) return null;\n return picked as string;\n } catch (error) {\n p.log.error(error instanceof Error ? error.message : String(error));\n return null;\n }\n}\n\nexport async function menu(flags: Flags): Promise<void> {\n p.intro(c.bold('splithub'));\n for (;;) {\n const s = state(flags);\n const where = s.project.configFile ? `${c.green('config')} ${s.mode === 'cloud' ? 'cloud mode' : 'self-hosted'}` : c.yellow('no config yet');\n const who = s.cred ? `${c.green('connected')} to ${c.cyan(s.cred.projectName ?? s.cred.projectId ?? 'project')}` : s.mode === 'cloud' ? c.yellow('not connected') : c.dim('local only');\n p.log.info(`${c.bold(s.project.name)} (${s.project.framework}) · ${where} · ${who}`);\n\n const options: Array<{ value: Action; label: string; hint?: string }> = [];\n if (!s.project.configFile) options.push({ value: 'init', label: 'Set up this app', hint: 'config, framework files, agent docs, sign-in link' });\n else {\n if (s.mode === 'cloud' && !s.connected) options.push({ value: 'login', label: 'Connect to SplitHub Cloud', hint: 'opens a sign-in link' });\n options.push({ value: 'create', label: 'Create an experiment', hint: 'step by step' });\n options.push({ value: 'status', label: 'Status of all experiments' });\n options.push({ value: 'results', label: 'Results of one experiment', hint: 'verdict, lift, confidence' });\n options.push({ value: 'start', label: 'Start an experiment' }, { value: 'pause', label: 'Pause an experiment' }, { value: 'finish', label: 'Finish an experiment' });\n if (s.mode === 'cloud') options.push({ value: 'push', label: 'Push config to the cloud', hint: 'after editing splithub.config.ts' }, { value: 'pull', label: 'Pull dashboard changes into the file' });\n options.push({ value: 'dev', label: 'Test locally in the browser', hint: 'debug panel: variants, reasons, events' });\n options.push({ value: 'doctor', label: 'Check the installation' });\n options.push({ value: 'skills', label: 'Install agent skills + MCP server', hint: 'Claude Code, Cursor, Codex' });\n if (s.cred) options.push({ value: 'logout', label: 'Disconnect this folder' });\n }\n options.push({ value: 'exit', label: 'Exit' });\n\n const action = await p.select<Action>({ message: 'What do you want to do?', options });\n if (p.isCancel(action) || action === 'exit') break;\n try {\n switch (action) {\n case 'init':\n await init({ ...flags, mode: flags.mode ?? 'cloud' });\n break;\n case 'login':\n await login({ ...flags, yes: true });\n break;\n case 'create':\n await create(flags);\n break;\n case 'status':\n await status(flags);\n break;\n case 'results': {\n const key = await pickExperiment(flags, 'Which experiment?');\n if (key) await results(key, flags);\n break;\n }\n case 'start':\n case 'pause':\n case 'finish': {\n const key = await pickExperiment(flags, `Which experiment to ${action}?`);\n if (key) await lifecycle(action, key, flags);\n break;\n }\n case 'push':\n await push(flags);\n break;\n case 'pull':\n await pull(flags);\n break;\n case 'logout':\n await logout(flags);\n break;\n case 'dev':\n await dev(flags);\n break;\n case 'doctor':\n await doctor(flags);\n break;\n case 'skills':\n await skills({ ...flags, mcp: true });\n break;\n }\n } catch (error) {\n p.log.error(error instanceof Error ? error.message : String(error));\n }\n console.log();\n }\n p.outro(`Scripts and agents: ${c.cyan('splithub --help')} lists every command; add ${c.cyan('--json')} for machine output.`);\n}\n","import { relative } from 'node:path';\nimport { apiErrorMessage, cloudTarget } from '../api';\nimport { hasExperiment, insertExperiment, loadConfig, readSource, writeSource } from '../config-file';\nimport { detectProject } from '../project';\nimport { c } from '../ui';\nimport type { Flags } from './init';\n\ninterface CloudExperiment {\n key: string;\n kind: 'component' | 'value' | 'redirect' | 'mvt';\n status: 'draft' | 'running' | 'paused' | 'finished';\n goal: string | null;\n match: string | null;\n description: string | null;\n variants: Array<{ key: string; weight: number; value?: unknown; to?: string; levels?: Record<string, string> }>;\n /** Multivariate: the factors whose combinations the variants are. */\n factors?: Array<{ key: string; levels: string[] }>;\n flow?: unknown;\n traffic?: number;\n maxExposures?: number | null;\n schedule?: { startAt?: string | null; endAt?: string | null } | null;\n}\n\ninterface PushResponse {\n ok: boolean;\n project: string;\n version: number;\n pushedAt: string;\n publicKey: string;\n experiments: number;\n /** Experiments created in the dashboard that the local file does not have yet. */\n cloudOnly?: CloudExperiment[];\n}\n\n/** Write dashboard-created experiments into the local config file. Returns the keys written. */\n/** Factor → level → value, read back from the combinations the cloud generated. */\nfunction factorsOf(e: CloudExperiment): Record<string, Record<string, string>> {\n const out: Record<string, Record<string, string>> = {};\n for (const f of e.factors ?? []) {\n out[f.key] = {};\n for (const level of f.levels) {\n const combo = e.variants.find((v) => v.levels?.[f.key] === level);\n const value = (combo?.value as Record<string, unknown> | undefined)?.[f.key];\n out[f.key]![level] = typeof value === 'string' ? value : value === undefined ? level : JSON.stringify(value);\n }\n }\n return out;\n}\n\nfunction adoptCloudExperiments(file: string, cloudOnly: CloudExperiment[] | undefined): string[] {\n if (!cloudOnly || cloudOnly.length === 0) return [];\n let source = readSource(file);\n const written: string[] = [];\n for (const e of cloudOnly) {\n if (hasExperiment(source, e.key)) continue;\n const total = e.variants.reduce((s, v) => s + v.weight, 0) || 1;\n source = insertExperiment(source, {\n key: e.key,\n kind: e.kind,\n status: e.status,\n goal: e.goal ?? undefined,\n match: e.match ?? undefined,\n description: e.description ?? undefined,\n flow: e.flow ?? undefined,\n traffic: e.traffic,\n maxExposures: e.maxExposures ?? undefined,\n schedule: e.schedule ?? undefined,\n variants: e.variants.map((v) => ({ key: v.key, weight: Math.round((v.weight / total) * 100), value: typeof v.value === 'string' ? v.value : v.value === undefined ? undefined : JSON.stringify(v.value), to: v.to })),\n ...(e.kind === 'mvt' && e.factors ? { factors: factorsOf(e) } : {}),\n });\n written.push(e.key);\n }\n if (written.length) writeSource(file, source);\n return written;\n}\n\n/**\n * `splithub push`: upload the normalized splithub.config.ts to SplitHub Cloud.\n * Needs a project API key (sk_...) via --token or SPLITHUB_API_KEY. The first\n * push returns the public key (pk_...) which is written into the config's\n * `storage.key` when it is still empty.\n */\nexport async function push(flags: Flags): Promise<void> {\n const project = detectProject();\n if (!project.configFile) throw new Error('splithub.config.ts not found. Run `npx splithub init` first.');\n const config = await loadConfig(project.configFile);\n if (config.storage.mode !== 'cloud') {\n throw new Error(`storage.mode is \"${config.storage.mode}\". Set storage: { mode: 'cloud' } in splithub.config.ts to use SplitHub Cloud.`);\n }\n const target = cloudTarget(flags);\n if (!target.token) throw new Error('project API key required: run `npx splithub login`, or pass --token sk_... / SPLITHUB_API_KEY (dashboard → Settings → API keys).');\n\n const res = await fetch(`${target.url}/config`, {\n method: 'PUT',\n headers: { authorization: `Bearer ${target.token}`, 'content-type': 'application/json' },\n body: JSON.stringify({ config }),\n });\n const body = (await res.json().catch(() => ({}))) as Partial<PushResponse> & { error?: string };\n if (!res.ok) throw new Error(apiErrorMessage(res.status, body, `${target.url}/config responded ${res.status}`));\n\n // Write the public key into the config when it is missing.\n let keyWritten = false;\n if (body.publicKey && !config.storage.key) {\n const source = readSource(project.configFile);\n const updated = source.replace(/(mode\\s*:\\s*['\"]cloud['\"]\\s*)(,?)(\\s*\\})/, (_m, a: string, _comma: string, b: string) => `${a}, key: '${body.publicKey}'${b}`);\n if (updated !== source) {\n writeSource(project.configFile, updated);\n keyWritten = true;\n }\n }\n\n const adopted = adoptCloudExperiments(project.configFile, body.cloudOnly);\n const out = { ...body, configFile: relative(project.root, project.configFile), keyWritten, adopted };\n if (flags.json) {\n console.log(JSON.stringify(out, null, 2));\n return;\n }\n console.log(`${c.green('✔')} pushed ${c.bold(String(body.project))} v${body.version} · ${body.experiments} experiment(s) → ${target.url}`);\n if (adopted.length) console.log(`${c.green('✔')} written into ${out.configFile} from the dashboard: ${adopted.join(', ')} (wire them in code if they are value/component experiments)`);\n if (body.publicKey) {\n console.log(keyWritten ? `${c.green('✔')} public key written to ${out.configFile}` : `${c.dim('public key:')} ${body.publicKey}`);\n if (!keyWritten && !config.storage.key) console.log(c.yellow(`Add it to splithub.config.ts: storage: { mode: 'cloud', key: '${body.publicKey}' }`));\n }\n}\n\n/** `splithub pull`: print the config stored in the cloud (for inspection or recovery). */\nexport async function pull(flags: Flags): Promise<void> {\n const target = cloudTarget(flags);\n if (!target.token) throw new Error('project API key required: run `npx splithub login`, or pass --token sk_... / SPLITHUB_API_KEY');\n const res = await fetch(`${target.url}/config`, { headers: { authorization: `Bearer ${target.token}` } });\n const body = (await res.json().catch(() => ({}))) as { error?: string; config?: { experiments?: Array<CloudExperiment & { origin?: string }> }; version?: number; pushedAt?: string; publicKey?: string };\n if (!res.ok) throw new Error(apiErrorMessage(res.status, body, `${target.url}/config responded ${res.status}`));\n const project = detectProject();\n const dashboardOnes = (body.config?.experiments ?? []).filter((e) => e.origin === 'dashboard');\n const adopted = project.configFile ? adoptCloudExperiments(project.configFile, dashboardOnes) : [];\n if (flags.json) {\n console.log(JSON.stringify({ ...body, adopted }, null, 2));\n return;\n }\n console.log(`${c.bold('cloud config')} v${body.version} ${c.dim(`pushed ${body.pushedAt}`)} · public key ${body.publicKey}`);\n if (adopted.length) console.log(`${c.green('✔')} written into ${relative(project.root, project.configFile ?? '')}: ${adopted.join(', ')}`);\n else if (dashboardOnes.length) console.log(c.dim(`dashboard experiments already present locally: ${dashboardOnes.map((e) => e.key).join(', ')}`));\n else console.log(c.dim('no dashboard-created experiments to pull'));\n}\n","import { fetchResults, resolveTarget } from '../api';\nimport { detectProject } from '../project';\nimport { bar, c, pct, statusColor, table, verdictColor, verdictIcon } from '../ui';\n\nexport async function results(key: string | undefined, flags: Record<string, unknown>): Promise<void> {\n if (!key) throw new Error('usage: splithub results <experiment>');\n const target = resolveTarget(flags, detectProject());\n const r = await fetchResults(target, key);\n if (flags.json) {\n console.log(JSON.stringify(r.status === 'finished' ? { ...r, next: FINISHED_NEXT } : r, null, 2));\n return;\n }\n const v = r.verdict;\n console.log(`${c.bold(r.experiment)} ${c.dim(`· ${r.kind} · `)}${statusColor(r.status)} ${c.dim(`· goal: ${r.goal ?? 'none'}`)}`);\n if (r.description) console.log(c.dim(r.description));\n console.log();\n console.log(verdictColor(v.status, `${label(v.status)} ${v.message}`));\n console.log();\n\n const rates = new Map<string, number>();\n for (const cnt of v.sample.variants) rates.set(cnt.variant, cnt.exposures > 0 ? cnt.conversions / cnt.exposures : 0);\n\n console.log(\n table(\n ['VARIANT', 'VISITORS', 'CONV', 'RATE', 'LIFT', 'P(BEAT)', 'P-VALUE', '95% CI'],\n v.sample.variants.map((cnt, i) => {\n const cmp = v.comparisons.find((x) => x.variant === cnt.variant);\n const name = i === 0 ? `${cnt.variant} ${c.dim('(control)')}` : cnt.variant;\n const marked = v.winner === cnt.variant ? c.green(`★ ${name}`) : name;\n return [\n marked,\n String(cnt.exposures),\n String(cnt.conversions),\n pct(rates.get(cnt.variant)),\n cmp ? pct(cmp.relativeLift, true) : '–',\n cmp ? pct(cmp.probabilityToBeat) : '–',\n cmp ? cmp.pValue.toFixed(4) : '–',\n cmp ? `${pct(cmp.ci.low, true)} … ${pct(cmp.ci.high, true)}` : '–',\n ];\n })\n )\n );\n // Rates as bars, lift next to them; P(beat) as a second bar. Reads at a glance in a terminal.\n const maxRate = Math.max(0.0001, ...v.sample.variants.map((cnt) => rates.get(cnt.variant) ?? 0));\n const nameWidth = Math.max(...v.sample.variants.map((cnt) => cnt.variant.length));\n console.log();\n console.log(c.dim('RATE'));\n for (const cnt of v.sample.variants) {\n const cmp = v.comparisons.find((x) => x.variant === cnt.variant);\n const paint = v.winner === cnt.variant ? c.green : cmp && (cmp.relativeLift ?? 0) < 0 ? c.red : c.cyan;\n const lift = cmp ? (cmp.relativeLift ?? 0) >= 0 ? c.green(`▲ ${pct(cmp.relativeLift, true)}`) : c.red(`▼ ${pct(cmp.relativeLift, true)}`) : c.dim('baseline');\n console.log(`${cnt.variant.padEnd(nameWidth)} ${bar(rates.get(cnt.variant) ?? 0, maxRate, 24, paint)} ${pct(rates.get(cnt.variant)).padStart(6)} ${lift}`);\n }\n if (v.comparisons.length) {\n console.log();\n console.log(c.dim('CHANCE TO BEAT THE CONTROL'));\n for (const cmp of v.comparisons) {\n const paint = cmp.probabilityToBeat >= 0.95 ? c.green : cmp.probabilityToBeat <= 0.05 ? c.red : c.yellow;\n console.log(`${cmp.variant.padEnd(nameWidth)} ${bar(cmp.probabilityToBeat, 1, 24, paint)} ${pct(cmp.probabilityToBeat).padStart(6)}`);\n }\n }\n if (v.srm) {\n console.log();\n console.log(c.dim(`SRM check: chi²=${v.srm.chiSquare.toFixed(2)} p=${v.srm.pValue.toExponential(2)} ${v.srm.detected ? c.red('DETECTED') : 'ok'}`));\n }\n if (v.status === 'insufficient_sample' && v.sample.neededPerVariant) {\n console.log(c.dim(`Estimated ${v.sample.neededPerVariant} visitors per variant needed to confirm the current lift.`));\n }\n if (r.factors?.length) {\n console.log();\n console.log(c.bold('Each factor on its own') + c.dim(' (a level sums every combination that uses it, compared with the first level)'));\n for (const f of r.factors) {\n console.log(\n table(\n [f.key.toUpperCase(), 'VISITORS', 'CONV.', 'RATE', 'LIFT', 'P-VALUE'],\n f.levels.map((l) => [l.level + (f.best === l.level ? c.green(' ✔') : ''), String(l.exposures), String(l.conversions), pct(l.rate), l.relativeLift === null ? '–' : pct(l.relativeLift, true), l.pValue === null ? '–' : l.pValue.toFixed(3)])\n )\n );\n }\n }\n if (r.status === 'finished') {\n console.log();\n console.log(c.dim(FINISHED_NEXT));\n }\n}\n\n/** Printed for finished tests, so a human or an agent knows the code still carries every variant. */\nconst FINISHED_NEXT = 'This test is finished but its variants are still in the code. Decide which variant to keep, then remove the test from the code and the config (agents: the splithub-ship skill).';\n\nfunction label(status: string): string {\n const icon = verdictIcon(status);\n switch (status) {\n case 'winner_found':\n return `${icon} WINNER`;\n case 'srm_detected':\n return `${icon} SRM`;\n case 'insufficient_sample':\n return `${icon} TOO EARLY`;\n case 'no_significant_difference':\n return `${icon} NO DIFFERENCE`;\n default:\n return `${icon} NO DATA`;\n }\n}\n","import { fetchStatus, resolveTarget } from '../api';\nimport { detectProject } from '../project';\nimport { bar, c, statusColor, table, verdictColor, verdictIcon } from '../ui';\n\nexport async function status(flags: Record<string, unknown>): Promise<void> {\n const target = resolveTarget(flags, detectProject());\n const data = await fetchStatus(target);\n const finished = data.experiments.filter((e) => e.status === 'finished').map((e) => e.experiment);\n const next = finished.length ? `Finished but still in the code: ${finished.join(', ')}. Decide which variant to keep, then remove the test from the code and the config (agents: the splithub-ship skill).` : null;\n if (flags.json) {\n console.log(JSON.stringify(next ? { ...data, next } : data, null, 2));\n return;\n }\n console.log(`${c.bold('SplitHub')} ${c.dim('·')} project ${c.cyan(data.project)} ${c.dim(`· ${target.url}`)}\\n`);\n if (data.experiments.length === 0) {\n console.log(c.dim('No experiments in splithub.config.ts yet. Run `splithub create`.'));\n return;\n }\n // Visitors as a bar relative to the busiest experiment, verdict with its icon.\n const maxVisitors = Math.max(1, ...data.experiments.map((e) => e.visitors));\n console.log(\n table(\n ['EXPERIMENT', 'KIND', 'STATUS', 'VISITORS', '', 'DAYS', 'VERDICT'],\n data.experiments.map((e) => [\n c.bold(e.experiment),\n e.kind,\n statusColor(e.status),\n String(e.visitors),\n bar(e.visitors, maxVisitors, 12, e.status === 'running' ? c.green : c.dim),\n e.days ? String(e.days) : '–',\n verdictColor(e.verdict, `${verdictIcon(e.goal ? e.verdict : null)} ${e.headline ?? (e.goal ? 'no data' : 'no goal')}`),\n ])\n )\n );\n if (next) console.log(`\\n${c.dim(next)}`);\n}\n","import { apiErrorMessage, cloudTarget } from '../api';\nimport { c } from '../ui';\nimport type { Flags } from './init';\n\ninterface Review {\n id: string;\n experiment: string | null;\n kind: string;\n trigger: string;\n body: string;\n model: string | null;\n createdAt: string;\n}\n\n/** `splithub review [<experiment>]`: the AI reviews stored in the cloud (Pro), newest first. */\nexport async function review(key: string | undefined, flags: Flags): Promise<void> {\n const target = cloudTarget(flags);\n if (!target.token) throw new Error('project API key required: run `npx splithub login`, or set SPLITHUB_API_KEY');\n const res = await fetch(`${target.url}/reviews${key ? `/${encodeURIComponent(key)}` : ''}`, { headers: { authorization: `Bearer ${target.token}` } });\n const data = (await res.json().catch(() => ({}))) as { reviews?: Review[]; error?: string };\n if (!res.ok) throw new Error(apiErrorMessage(res.status, data, `${target.url}/reviews responded ${res.status}`));\n const reviews = data.reviews ?? [];\n if (flags.json) {\n console.log(JSON.stringify({ experiment: key ?? null, reviews }, null, 2));\n return;\n }\n if (reviews.length === 0) {\n console.log(c.dim(key ? `no reviews for ${key} yet (Pro writes one at the start, when the verdict changes while running, and on finish; or click \"Review now\" in the dashboard)` : 'no reviews yet'));\n return;\n }\n for (const r of reviews) {\n console.log(`${c.bold(r.experiment ?? 'project')} ${c.dim(`· ${r.kind}${r.trigger && r.trigger !== 'manual' ? ` · ${r.trigger}` : ''} · ${new Date(r.createdAt).toLocaleString()}`)}`);\n console.log(r.body.trim());\n console.log();\n }\n}\n"],"mappings":";;;AAAA,SAAS,iBAAiB;;;ACA1B,YAAY,OAAO;AACnB,SAAS,mBAA+D;AACxE,SAAS,cAAAA,aAAY,WAAW,iBAAAC,sBAAqB;AACrD,SAAS,QAAAC,OAAM,gBAAgB;;;ACH/B,SAAS,wBAAyF;AAClG,SAAS,cAAc,qBAAqB;AAC5C,SAAS,qBAAqB;AAG9B,eAAsB,WAAW,MAAuC;AACtE,QAAM,EAAE,WAAW,IAAI,MAAM,OAAO,MAAM;AAC1C,QAAM,OAAO,WAAW,cAAc,IAAI,EAAE,MAAM,EAAE,SAAS,OAAO,aAAa,MAAM,CAAC;AACxF,QAAM,MAAO,MAAM,KAAK,OAAO,MAAM,EAAE,SAAS,KAAK,CAAC;AACtD,MAAI,CAAC,iBAAiB,GAAG,GAAG;AAC1B,UAAM,IAAI,MAAM,GAAG,IAAI,mEAAmE;AAAA,EAC5F;AACA,SAAO;AACT;AAEA,SAAS,WAAW,KAAqB;AACvC,QAAM,MAAM,IAAI,QAAQ,uBAAuB,MAAM;AACrD,SAAO,IAAI,OAAO,0BAA0B,GAAG,uBAAuB;AACxE;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KAAM,QAAO,KAAK,MAAM;AACnF,YAAQ,IAAI,KAAK,QAAQ,CAAC;AAC1B;AAAA,EACF;AACA,UAAQ,SAAS;AAAA,IACf,KAAK;AACH,aAAO,KAAK,MAAM;AAAA,IACpB,KAAK;AACH,aAAO,OAAO,MAAM;AAAA,IACtB,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACH,aAAO,UAAU,SAAS,KAAK,MAAM;AAAA,IACvC,KAAK;AACH,aAAO,OAAO,MAAM;AAAA,IACtB,KAAK;AACH,aAAO,QAAQ,KAAK,MAAM;AAAA,IAC5B,KAAK;AACH,aAAO,OAAO,KAAK,MAAM;AAAA,IAC3B,KAAK;AACH,aAAO,IAAI,MAAM;AAAA,IACnB,KAAK;AACH,aAAO,OAAO,MAAM;AAAA,IACtB,KAAK;AACH,aAAO,OAAO,MAAM;AAAA,IACtB,KAAK;AACH,aAAO,KAAK,MAAM;AAAA,IACpB,KAAK;AACH,aAAO,KAAK,MAAM;AAAA,IACpB,KAAK;AACH,aAAO,MAAM,MAAM;AAAA,IACrB,KAAK;AACH,aAAO,OAAO,MAAM;AAAA,IACtB,KAAK;AACH,aAAO,OAAO,MAAM;AAAA,IACtB,KAAK;AACH,aAAO,SAAS,MAAM;AAAA,IACxB;AACE,YAAM,IAAI,MAAM,oBAAoB,OAAO;AAAA,EAAM,IAAI,EAAE;AAAA,EAC3D;AACF;AAEA,KAAK,EAAE,MAAM,CAAC,UAAmB;AAC/B,UAAQ,MAAM,EAAE,IAAI,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE,CAAC;AACvF,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["existsSync","writeFileSync","join","status","readFileSync","p","dev","status","text","k","status","join","existsSync","writeFileSync","readFileSync","existsSync","mkdirSync","readFileSync","writeFileSync","join","resolve","readFileSync","status","text","resolve","existsSync","readFileSync","join","relative","relative","join","existsSync","readFileSync","label","p","existsSync","mkdirSync","writeFileSync","dirname","join","relative","label","existsSync","mkdirSync","readFileSync","writeFileSync","join","relative","existsSync","readFileSync","mkdirSync","writeFileSync","join","relative","str","existsSync","mkdirSync","dirname","writeFileSync","relative","cancel","k","join","relative","status","relative","p","readFileSync","relative","relative","status","readFileSync"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/commands/create.ts","../src/config-file.ts","../src/project.ts","../src/skills-self-hosted.ts","../src/skills-ship.ts","../src/skills.ts","../src/templates.ts","../src/ui.ts","../src/commands/dev.ts","../src/api.ts","../src/credentials.ts","../src/commands/doctor.ts","../src/commands/init.ts","../src/commands/login.ts","../src/templates-store.ts","../src/commands/skills.ts","../src/commands/lifecycle.ts","../src/commands/menu.ts","../src/commands/push.ts","../src/commands/results.ts","../src/commands/status.ts","../src/commands/review.ts"],"sourcesContent":["import { parseArgs } from 'node:util';\nimport { create } from './commands/create';\nimport { dev } from './commands/dev';\nimport { doctor } from './commands/doctor';\nimport { init } from './commands/init';\nimport { lifecycle } from './commands/lifecycle';\nimport { login, logout, projects, whoami } from './commands/login';\nimport { menu } from './commands/menu';\nimport { skills } from './commands/skills';\nimport { pull, push } from './commands/push';\nimport { results } from './commands/results';\nimport { review } from './commands/review';\nimport { status } from './commands/status';\nimport { c } from './ui';\n\nconst HELP = `\n${c.bold('splithub')} — A/B testing for agent-built apps\n\nUsage\n splithub interactive menu: set up, create, results, start/pause, push — step by step\n splithub init set up config, framework files, agent docs\n splithub create add an experiment (wizard, or flags for agents)\n splithub start|pause|finish <id>\n splithub status all experiments with a verdict headline\n splithub results <id> full verdict for one experiment\n splithub review [<id>] AI reviews stored in the cloud (Pro: at start, on verdict changes, on finish, or on demand)\n splithub dev [--url] [--hold] open the app with ?sh_debug=1 (console + panel: variants, reasons, events) and watch results\n splithub doctor check the installation\n splithub skills [--mcp] install / refresh agent skills (library, A/B testing, API, MCP, self-hosting, ship the winner); --mcp registers the MCP server\n splithub login [--project <name|id>] connect this directory to a SplitHub Cloud project (sign-in link, no secrets typed)\n splithub projects every directory connected on this machine and its project; --json for agents\n splithub whoami the project this directory is connected to\n splithub logout disconnect this directory\n splithub push upload splithub.config.ts to SplitHub Cloud\n splithub pull show the config stored in the cloud\n\ncreate flags\n --kind value|component|redirect --id <key> --variants control,b --weights 50,50\n --goal <goal> --value k=text (repeatable) --match /path --to k=/url (repeatable)\n --status draft|running --description \"...\" --traffic 50 (percent) --max-visitors 10000 --start/--end <ISO date> --yes\n\ninit flags\n --mode self|cloud --db sqlite|postgres|mysql|custom (self mode) --key pk_... --no-install --no-login --no-mcp --yes\n (cloud mode without a saved login prints a link; approve it in the browser and init continues)\n\nGlobal\n --url <url> results endpoint (default: $SPLITHUB_URL, the cloud API in cloud mode, else the local dev server)\n --token <token> admin token (self: $SPLITHUB_ADMIN_TOKEN) or project API key (cloud: $SPLITHUB_API_KEY, else the key saved by \"splithub login\")\n --api <url> cloud API base (default: https://go.splithub.io/v1 or $SPLITHUB_API)\n --json machine-readable output (for agents)\n -h, --help\n`;\n\nasync function main(): Promise<void> {\n const { values, positionals } = parseArgs({\n allowPositionals: true,\n options: {\n url: { type: 'string' },\n api: { type: 'string' },\n token: { type: 'string' },\n json: { type: 'boolean', default: false },\n yes: { type: 'boolean', short: 'y', default: false },\n help: { type: 'boolean', short: 'h', default: false },\n mode: { type: 'string' },\n db: { type: 'string' },\n key: { type: 'string' },\n 'no-install': { type: 'boolean', default: false },\n 'no-login': { type: 'boolean', default: false },\n 'no-mcp': { type: 'boolean', default: false },\n mcp: { type: 'boolean', default: false },\n force: { type: 'boolean', default: false },\n kind: { type: 'string' },\n id: { type: 'string' },\n variants: { type: 'string' },\n weights: { type: 'string' },\n goal: { type: 'string' },\n value: { type: 'string', multiple: true },\n match: { type: 'string' },\n to: { type: 'string', multiple: true },\n factor: { type: 'string', multiple: true },\n status: { type: 'string' },\n description: { type: 'string' },\n traffic: { type: 'string' },\n 'max-visitors': { type: 'string' },\n start: { type: 'string' },\n end: { type: 'string' },\n project: { type: 'string' },\n },\n });\n const [command, arg] = positionals;\n if (values.help) {\n console.log(HELP.trimEnd());\n return;\n }\n if (!command) {\n // A terminal → the interactive menu; a pipe or an agent → the help text.\n if (process.stdin.isTTY && process.stdout.isTTY && !values.json) return menu(values);\n console.log(HELP.trimEnd());\n return;\n }\n switch (command) {\n case 'init':\n return init(values);\n case 'create':\n return create(values);\n case 'start':\n case 'pause':\n case 'finish':\n return lifecycle(command, arg, values);\n case 'status':\n return status(values);\n case 'results':\n return results(arg, values);\n case 'review':\n return review(arg, values);\n case 'dev':\n return dev(values);\n case 'doctor':\n return doctor(values);\n case 'skills':\n return skills(values);\n case 'push':\n return push(values);\n case 'pull':\n return pull(values);\n case 'login':\n return login(values);\n case 'logout':\n return logout(values);\n case 'whoami':\n return whoami(values);\n case 'projects':\n return projects(values);\n default:\n throw new Error(`unknown command \"${command}\"\\n${HELP}`);\n }\n}\n\nmain().catch((error: unknown) => {\n console.error(c.red(`error: ${error instanceof Error ? error.message : String(error)}`));\n process.exit(1);\n});\n","import * as p from '@clack/prompts';\nimport { mvtVariants, type ExperimentKind, type ExperimentStatus } from '@splithub/core';\nimport { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport { hasExperiment, insertExperiment, loadConfig, readSource, writeSource, type NewExperiment } from '../config-file';\nimport { detectProject } from '../project';\nimport { componentVariantTemplate } from '../templates';\nimport { c } from '../ui';\nimport type { Flags } from './init';\n\nconst KEY = /^[a-z0-9][a-z0-9_-]{0,63}$/;\n\nfunction str(v: unknown): string | undefined {\n return typeof v === 'string' && v.length > 0 ? v : undefined;\n}\nfunction list(v: unknown): string[] {\n if (Array.isArray(v)) return v.map(String);\n if (typeof v === 'string') return [v];\n return [];\n}\nfunction parsePairs(items: string[]): Record<string, string> {\n const out: Record<string, string> = {};\n for (const item of items) {\n const i = item.indexOf('=');\n if (i > 0) out[item.slice(0, i).trim()] = item.slice(i + 1);\n }\n return out;\n}\nfunction pascal(s: string): string {\n return s.replace(/(^|[-_])([a-z0-9])/g, (_, __, ch: string) => ch.toUpperCase());\n}\n\nasync function ask<T>(promise: Promise<T | symbol>): Promise<T> {\n const v = await promise;\n if (p.isCancel(v)) {\n p.cancel('Cancelled.');\n process.exit(0);\n }\n return v as T;\n}\n\nexport async function create(flags: Flags): Promise<void> {\n const json = Boolean(flags.json);\n const yes = Boolean(flags.yes);\n const project = detectProject();\n if (!project.configFile) throw new Error('splithub.config.ts not found. Run `npx splithub init` first.');\n const config = await loadConfig(project.configFile);\n const source = readSource(project.configFile);\n const interactive = !yes && !json;\n\n if (interactive) p.intro(c.bold('splithub create'));\n\n let kind = str(flags.kind) as ExperimentKind | undefined;\n if (!kind) {\n if (!interactive) throw new Error('--kind value|component|redirect|mvt is required with --yes');\n kind = await ask(\n p.select<ExperimentKind>({\n message: 'What changes between variants?',\n options: [\n { value: 'value', label: 'Text, image URL, number', hint: 'no new components' },\n { value: 'component', label: 'Layout / structure', hint: 'one component per variant' },\n { value: 'redirect', label: 'A whole page', hint: 'needs @splithub/next middleware' },\n { value: 'mvt', label: 'Several things at once', hint: 'multivariate: every combination, each factor read on its own' },\n ],\n })\n );\n }\n\n let id = str(flags.id);\n if (!id) {\n if (!interactive) throw new Error('--id is required with --yes');\n id = await ask(\n p.text({\n message: 'Experiment id',\n placeholder: 'hero-title',\n validate: (v) => (!KEY.test(v) ? 'lowercase a-z 0-9 - _ only' : hasExperiment(source, v) ? 'already exists' : undefined),\n })\n );\n }\n if (!KEY.test(id)) throw new Error(`invalid id \"${id}\" (lowercase a-z 0-9 - _, max 64)`);\n if (hasExperiment(source, id)) throw new Error(`experiment \"${id}\" already exists`);\n\n // Multivariate: --factor headline=old:Old,new:New (repeatable); the variants are the combinations.\n const factors: Record<string, Record<string, string>> = {};\n if (kind === 'mvt') {\n for (const raw of list(flags.factor)) {\n const eq = raw.indexOf('=');\n if (eq <= 0) throw new Error(`--factor expects name=level:value,level:value, got \"${raw}\"`);\n const name = raw.slice(0, eq).trim();\n const levels: Record<string, string> = {};\n for (const part of raw.slice(eq + 1).split(',')) {\n const colon = part.indexOf(':');\n const level = (colon >= 0 ? part.slice(0, colon) : part).trim();\n if (!level) continue;\n levels[level] = colon >= 0 ? part.slice(colon + 1).trim() : level;\n }\n factors[name] = levels;\n }\n while (interactive && Object.keys(factors).length === 0) {\n const name = await ask(p.text({ message: 'Factor name (what changes), e.g. headline', validate: (v) => (!KEY.test(v) ? 'lowercase a-z 0-9 - _ only' : undefined) }));\n const levelsRaw = await ask(p.text({ message: `Levels of \"${name}\" as key:value, comma separated (first = control)`, placeholder: 'old:Old headline, new:New headline' }));\n const levels: Record<string, string> = {};\n for (const part of levelsRaw.split(',')) {\n const colon = part.indexOf(':');\n const level = (colon >= 0 ? part.slice(0, colon) : part).trim();\n if (level) levels[level] = colon >= 0 ? part.slice(colon + 1).trim() : level;\n }\n factors[name] = levels;\n while (await ask(p.confirm({ message: 'Add another factor?', initialValue: false }))) {\n const more = await ask(p.text({ message: 'Factor name', validate: (v) => (!KEY.test(v) ? 'lowercase a-z 0-9 - _ only' : undefined) }));\n const moreRaw = await ask(p.text({ message: `Levels of \"${more}\" as key:value, comma separated`, placeholder: 'blue:#2563eb, green:#16a34a' }));\n const moreLevels: Record<string, string> = {};\n for (const part of moreRaw.split(',')) {\n const colon = part.indexOf(':');\n const level = (colon >= 0 ? part.slice(0, colon) : part).trim();\n if (level) moreLevels[level] = colon >= 0 ? part.slice(colon + 1).trim() : level;\n }\n factors[more] = moreLevels;\n }\n }\n if (Object.keys(factors).length === 0) throw new Error('--factor name=level:value,level:value is required for mvt experiments (repeat it per factor)');\n }\n const mvt = kind === 'mvt' ? mvtVariants(id, factors) : null;\n\n let variantKeys = mvt ? mvt.variants.map((v) => v.key) : str(flags.variants)?.split(',').map((s) => s.trim()).filter(Boolean);\n if (!variantKeys || variantKeys.length < 2) {\n if (!interactive) variantKeys = ['control', 'b'];\n else {\n const v = await ask(p.text({ message: 'Variant keys, comma separated (first = control)', initialValue: 'control, b' }));\n variantKeys = v.split(',').map((s) => s.trim()).filter(Boolean);\n }\n }\n for (const k of variantKeys) if (!KEY.test(k)) throw new Error(`invalid variant key \"${k}\"`);\n if (variantKeys.length < 2) throw new Error('need at least 2 variants');\n\n const weightsRaw = str(flags.weights)?.split(',').map(Number);\n const weights = weightsRaw && weightsRaw.length === variantKeys.length && weightsRaw.every((w) => Number.isFinite(w) && w >= 0) ? weightsRaw : variantKeys.map(() => 1);\n\n const values = parsePairs(list(flags.value));\n const tos = parsePairs(list(flags.to));\n if (kind === 'value' && interactive) {\n for (const k of variantKeys) {\n if (values[k] === undefined) values[k] = await ask(p.text({ message: `Value for \"${k}\"`, placeholder: k === variantKeys[0] ? 'current text' : 'new text' }));\n }\n }\n let match = str(flags.match);\n if (kind === 'redirect') {\n if (!match) {\n if (!interactive) throw new Error('--match /path is required for redirect experiments');\n match = await ask(p.text({ message: 'Path to run the redirect test on', initialValue: '/' }));\n }\n for (const k of variantKeys) {\n if (tos[k] === undefined) {\n if (!interactive) tos[k] = k === variantKeys[0] ? match : `${match.replace(/\\/$/, '')}/${k}`;\n else tos[k] = await ask(p.text({ message: `URL for \"${k}\"`, initialValue: k === variantKeys[0] ? match : '' }));\n }\n }\n }\n\n let goal = str(flags.goal);\n const goals = config.goals.map((g) => g.key);\n if (!goal) {\n if (!interactive) goal = goals[0];\n else if (goals.length > 0) {\n goal = await ask(\n p.select<string>({\n message: 'Goal (conversion) to optimise',\n options: [...goals.map((g) => ({ value: g, label: g })), { value: '', label: 'none yet (add later)' }],\n })\n );\n if (!goal) goal = undefined;\n }\n }\n if (goal && !goals.includes(goal)) throw new Error(`goal \"${goal}\" is not declared in splithub.config.ts goals: ${goals.join(', ') || 'none'}`);\n\n // Running by default: the test goes live with the deploy that ships its code, first page views included.\n const status = (str(flags.status) as ExperimentStatus | undefined) ?? 'running';\n const description = str(flags.description);\n\n const experiment: NewExperiment = {\n key: id,\n kind,\n status,\n goal,\n match,\n description,\n variants: mvt ? mvt.variants.map((v) => ({ key: v.key, weight: v.weight })) : variantKeys.map((k, i) => ({ key: k, weight: weights[i]!, value: values[k], to: tos[k] })),\n ...(mvt ? { factors } : {}),\n // limits: --traffic 50 (percent), --max-visitors 10000, --start / --end ISO dates\n traffic: typeof flags.traffic === 'string' && flags.traffic !== '' ? Math.min(1, Math.max(0, Number(flags.traffic) / 100)) : undefined,\n maxExposures: typeof flags['max-visitors'] === 'string' && Number(flags['max-visitors']) > 0 ? Math.floor(Number(flags['max-visitors'])) : undefined,\n schedule: typeof flags.start === 'string' || typeof flags.end === 'string' ? { startAt: typeof flags.start === 'string' ? flags.start : null, endAt: typeof flags.end === 'string' ? flags.end : null } : undefined,\n };\n\n writeSource(project.configFile, insertExperiment(source, experiment));\n\n const files: string[] = [];\n const componentNames: Record<string, string> = {};\n if (kind === 'component') {\n const dir = join(project.root, project.hasSrc ? 'src/splithub' : 'splithub', id);\n mkdirSync(dir, { recursive: true });\n for (const k of variantKeys) {\n const name = `${pascal(id)}${pascal(k)}`;\n componentNames[k] = name;\n const file = join(dir, `${pascal(k)}.tsx`);\n if (!existsSync(file)) {\n writeFileSync(file, componentVariantTemplate(name, id, k), 'utf8');\n files.push(relative(project.root, file));\n }\n }\n }\n\n const snippet =\n kind === 'mvt'\n ? `const { ${Object.keys(factors).join(', ')} } = useValue<{ ${Object.keys(factors).map((f) => `${f}: string`).join('; ')} }>('${id}');`\n : kind === 'value'\n ? `const value = useValue<string>('${id}');`\n : kind === 'component'\n ? `<Experiment id=\"${id}\">\\n${variantKeys.map((k) => ` <Variant name=\"${k}\"><${componentNames[k]} /></Variant>`).join('\\n')}\\n</Experiment>`\n : `// handled by @splithub/next middleware on ${match}; no code needed`;\n\n const result = { experiment: id, kind, status, variants: experiment.variants, goal: goal ?? null, configFile: relative(project.root, project.configFile), files, snippet };\n if (json) {\n const cloudMode = /mode\\s*:\\s*['\"]cloud['\"]/.test(readSource(project.configFile));\n // Agents read this JSON: the hand-off line makes sure the human learns the test is not live yet.\n const handoff =\n status === 'draft'\n ? `${id} is a draft: visitors do not see it and nothing is recorded until it is started. Tell the user and ask whether to start it now (npx splithub start ${id}).`\n : `${id} is running in the config: it goes live for visitors when this code is deployed${cloudMode ? ' and pushed; local development never sends events to the cloud' : ''}. Tell the user, and that npx splithub pause ${id} or Pause in the dashboard holds it.`;\n const nextStep = cloudMode ? `npx splithub push # the cloud does not know about ${id} until you push` : status === 'draft' ? `npx splithub start ${id}` : 'deploy the app';\n console.log(JSON.stringify({ ...result, nextStep, handoff }, null, 2));\n return;\n }\n p.note(snippet, kind === 'redirect' ? 'Nothing to wire' : 'Wire it in your code');\n if (files.length) p.note(files.join('\\n'), 'Scaffolded');\n const cloud = /mode\\s*:\\s*['\"]cloud['\"]/.test(readSource(project.configFile));\n if (cloud) p.log.warn(`Cloud mode: the cloud does not know about it until you run ${c.cyan('npx splithub push')}.`);\n if (status === 'draft') p.log.warn(`${c.bold(id)} is a draft: visitors do not see it and nothing is recorded until you start it.`);\n if (status === 'running') p.log.info(`${c.bold(id)} goes live when you deploy this code. Check it first with ${c.cyan(`?sh_force=${id}:<variant>`)}; ${c.cyan(`npx splithub pause ${id}`)} holds it.`);\n if (status === 'draft') p.log.info(`See it before you start it: ${c.cyan('runDraftsInDev: true')} in the config serves drafts in development, ${c.cyan(`?sh_force=${id}:<variant>`)} shows one variant anywhere.`);\n p.outro(`Added ${c.bold(id)} (${status}) to ${relative(project.root, project.configFile)}. ${status === 'running' ? '' : `Start it with ${c.cyan(`npx splithub start ${id}`)}. `}${cloud ? `Then ${c.cyan('npx splithub push')}.` : ''}`);\n}\n","import { isSplitHubConfig, type ExperimentKind, type ExperimentStatus, type SplitHubConfig } from '@splithub/core';\nimport { readFileSync, writeFileSync } from 'node:fs';\nimport { pathToFileURL } from 'node:url';\n\n/** Load splithub.config.ts (TypeScript or JS) through jiti. */\nexport async function loadConfig(file: string): Promise<SplitHubConfig> {\n const { createJiti } = await import('jiti');\n const jiti = createJiti(pathToFileURL(file).href, { fsCache: false, moduleCache: false });\n const mod = (await jiti.import(file, { default: true })) as unknown;\n if (!isSplitHubConfig(mod)) {\n throw new Error(`${file} must \\`export default defineConfig({...})\\` from @splithub/core.`);\n }\n return mod;\n}\n\nfunction keyPattern(key: string): RegExp {\n const esc = key.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp(`(^|\\\\n)([ \\\\t]*)(['\"]?)${esc}\\\\3[ \\\\t]*:[ \\\\t]*\\\\{`);\n}\n\n/** Index of the `}` closing the object that opens at `open`. Skips strings and `//` comments. */\nfunction findObjectEnd(source: string, open: number): number | null {\n let depth = 0;\n let inStr: string | null = null;\n let inLineComment = false;\n for (let i = open; i < source.length; i++) {\n const ch = source[i]!;\n if (inLineComment) {\n if (ch === '\\n') inLineComment = false;\n continue;\n }\n if (inStr) {\n if (ch === '\\\\') i++;\n else if (ch === inStr) inStr = null;\n continue;\n }\n if (ch === '/' && source[i + 1] === '/') {\n inLineComment = true;\n continue;\n }\n if (ch === \"'\" || ch === '\"' || ch === '`') inStr = ch;\n else if (ch === '{') depth++;\n else if (ch === '}') {\n depth--;\n if (depth === 0) return i;\n }\n }\n return null;\n}\n\n/** Find the `{ ... }` body of an experiment entry. Returns [openIndex, closeIndex]. */\nfunction findExperimentBlock(source: string, key: string): [number, number] | null {\n const expIdx = source.search(/experiments\\s*:\\s*\\{/);\n if (expIdx < 0) return null;\n const m = keyPattern(key).exec(source.slice(expIdx));\n if (!m) return null;\n const open = expIdx + m.index + m[0].length - 1;\n const close = findObjectEnd(source, open);\n return close === null ? null : [open, close];\n}\n\nexport function hasExperiment(source: string, key: string): boolean {\n return findExperimentBlock(source, key) !== null;\n}\n\nexport interface NewExperiment {\n key: string;\n kind: ExperimentKind;\n status: ExperimentStatus;\n variants: Array<{ key: string; weight: number; value?: string; to?: string }>;\n /** Multivariate: factor → level → value; the variants are derived and not written. */\n factors?: Record<string, Record<string, string>>;\n goal?: string;\n match?: string;\n description?: string;\n /** Targeting graph from the dashboard, written verbatim as JSON. */\n flow?: unknown;\n traffic?: number;\n maxExposures?: number;\n schedule?: { startAt?: string | null; endAt?: string | null };\n}\n\n/** Single-quoted string literal. */\nfunction q(s: string): string {\n return `'${s.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`;\n}\n\n/** Object key: bare when it is a valid identifier, quoted otherwise. */\nfunction k(s: string): string {\n return /^[a-z_$][\\w$]*$/i.test(s) ? s : q(s);\n}\n\n/** Render an experiment entry. Every line after the first carries its own indentation. */\nexport function renderExperiment(e: NewExperiment, indent = ' '): string {\n const i2 = indent + ' ';\n const i3 = i2 + ' ';\n const lines: string[] = [`${k(e.key)}: {`];\n lines.push(`${i2}kind: ${q(e.kind)},`);\n lines.push(`${i2}status: ${q(e.status)},`);\n if (e.match) lines.push(`${i2}match: ${q(e.match)},`);\n if (e.kind === 'mvt') {\n lines.push(`${i2}factors: {`);\n for (const [factor, levels] of Object.entries(e.factors ?? {})) {\n lines.push(`${i3}${k(factor)}: { ${Object.entries(levels).map(([l, v]) => `${k(l)}: ${q(v)}`).join(', ')} },`);\n }\n lines.push(`${i2}},`);\n } else if (e.kind === 'component') {\n lines.push(`${i2}variants: { ${e.variants.map((v) => `${k(v.key)}: ${v.weight}`).join(', ')} },`);\n } else {\n lines.push(`${i2}variants: {`);\n for (const v of e.variants) {\n const extra = e.kind === 'value' ? `value: ${q(v.value ?? '')}` : `to: ${q(v.to ?? '/')}`;\n lines.push(`${i3}${k(v.key)}: { weight: ${v.weight}, ${extra} },`);\n }\n lines.push(`${i2}},`);\n }\n if (e.goal) lines.push(`${i2}goal: ${q(e.goal)},`);\n if (e.traffic !== undefined && e.traffic !== 1) lines.push(`${i2}traffic: ${e.traffic},`);\n if (e.maxExposures) lines.push(`${i2}maxExposures: ${e.maxExposures},`);\n if (e.schedule && (e.schedule.startAt || e.schedule.endAt)) lines.push(`${i2}schedule: { ${[e.schedule.startAt ? `startAt: ${q(e.schedule.startAt)}` : null, e.schedule.endAt ? `endAt: ${q(e.schedule.endAt)}` : null].filter(Boolean).join(', ')} },`);\n if (e.description) lines.push(`${i2}description: ${q(e.description)},`);\n if (e.flow) {\n const json = JSON.stringify(e.flow, null, 2).split('\\n');\n lines.push(`${i2}// targeting graph from the dashboard; edit it there or by hand\\n${i2}flow: ${json.map((l, n) => (n === 0 ? l : i2 + l)).join('\\n')},`);\n }\n lines.push(`${indent}}`);\n return lines.join('\\n');\n}\n\n/** Append a new experiment at the end of the `experiments: { ... }` object. */\nexport function insertExperiment(source: string, e: NewExperiment): string {\n const m = /experiments\\s*:\\s*\\{/.exec(source);\n if (!m) throw new Error('could not find `experiments: {` in the config file.');\n const open = m.index + m[0].length - 1;\n const close = findObjectEnd(source, open);\n if (close === null) throw new Error('unbalanced braces after `experiments: {`.');\n\n const lineStart = source.lastIndexOf('\\n', close) + 1;\n const closeIndent = /^[ \\t]*/.exec(source.slice(lineStart, close))?.[0] ?? ' ';\n const indent = closeIndent + ' ';\n\n // Does the previous entry end with a comma? Ignore whitespace and // comments.\n const before = source\n .slice(open + 1, lineStart)\n .replace(/\\/\\/[^\\n]*/g, '')\n .trimEnd();\n const needsComma = before.length > 0 && !before.endsWith(',');\n\n const block = `${indent}${renderExperiment(e, indent)},\\n`;\n const head = source.slice(0, lineStart);\n return `${needsComma ? addTrailingComma(head) : head}${block}${source.slice(lineStart)}`;\n}\n\n/** Append a comma to the last code line of `head`, skipping blank and `//` comment lines. */\nfunction addTrailingComma(head: string): string {\n const lines = head.split('\\n');\n for (let i = lines.length - 1; i >= 0; i--) {\n const line = lines[i]!;\n const trimmed = line.trim();\n if (trimmed === '' || trimmed.startsWith('//')) continue;\n const commentAt = line.indexOf('//');\n const code = commentAt >= 0 ? line.slice(0, commentAt) : line;\n const rest = commentAt >= 0 ? line.slice(commentAt) : '';\n const codeTrimmed = code.trimEnd();\n lines[i] = `${codeTrimmed},${code.slice(codeTrimmed.length)}${rest}`;\n break;\n }\n return lines.join('\\n');\n}\n\nexport function setExperimentStatus(source: string, key: string, status: ExperimentStatus): string {\n const block = findExperimentBlock(source, key);\n if (!block) throw new Error(`experiment \"${key}\" not found in the config file.`);\n const [open, close] = block;\n const body = source.slice(open, close + 1);\n const re = /(status\\s*:\\s*)(['\"])[a-z]+\\2/;\n if (!re.test(body)) throw new Error(`experiment \"${key}\" has no \\`status\\` field.`);\n const updated = body.replace(re, `$1$2${status}$2`);\n return source.slice(0, open) + updated + source.slice(close + 1);\n}\n\nexport function readSource(file: string): string {\n return readFileSync(file, 'utf8');\n}\n\nexport function writeSource(file: string, source: string): void {\n writeFileSync(file, source, 'utf8');\n}\n","import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\n\nexport type Framework = 'next' | 'vite' | 'unknown';\nexport type PackageManager = 'pnpm' | 'yarn' | 'bun' | 'npm';\n\nexport interface ProjectInfo {\n root: string;\n name: string;\n framework: Framework;\n packageManager: PackageManager;\n /** Next.js app directory (`app` or `src/app`), when present. */\n appDir: string | null;\n /** Whether sources live under `src/`. */\n hasSrc: boolean;\n configFile: string | null;\n typescript: boolean;\n}\n\nconst CONFIG_NAMES = ['splithub.config.ts', 'splithub.config.mts', 'splithub.config.js', 'splithub.config.mjs'];\n\nexport function findConfigFile(root: string): string | null {\n for (const name of CONFIG_NAMES) {\n const p = join(root, name);\n if (existsSync(p)) return p;\n }\n return null;\n}\n\nexport function detectProject(cwd = process.cwd()): ProjectInfo {\n const root = resolve(cwd);\n let name = 'my-app';\n let deps: Record<string, string> = {};\n try {\n const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { name?: string; dependencies?: Record<string, string>; devDependencies?: Record<string, string> };\n name = pkg.name ?? name;\n deps = { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) };\n } catch {\n // no package.json: still usable\n }\n const has = (file: string) => existsSync(join(root, file));\n const framework: Framework = deps.next || has('next.config.js') || has('next.config.mjs') || has('next.config.ts')\n ? 'next'\n : deps.vite || has('vite.config.ts') || has('vite.config.js') || has('vite.config.mjs')\n ? 'vite'\n : 'unknown';\n const packageManager: PackageManager = has('pnpm-lock.yaml') ? 'pnpm' : has('yarn.lock') ? 'yarn' : has('bun.lockb') || has('bun.lock') ? 'bun' : 'npm';\n const appDir = has('src/app') ? 'src/app' : has('app') ? 'app' : null;\n return {\n root,\n name: name.replace(/^@[^/]+\\//, ''),\n framework,\n packageManager,\n appDir,\n hasSrc: has('src'),\n configFile: findConfigFile(root),\n typescript: has('tsconfig.json'),\n };\n}\n\nexport function installCommand(pm: PackageManager, packages: string[], dev = false): string {\n const flag = dev ? (pm === 'npm' ? ' -D' : ' -D') : '';\n switch (pm) {\n case 'pnpm':\n return `pnpm add${flag} ${packages.join(' ')}`;\n case 'yarn':\n return `yarn add${flag} ${packages.join(' ')}`;\n case 'bun':\n return `bun add${dev ? ' -d' : ''} ${packages.join(' ')}`;\n default:\n return `npm install${flag} ${packages.join(' ')}`;\n }\n}\n\nconst SKIP_DIRS = new Set(['node_modules', '.next', 'dist', 'build', '.git', 'coverage', 'out', '.turbo']);\nconst CODE_EXT = /\\.(tsx?|jsx?|mjs|cjs|mts|cts)$/;\n\n/** Source files of the project (shallow enough for a doctor run). */\nexport function listSourceFiles(root: string, maxFiles = 5000): string[] {\n const out: string[] = [];\n const walk = (dir: string, depth: number) => {\n if (out.length >= maxFiles || depth > 8) return;\n let entries: string[];\n try {\n entries = readdirSync(dir);\n } catch {\n return;\n }\n for (const entry of entries) {\n if (SKIP_DIRS.has(entry)) continue;\n const full = join(dir, entry);\n let st;\n try {\n st = statSync(full);\n } catch {\n continue;\n }\n if (st.isDirectory()) walk(full, depth + 1);\n else if (CODE_EXT.test(entry)) out.push(full);\n }\n };\n walk(root, 0);\n return out;\n}\n\nexport function grepFiles(files: string[], needle: string): string[] {\n const hits: string[] = [];\n for (const f of files) {\n try {\n if (readFileSync(f, 'utf8').includes(needle)) hits.push(f);\n } catch {\n // unreadable file\n }\n }\n return hits;\n}\n","// Skill: SplitHub with the user's own database (self mode) and reporting from the cloud.\nexport const SKILL_SELF_HOSTED = `---\nname: splithub-self-hosted\ndescription: Keep SplitHub 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# SplitHub 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 SplitHub 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- 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- Compute winners from raw rates in SQL; use \\`npx splithub results\\` (or \\`@splithub/stats\\`) for the verdict.\n`;\n","// Skill: ship the winner and take the experiment out of the code. Installed\n// next to the other skills by `splithub init` / `splithub skills`.\n\nexport const SKILL_SHIP = `---\nname: splithub-ship\ndescription: Ship the winner of an A/B test and remove the test 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 a test has a verdict and the user says ship it, roll out the winner, remove the test, or clean up; and whenever a test 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 winning variant did, with no experiment left in the code or in the config.\n\n## Before touching code\n\n1. Read the verdict: \\`npx splithub results <id> --json\\`. Act on \\`verdict.status\\`:\n - \\`winner_found\\`: ship \\`verdict.winner\\`.\n - \\`no_significant_difference\\` with enough sample: keep the control, or the simpler variant if the user agrees.\n - \\`insufficient_sample\\`: do not ship. Say roughly how many more visitors are needed (\\`sample.neededPerVariant\\`).\n - \\`srm_detected\\`: do not ship. The split is broken; fix the setup first.\n2. Finish the experiment first so new visitors stop entering: \\`npx splithub finish <id>\\`. Results stay readable afterwards.\n\n## Per kind\n\n- **value** (\\`useValue('<id>')\\`, \\`sh.value('<id>')\\`, \\`getValue\\`): replace every call with the winning literal (text, number, JSON).\n Remove imports that become unused.\n- **component** (\\`<Experiment id=\"<id>\">\\` with \\`<Variant>\\` children, or a \\`useVariant('<id>')\\` switch): keep the winning branch\n inline where the wrapper was, delete the other branches and the wrapper. Delete components, files and styles only the losing\n variants used.\n- **redirect** (the winner is a URL): if a new page won, make it the real page: serve the winning content at the original path\n (move the route, or add a permanent redirect from the old path), delete the losing page, update internal links and the sitemap.\n If the control won, delete the new page and its route. Remove the experiment's \\`match\\`.\n- **drop-in script sites** (no SDK): nothing to change in code; remove the test from the config or the dashboard.\n\n## Config and cloud\n\n3. Remove the experiment from \\`experiments\\` in \\`splithub.config.ts\\`. Keep the goal if another test uses it. Cloud mode:\n \\`npx splithub push\\`. Tests created in the dashboard (\"cloud\" badge): finished is enough, or delete them there.\n4. Keep \\`track('<goal>')\\` calls when the goal is still in use; remove them only if nothing else measures that goal.\n\n## Verify and report\n\n5. \\`npx splithub doctor\\`, then the project's typecheck and tests. Grep for the experiment id: nothing should reference it.\n6. Report what changed (files, the winning content) and the verdict in one line with its numbers.\n7. Never reuse the experiment id for a new test: the history belongs to the old one.\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// 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 A/B experiments in an app that uses SplitHub (@splithub/react, splithub.config.ts, the splithub CLI, SplitHub 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 a test.\n---\n\n# SplitHub 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 SplitHub 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; \\`npx splithub pull\\` writes dashboard-created experiments into the file.\n- Results: \\`npx splithub status --json\\`, \\`npx splithub results <id> --json\\`.\n- Everything interactive: \\`npx splithub\\` (menu). Everything scriptable: subcommands + \\`--json\\`.\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.splithub.io/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 an A/B test: 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, test one thing with \\`value\\`.\n\n## Create an experiment\n\n1. \\`npx splithub create --kind <value|component|redirect|mvt> --id <key> … --goal <goal> --yes --json\\` (see the table).\n2. Goal: pick an existing key or add one to \\`goals\\`:\n \\`{ type: 'event' }\\` + \\`track('<goal>')\\` where the conversion happens; \\`{ type: 'pageview', path: '/thanks' }\\`;\n \\`{ type: 'click', selector: '#buy' }\\` (tracked automatically by the SDK and the script).\n3. Wire it in code. \\`create\\` writes \\`status: 'running'\\`: the test 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 test 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 tests 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 tests 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, p-value, CI).\nNever declare a winner from raw rates. \\`srm_detected\\` means the split is broken: fix the setup before anything else.\n\n## Finish, and what to do when a test is finished\n\n\\`npx splithub finish <id>\\` stops the test (live within a minute in cloud mode). A finished test 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 a test 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 test from the code now**.\n3. On yes, follow the \\`splithub-ship\\` skill: keep only the chosen variant's content, delete the other variants' code and\n files, remove the entry from \\`splithub.config.ts\\`, \\`push\\` in cloud mode, run \\`doctor\\` and the project's checks.\n4. On no, leave everything: a finished test costs nothing and the user may come back to it.\n\nA \\`paused\\` test is not over: say so and ask whether to resume (\\`start\\`) or finish it.\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 A/B test 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 A/B test 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 a test\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, test a bigger change or a higher-traffic page.\n4. **Few tests per page.** Interactions between simultaneous tests 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 test.\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 test, 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 test.\n- The business moved on → finish; do not leave tests 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 SplitHub Cloud HTTP API directly: public key event ingest, API-key endpoints for config, status, results and overrides, hosted experiments. Use when writing a server, a script, a non-JS client, or when the CLI is not available.\n---\n\n# SplitHub Cloud API\n\nBase URL: \\`https://go.splithub.io\\`. 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.\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- \\`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. \\`403 origin_not_allowed\\` when the project restricts domains.\n- Exposures for experiments that are not running are dropped and not billed. Goals are never billed.\n\n## Live config for clients (public key)\n\n\\`GET /v1/overrides/<pk>.json\\` → \\`{ 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\nGET /v1/config the config stored in the cloud (file + dashboard experiments)\nPUT /v1/config { config } push a normalized config (what defineConfig returns); answers cloudOnly experiments to adopt\nGET /v1/overrides live overrides\nPUT /v1/overrides/<experiment> { status | traffic | weights | values } pause / resume / reweight without a deploy\nDELETE /v1/overrides/<experiment>\n\\`\\`\\`\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\\`, \\`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.splithub.io/sh.js\" data-key=\"pk_live_…\"></script>\\` in \\`<head>\\`: redirect experiments, page-visit and\nclick goals from the cloud config, \\`window.splithub.track('goal')\\` for custom events,\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, \\`404\\` unknown experiment/project, \\`409\\` state\n(e.g. \\`config_not_pushed\\`, \\`file_owned\\`), \\`429\\` gate or rate limit. Bodies: \\`{ error, code? }\\`.\n`;\n\nexport const SKILL_SPLITHUB_MCP = `---\nname: splithub-mcp\ndescription: Use or set up the SplitHub MCP server (@splithub/mcp) so an agent can create experiments, read verdicts, start/pause/finish tests and push config through tools instead of shelling out. Use when the user asks to connect SplitHub to Claude Code, Cursor, Codex or another MCP client.\n---\n\n# SplitHub 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 | report \\`verdict.message\\` verbatim |\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_create_experiment\\` | adds an experiment to splithub.config.ts | kind value / component / redirect / mvt, id, variants (or factors for mvt), goal, values/to; starts as draft |\n| \\`splithub_set_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\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- If a tool answers that the folder is not connected, call \\`splithub_login\\`, show the link to the user, wait for them, then retry.\n- A \\`finished\\` experiment in \\`splithub_status\\` or \\`splithub_results\\` means the test is over but its code is still there: report\n the verdict, ask which variant to keep and whether to remove the test 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_SHIP } from './skills-ship';\nimport { SKILL_SHIP } from './skills-ship';\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];\n\nexport const MCP_SERVER_ENTRY = { command: 'npx', args: ['-y', '@splithub/mcp'] };\n","export function configTemplate(project: string, mode: 'self' | 'cloud', key?: string): string {\n const storage = mode === 'self' ? `{ mode: 'self', endpoint: '/api/splithub' }` : `{ mode: 'cloud', key: ${key ? `'${key}'` : \"process.env.NEXT_PUBLIC_SPLITHUB_KEY ?? ''\"} }`;\n return `import { defineConfig } from '@splithub/core';\n\n// SplitHub 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.\nexport default defineConfig({\n project: '${project}',\n storage: ${storage},\n // Drafts behave like running tests while you develop (next dev, vite); production ignores them.\n runDraftsInDev: true,\n\n goals: {\n // call track('signup') where the conversion happens\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 (SplitHub)\n\nThis project uses SplitHub (\\`@splithub/react\\`). Experiments are declared in\n\\`splithub.config.ts\\` and rendered with \\`<Experiment id>\\` / \\`useVariant(id)\\` /\n\\`useValue(id)\\`. Conversions: \\`useTrack()\\` then \\`track('<goal>')\\`.\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 <goal> --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\\` test still has all its variants in the code: report the verdict, ask which variant to keep and whether to\n remove the test from the code, then follow .claude/skills/splithub-ship/SKILL.md. Never delete test code unasked.\n- \\`create\\` writes \\`status: 'running'\\`: the test 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- 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: SplitHub A/B testing conventions\nglobs: [\"splithub.config.ts\", \"splithub/**\", \"**/*.tsx\"]\nalwaysApply: false\n---\n${SKILL_SPLITHUB.replace(/^---[\\s\\S]*?---\\n/, '')}`;\n","const enabled = process.stdout.isTTY && !process.env.NO_COLOR;\nconst wrap = (open: number, close: number) => (s: string) => (enabled ? `\\u001b[${open}m${s}\\u001b[${close}m` : s);\n\nexport const c = {\n bold: wrap(1, 22),\n dim: wrap(2, 22),\n red: wrap(31, 39),\n green: wrap(32, 39),\n yellow: wrap(33, 39),\n blue: wrap(34, 39),\n magenta: wrap(35, 39),\n cyan: wrap(36, 39),\n};\n\nexport function table(headers: string[], rows: string[][]): string {\n const widths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) => strip(r[i] ?? '').length)));\n const line = (cells: string[]) => cells.map((cell, i) => cell + ' '.repeat(widths[i]! - strip(cell).length)).join(' ');\n return [c.dim(line(headers)), ...rows.map(line)].join('\\n');\n}\n\nexport function strip(s: string): string {\n // eslint-disable-next-line no-control-regex\n return s.replace(/\\u001b\\[\\d+m/g, '');\n}\n\nexport function pct(x: number | null | undefined, signed = false): string {\n if (x === null || x === undefined || !Number.isFinite(x)) return '–';\n const v = (x * 100).toFixed(1);\n return signed && x >= 0 ? `+${v}%` : `${v}%`;\n}\n\nexport function statusColor(status: string): string {\n switch (status) {\n case 'running':\n return c.green(status);\n case 'paused':\n return c.yellow(status);\n case 'finished':\n return c.blue(status);\n default:\n return c.dim(status);\n }\n}\n\n/** One plain glyph per verdict (no emoji: terminals and CI logs render these everywhere). */\nexport function verdictIcon(status: string | null | undefined): string {\n switch (status) {\n case 'winner_found':\n return '★';\n case 'srm_detected':\n return '!';\n case 'insufficient_sample':\n return '…';\n case 'no_significant_difference':\n return '=';\n default:\n return '·';\n }\n}\n\n/** A horizontal bar: filled blocks for value / max, dim blocks for the rest. */\nexport function bar(value: number, max: number, width = 20, paint: (s: string) => string = c.green): string {\n const n = max > 0 ? Math.max(0, Math.min(width, Math.round((value / max) * width))) : 0;\n return paint('█'.repeat(n)) + c.dim('░'.repeat(width - n));\n}\n\nexport function verdictColor(status: string | null, text: string): string {\n switch (status) {\n case 'winner_found':\n return c.green(text);\n case 'srm_detected':\n return c.red(text);\n case 'insufficient_sample':\n return c.yellow(text);\n case 'no_significant_difference':\n return c.cyan(text);\n default:\n return c.dim(text);\n }\n}\n","// splithub dev — test experiments locally with full visibility.\n//\n// splithub dev opens the app (localhost:3000 for Next.js, 5173 for Vite) with ?sh_debug=1\n// splithub dev --url http://… a different page\n// splithub dev --hold redirect experiments log the target instead of navigating\n// splithub dev --no-open only print the link and watch\n//\n// With ?sh_debug the SDK and the drop-in script log every decision (which\n// variant and why), every exposure and goal with its payload, and the remote\n// overrides they applied, in the browser console and in a floating panel that\n// can force a variant, start a new visitor or hold redirects. Meanwhile this\n// command polls `status` and prints new visitors / conversions as they land.\n\nimport { spawn } from 'node:child_process';\nimport { fetchStatus, resolveTarget } from '../api';\nimport { detectProject } from '../project';\nimport { c } from '../ui';\n\nfunction openBrowser(url: string): void {\n const [cmd, args] = process.platform === 'win32' ? ['cmd', ['/c', 'start', '', url]] : process.platform === 'darwin' ? ['open', [url]] : ['xdg-open', [url]];\n try {\n spawn(cmd, args, { stdio: 'ignore', detached: true }).unref();\n } catch {\n // no browser available: the link is printed anyway\n }\n}\n\nexport async function dev(flags: Record<string, unknown>): Promise<void> {\n const project = detectProject();\n const port = project?.framework === 'next' ? 3000 : 5173;\n const page = (typeof flags.url === 'string' && flags.url) || `http://localhost:${port}/`;\n const u = new URL(page);\n u.searchParams.set('sh_debug', flags.hold ? 'hold' : '1');\n const link = u.toString();\n\n console.log(`${c.bold('SplitHub dev mode')}\\n`);\n console.log(` ${c.cyan(link)}\\n`);\n console.log(c.dim(' In the browser: the console shows every assignment (variant + reason), exposure and goal; the panel'));\n console.log(c.dim(' in the corner forces variants, starts a new visitor and can hold redirects. Add ?sh_debug=0 to stop.\\n'));\n if (!flags['no-open']) openBrowser(link);\n\n const target = resolveTarget(flags, project);\n console.log(c.dim(` Watching ${target.url} every 5 s. Ctrl+C to stop.\\n`));\n const seen = new Map<string, { visitors: number; headline: string | null }>();\n let first = true;\n const poll = async () => {\n let data: Awaited<ReturnType<typeof fetchStatus>>;\n try {\n data = await fetchStatus(target);\n } catch (e) {\n if (first) console.log(c.yellow(` results endpoint not reachable yet (${e instanceof Error ? e.message : String(e)}); is the dev server running?`));\n first = false;\n return;\n }\n const now = new Date().toLocaleTimeString();\n for (const e of data.experiments) {\n const prev = seen.get(e.experiment);\n if (!prev) console.log(` ${c.dim(now)} ${c.bold(e.experiment)} ${c.dim(e.status)} · ${e.visitors} visitors${e.headline ? ` · ${e.headline}` : ''}`);\n else if (prev.visitors !== e.visitors || prev.headline !== (e.headline ?? null)) console.log(` ${c.dim(now)} ${c.bold(e.experiment)} ${c.green(`+${e.visitors - prev.visitors}`)} → ${e.visitors} visitors${e.headline ? ` · ${e.headline}` : ''}`);\n seen.set(e.experiment, { visitors: e.visitors, headline: e.headline ?? null });\n }\n first = false;\n };\n await poll();\n await new Promise<void>((resolve) => {\n const t = setInterval(() => void poll(), 5000);\n process.on('SIGINT', () => {\n clearInterval(t);\n resolve();\n });\n });\n}\n","import type { ExperimentResults, StatusRow } from '@splithub/node';\nimport { readFileSync } from 'node:fs';\nimport { loadCredential } from './credentials';\nimport type { ProjectInfo } from './project';\n\nexport interface Target {\n url: string;\n token?: string;\n}\n\nexport const CLOUD_API = 'https://go.splithub.io/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 };\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 };\n}\n\n/**\n * Readable message from an API error body. Most routes answer `{ error: 'text' }`; the auth layer\n * answers `{ success: false, error: { code, message } }`. Without this the CLI printed \"[object Object]\".\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\nasync function get<T>(target: Target, path: string): Promise<T> {\n const headers: Record<string, string> = {};\n if (target.token) headers.authorization = `Bearer ${target.token}`;\n let res: Response;\n try {\n res = await fetch(`${target.url}${path}`, { headers });\n } catch (error) {\n throw new Error(`cannot reach ${target.url}: ${error instanceof Error ? error.message : String(error)}. Is your app running? Set --url or SPLITHUB_URL.`);\n }\n if (!res.ok) {\n const body: unknown = await res.json().catch(() => ({}));\n throw new Error(apiErrorMessage(res.status, body, `${target.url}${path} responded ${res.status}`));\n }\n return (await res.json()) as T;\n}\n\nexport const fetchStatus = (t: Target) => get<{ project: string; experiments: StatusRow[] }>(t, '/status');\nexport const fetchResults = (t: Target, key: string) => get<ExperimentResults>(t, `/results/${encodeURIComponent(key)}`);\n","// 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 { existsSync, readFileSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport { resolveTarget } from '../api';\nimport { loadConfig } from '../config-file';\nimport { detectProject, grepFiles, listSourceFiles } from '../project';\nimport { c } from '../ui';\nimport type { Flags } from './init';\n\ntype Level = 'ok' | 'warn' | 'error';\ninterface Check {\n level: Level;\n message: string;\n}\n\nexport async function doctor(flags: Flags): Promise<void> {\n const checks: Check[] = [];\n const add = (level: Level, message: string) => checks.push({ level, message });\n const project = detectProject();\n\n add('ok', `project \"${project.name}\" · ${project.framework} · ${project.packageManager}`);\n\n if (!project.configFile) {\n add('error', 'splithub.config.ts not found. Run `npx splithub init`.');\n return report(checks, flags);\n }\n add('ok', `config: ${relative(project.root, project.configFile)}`);\n\n let config;\n try {\n config = await loadConfig(project.configFile);\n add('ok', `config loads · ${config.experiments.length} experiment(s) · storage ${config.storage.mode}`);\n } catch (error) {\n add('error', `config does not load: ${error instanceof Error ? error.message : String(error)}`);\n return report(checks, flags);\n }\n\n const files = listSourceFiles(project.root);\n const providerHits = grepFiles(files, 'SplitHubProvider').concat(grepFiles(files, 'SplitHubNextProvider'));\n if (providerHits.length === 0) add('error', 'no <SplitHubProvider> found in source. Wrap your app once.');\n else add('ok', `provider in ${relative(project.root, providerHits[0]!)}`);\n\n if (project.framework === 'next') {\n const mw = ['middleware.ts', 'src/middleware.ts', 'middleware.js', 'src/middleware.js'].map((f) => join(project.root, f)).find((f) => existsSync(f));\n const hasRedirects = config.experiments.some((e) => e.kind === 'redirect');\n if (!mw) add(hasRedirects ? 'error' : 'warn', 'no middleware.ts: visitor cookie is not set on the server (SSR may flicker)' + (hasRedirects ? '; redirect experiments will not run' : ''));\n else if (!readFileSync(mw, 'utf8').includes('splithubMiddleware')) add('warn', `${relative(project.root, mw)} does not call splithubMiddleware()`);\n else add('ok', `middleware: ${relative(project.root, mw)}`);\n if (config.storage.mode === 'self' && project.appDir) {\n const catchAll = join(project.root, project.appDir, 'api/splithub/[[...path]]/route.ts');\n const plain = join(project.root, project.appDir, 'api/splithub/route.ts');\n if (existsSync(catchAll)) add('ok', `ingest route: ${relative(project.root, catchAll)}`);\n else if (existsSync(plain)) add('error', `${relative(project.root, plain)} only serves POST /api/splithub; move it to api/splithub/[[...path]]/route.ts so /status and /results work`);\n else add('error', `self mode but ${relative(project.root, catchAll)} is missing (ingest endpoint)`);\n }\n }\n\n for (const exp of config.experiments) {\n const label = `${exp.key} (${exp.kind}, ${exp.status})`;\n if (!exp.goal) add(exp.status === 'running' ? 'error' : 'warn', `${label}: no goal; the verdict cannot be computed`);\n if (exp.kind !== 'redirect') {\n const used = grepFiles(files.filter((f) => !f.endsWith('splithub.config.ts')), `'${exp.key}'`).length + grepFiles(files, `\"${exp.key}\"`).length;\n if (used === 0) add(exp.status === 'running' ? 'error' : 'warn', `${label}: not referenced in code (useValue/useVariant/<Experiment id>)`);\n }\n if (exp.status === 'running' && exp.variants.every((v) => v.weight === 0)) add('error', `${label}: all weights are 0`);\n }\n for (const goal of config.goals) {\n if (goal.type === 'event' && grepFiles(files, `'${goal.key}'`).length + grepFiles(files, `\"${goal.key}\"`).length === 0) {\n add('warn', `goal \"${goal.key}\": track('${goal.key}') is never called`);\n }\n }\n\n const target = resolveTarget(flags, project);\n try {\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), 2500);\n const res = await fetch(`${target.url}/health`, { signal: ctrl.signal });\n clearTimeout(t);\n add(res.ok ? 'ok' : 'warn', `endpoint ${target.url}/health → ${res.status}`);\n } catch {\n add('warn', `endpoint ${target.url} not reachable (is the dev server running?)`);\n }\n\n return report(checks, flags);\n}\n\nfunction report(checks: Check[], flags: Flags): void {\n const errors = checks.filter((x) => x.level === 'error').length;\n if (flags.json) {\n console.log(JSON.stringify({ ok: errors === 0, checks }, null, 2));\n } else {\n for (const x of checks) {\n const icon = x.level === 'ok' ? c.green('✔') : x.level === 'warn' ? c.yellow('!') : c.red('✖');\n console.log(`${icon} ${x.message}`);\n }\n console.log();\n console.log(errors === 0 ? c.green('All good.') : c.red(`${errors} problem(s) to fix.`));\n }\n if (errors > 0) process.exitCode = 1;\n}\n","import * as p from '@clack/prompts';\nimport { execSync } from 'node:child_process';\nimport { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, join, relative } from 'node:path';\nimport { cloudTarget } from '../api';\nimport { loadCredential } from '../credentials';\nimport { detectProject, installCommand } from '../project';\nimport { deviceLogin } from './login';\nimport { configTemplate, nextMiddlewareTemplate, nextRouteTemplate } from '../templates';\nimport { DB_KINDS, runtimePackages, storeTemplate, storeUsage, type DbKind } from '../templates-store';\nimport { installSkills } from './skills';\nimport { c } from '../ui';\n\nexport type Flags = Record<string, string | boolean | string[] | undefined>;\n\nfunction str(v: unknown): string | undefined {\n return typeof v === 'string' ? v : undefined;\n}\n\nfunction writeIfMissing(file: string, content: string, created: string[], skipped: string[]): void {\n if (existsSync(file)) {\n skipped.push(file);\n return;\n }\n mkdirSync(dirname(file), { recursive: true });\n writeFileSync(file, content, 'utf8');\n created.push(file);\n}\n\nfunction importPath(fromFile: string, toFile: string): string {\n let rel = relative(dirname(fromFile), toFile).replace(/\\\\/g, '/').replace(/\\.(ts|mts|js|mjs)$/, '');\n if (!rel.startsWith('.')) rel = `./${rel}`;\n return rel;\n}\n\n// Vite apps run the SDK in the browser; this plugin prints what each experiment does in the dev server's terminal.\nconst VITE_PLUGIN_HINT = `// vite.config.ts\nimport { splithub } from '@splithub/core/vite';\n\nexport default defineConfig({ plugins: [react(), splithub()] });`;\n\nexport async function init(flags: Flags): Promise<void> {\n const yes = Boolean(flags.yes);\n const json = Boolean(flags.json);\n const project = detectProject();\n const created: string[] = [];\n const skipped: string[] = [];\n\n if (!json) p.intro(c.bold('splithub init'));\n\n let mode = str(flags.mode) as 'self' | 'cloud' | undefined;\n if (!mode) {\n if (yes) mode = 'self';\n else {\n const picked = await p.select({\n message: 'Where should events be stored?',\n options: [\n { value: 'self', label: 'My own database (self-hosted)', hint: 'free forever, nothing leaves your infra' },\n { value: 'cloud', label: 'SplitHub Cloud', hint: 'hosted dashboard, no server code' },\n ],\n });\n if (p.isCancel(picked)) return cancel();\n mode = picked as 'self' | 'cloud';\n }\n }\n\n // Cloud: connect this directory to a project. A saved login or SPLITHUB_API_KEY\n // is enough; otherwise run the device flow — print a link, the human signs in\n // and picks (or creates) the project, the CLI gets the keys. Works when an\n // agent runs init: it relays the link, the user clicks it.\n // Self mode: which database keeps the events. sqlite needs nothing; postgres / mysql\n // get a ready Store in splithub/store.ts; custom gets a documented stub.\n let db: DbKind = (DB_KINDS as string[]).includes(str(flags.db) ?? '') ? (str(flags.db) as DbKind) : 'sqlite';\n if (mode === 'self' && !flags.db && !yes) {\n const picked = await p.select({\n message: 'Where should events be stored?',\n options: [\n { value: 'sqlite', label: 'SQLite file (zero setup)', hint: './splithub.db via node:sqlite' },\n { value: 'postgres', label: 'Postgres', hint: 'pg + DATABASE_URL, table splithub_events' },\n { value: 'mysql', label: 'MySQL / MariaDB / PlanetScale', hint: 'mysql2 + DATABASE_URL' },\n { value: 'custom', label: 'My own store (Prisma, Drizzle, Supabase, Mongo…)', hint: 'a stub with the three methods to fill in' },\n ],\n });\n if (p.isCancel(picked)) return cancel();\n db = picked as DbKind;\n }\n\n let key = str(flags.key);\n let connected: { projectName: string | null; projectId: string | null } | null = null;\n if (mode === 'cloud') {\n const api = cloudTarget(flags).url;\n const saved = loadCredential(api, project.root);\n if (saved) {\n key ??= saved.publicKey ?? undefined;\n connected = { projectName: saved.projectName, projectId: saved.projectId };\n } else if (!process.env.SPLITHUB_API_KEY && !flags['no-login']) {\n if (!json) p.log.step('Connect to SplitHub Cloud');\n try {\n const cred = await deviceLogin({\n api,\n root: project.root,\n json,\n onCode: json\n ? (s) => console.log(JSON.stringify({ step: 'approve', verifyUrl: s.verifyUrl, userCode: s.userCode, expiresIn: s.expiresIn, hint: 'Show this link to the user and wait; init continues once approved.' }))\n : (s) => p.note(`${c.cyan(s.verifyUrl)}\\n\\nCode ${c.green(s.userCode)} · sign in, pick or create the project, approve.`, 'Open this link'),\n });\n key ??= cred.publicKey ?? undefined;\n connected = { projectName: cred.projectName, projectId: cred.projectId };\n if (!json) p.log.success(`connected to ${c.cyan(cred.projectName ?? cred.projectId ?? 'project')}`);\n } catch (error) {\n if (!json) p.log.warn(`not connected: ${error instanceof Error ? error.message : String(error)}. Run ${c.cyan('npx splithub login')} later.`);\n }\n }\n // An API key in the environment (CI, agents) identifies the project: ask the cloud for its public key.\n if (!key && process.env.SPLITHUB_API_KEY) {\n try {\n const res = await fetch(`${api}/config`, { headers: { authorization: `Bearer ${process.env.SPLITHUB_API_KEY}` } });\n const body = (await res.json().catch(() => ({}))) as { publicKey?: string };\n if (typeof body.publicKey === 'string' && body.publicKey.startsWith('pk_')) {\n key = body.publicKey;\n connected ??= { projectName: null, projectId: null };\n }\n } catch {\n // offline: the first push writes the key into the config anyway\n }\n }\n if (!key && !yes) {\n const k = await p.text({ message: 'Cloud public key (pk_...), leave empty to set later via NEXT_PUBLIC_SPLITHUB_KEY', placeholder: 'pk_' });\n if (p.isCancel(k)) return cancel();\n key = k || undefined;\n }\n }\n\n // 1. config\n const configFile = project.configFile ?? join(project.root, 'splithub.config.ts');\n writeIfMissing(configFile, configTemplate(project.name, mode, key), created, skipped);\n\n // 2a. store for self mode (postgres / mysql / custom); sqlite needs no file.\n const storeBody = mode === 'self' ? storeTemplate(db) : null;\n const storeFile = storeBody ? join(project.root, 'splithub', 'store.ts') : null;\n if (storeFile && storeBody) writeIfMissing(storeFile, storeBody, created, skipped);\n\n // 2. framework files\n if (project.framework === 'next') {\n const mwFile = join(project.root, project.hasSrc ? 'src/middleware.ts' : 'middleware.ts');\n writeIfMissing(mwFile, nextMiddlewareTemplate(importPath(mwFile, configFile)), created, skipped);\n if (mode === 'self' && project.appDir) {\n const routeFile = join(project.root, project.appDir, 'api/splithub/[[...path]]/route.ts');\n writeIfMissing(routeFile, nextRouteTemplate(importPath(routeFile, configFile), storeUsage(db, storeFile ? importPath(routeFile, storeFile) : '')), created, skipped);\n }\n }\n\n // 3. agent skills (+ MCP server registration): the agent learns the library, how to test\n // well, the API and the MCP tools from .claude/skills/*; Cursor gets the rule file.\n let mcp = !flags['no-mcp'];\n if (!yes && !json && mcp) {\n const want = await p.confirm({ message: 'Register the SplitHub MCP server for Claude Code / Cursor (.mcp.json, .cursor/mcp.json)?', initialValue: true });\n if (p.isCancel(want)) return cancel();\n mcp = want;\n }\n const skillsResult = installSkills(project.root, { mcp });\n created.push(...skillsResult.written, ...skillsResult.mcp.map((f) => `${f} (MCP server)`));\n skipped.push(...skillsResult.skipped);\n\n // 4. dependencies\n const runtime = ['@splithub/react', '@splithub/core'];\n if (project.framework === 'next') runtime.push('@splithub/next');\n if (mode === 'self') runtime.push('@splithub/node', ...runtimePackages(db));\n const installRuntime = installCommand(project.packageManager, runtime);\n const installDev = installCommand(project.packageManager, ['splithub'], true);\n let installed = false;\n if (!flags['no-install']) {\n const go = yes ? true : await p.confirm({ message: `Install packages now? (${installRuntime})` });\n if (p.isCancel(go)) return cancel();\n if (go) {\n const s = json ? null : p.spinner();\n s?.start('Installing');\n try {\n execSync(installRuntime, { cwd: project.root, stdio: json ? 'ignore' : 'inherit' });\n execSync(installDev, { cwd: project.root, stdio: json ? 'ignore' : 'inherit' });\n installed = true;\n s?.stop('Installed');\n } catch (error) {\n s?.stop('Install failed; run it manually');\n if (!json) p.log.error(error instanceof Error ? error.message : String(error));\n }\n }\n }\n\n const providerHint =\n project.framework === 'next'\n ? `// ${project.appDir ?? 'app'}/layout.tsx\\nimport { SplitHubNextProvider } from '@splithub/next/client';\\nimport { getSplitHub } from '@splithub/next/server';\\nimport config from '${importPath(join(project.root, project.appDir ?? 'app', 'layout.tsx'), configFile)}';\\n\\nexport default async function RootLayout({ children }) {\\n const sh = await getSplitHub(config);\\n return <html><body><SplitHubNextProvider config={config} visitorId={sh.visitorId ?? undefined} remoteOverrides={sh.overrides}>{children}</SplitHubNextProvider></body></html>;\\n}`\n : `// main.tsx\\nimport { SplitHubProvider } from '@splithub/react';\\nimport config from './splithub.config';\\n\\n<SplitHubProvider config={config}><App /></SplitHubProvider>`;\n\n const warning = mode === 'cloud' && !key ? 'No public key yet: storage.key falls back to process.env.NEXT_PUBLIC_SPLITHUB_KEY. It is written into the config by the first `npx splithub push`, by `npx splithub login` (saved with the credentials), or pass --key pk_… (dashboard → Setup); SPLITHUB_API_KEY in the environment also resolves it.' : null;\n const summary = { project: project.name, framework: project.framework, mode, db: mode === 'self' ? db : null, connected, publicKey: key ?? null, warning, created, skipped, installed, installCommands: installed ? [] : [installRuntime, installDev], nextStep: providerHint, ...(project.framework === 'vite' ? { vitePlugin: VITE_PLUGIN_HINT } : {}) };\n\n if (json) {\n console.log(JSON.stringify(summary, null, 2));\n return;\n }\n if (warning) p.log.warn(warning);\n if (mode === 'self' && db !== 'sqlite') p.note(db === 'custom' ? 'Fill in the three methods in splithub/store.ts (the comments say what each must return).' : `Set DATABASE_URL and run the SCHEMA_SQL from splithub/store.ts once (or add it to your migrations).`, `Database: ${db}`);\n if (created.length) p.note(created.map((f) => relative(project.root, f) || f).join('\\n'), 'Created');\n if (skipped.length) p.note(skipped.map((f) => relative(project.root, f)).join('\\n'), 'Already present, left untouched');\n if (!installed) p.note(`${installRuntime}\\n${installDev}`, 'Install');\n p.note(providerHint, 'Wrap your app once');\n if (project.framework === 'vite') p.note(VITE_PLUGIN_HINT, 'Notes in your dev terminal');\n p.outro(`Next: ${c.cyan('npx splithub create')} to add your first experiment, ${c.cyan('npx splithub push')} to sync it, ${c.cyan('npx splithub doctor')} to verify.`);\n}\n\n\nfunction cancel(): void {\n p.cancel('Cancelled.');\n process.exit(0);\n}\n","// `splithub login`: device-code sign-in. The CLI prints a short code and a\n// URL; the user opens it, picks (or creates) a project and approves; the CLI\n// receives a project API key and saves it for this directory. No browser\n// automation, no secrets typed into the terminal — works over SSH and when a\n// coding agent runs it: the agent shows the link, the human clicks it.\nimport { hostname } from 'node:os';\nimport { basename } from 'node:path';\nimport { apiErrorMessage, cloudTarget } from '../api';\nimport { credentialsFile, listCredentials, loadCredential, removeCredential, saveCredential, type SavedCredential } from '../credentials';\nimport { c } from '../ui';\nimport type { Flags } from './init';\n\ninterface Start {\n deviceCode: string;\n userCode: string;\n verifyUrl: string;\n interval: number;\n expiresIn: number;\n}\ninterface Poll {\n status: 'pending' | 'approved' | 'denied' | 'expired' | 'consumed';\n apiKey?: string;\n projectId?: string | null;\n projectName?: string | null;\n publicKey?: string | null;\n}\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\nexport interface DeviceLoginOptions {\n api: string;\n root?: string;\n json?: boolean;\n /** Project name or id to preselect on the approval page. */\n project?: string;\n /** Called with the link and code as soon as they exist (default: print them). */\n onCode?: (start: { verifyUrl: string; userCode: string; expiresIn: number }) => void;\n}\n\n/** Run the device flow and save the credential. Resolves with what was saved. */\nexport async function deviceLogin(options: DeviceLoginOptions): Promise<SavedCredential> {\n const { api } = options;\n const root = options.root ?? process.cwd();\n const label = `cli · ${basename(root)} @ ${hostname()}`.slice(0, 80);\n const startRes = await fetch(`${api}/auth/device`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ label }) });\n if (!startRes.ok) throw new Error(`${api}/auth/device responded ${startRes.status}`);\n const start = (await startRes.json()) as Start;\n if (options.project) start.verifyUrl += `${start.verifyUrl.includes('?') ? '&' : '?'}project=${encodeURIComponent(options.project)}`;\n\n if (options.onCode) options.onCode(start);\n else if (options.json) console.log(JSON.stringify({ step: 'approve', userCode: start.userCode, verifyUrl: start.verifyUrl, expiresIn: start.expiresIn }));\n else {\n console.log(`\\n${c.bold('Open this link to connect:')} ${c.cyan(start.verifyUrl)}`);\n console.log(`${c.dim('Code')} ${c.green(start.userCode)} ${c.dim(`(expires in ${Math.round(start.expiresIn / 60)} min)`)}`);\n console.log(c.dim('Sign in, pick or create the project, approve. Waiting…'));\n }\n\n const deadline = Date.now() + start.expiresIn * 1000;\n while (Date.now() < deadline) {\n await sleep(Math.max(2, start.interval) * 1000);\n const res = await fetch(`${api}/auth/device/${start.deviceCode}`);\n if (!res.ok) throw new Error(`${api}/auth/device responded ${res.status}`);\n const poll = (await res.json()) as Poll;\n if (poll.status === 'pending') continue;\n if (poll.status === 'denied') throw new Error('login was denied in the dashboard');\n if (poll.status === 'expired') throw new Error('the code expired. Run `splithub login` again.');\n if (poll.status === 'consumed' || !poll.apiKey) throw new Error('the key for this code was already collected. Run `splithub login` again.');\n const cred: SavedCredential = { apiKey: poll.apiKey, projectId: poll.projectId ?? null, projectName: poll.projectName ?? null, publicKey: poll.publicKey ?? null, savedAt: new Date().toISOString() };\n saveCredential(api, root, cred);\n return cred;\n }\n throw new Error('the code expired. Run `splithub login` again.');\n}\n\nexport async function login(flags: Flags): Promise<void> {\n const api = cloudTarget({ api: flags.api }).url;\n const root = process.cwd();\n const existing = loadCredential(api, root);\n if (existing && !flags.yes) {\n const msg = `already logged in for ${c.cyan(existing.projectName ?? existing.projectId ?? 'a project')} (${credentialsFile()}). Use --yes to replace.`;\n if (flags.json) console.log(JSON.stringify({ ok: true, alreadyLoggedIn: true, projectId: existing.projectId, projectName: existing.projectName, publicKey: existing.publicKey ?? null }));\n else console.log(msg);\n return;\n }\n const cred = await deviceLogin({ api, root, json: Boolean(flags.json), ...(typeof flags.project === 'string' ? { project: flags.project } : {}) });\n if (flags.json) console.log(JSON.stringify({ ok: true, projectId: cred.projectId, projectName: cred.projectName, publicKey: cred.publicKey, credentials: credentialsFile() }));\n else {\n console.log(`${c.green('✔')} logged in to ${c.cyan(cred.projectName ?? cred.projectId ?? 'project')}`);\n console.log(c.dim(`key saved for ${root} in ${credentialsFile()}`));\n console.log(c.dim('next: npx splithub push'));\n }\n}\n\nexport async function logout(flags: Flags): Promise<void> {\n const api = cloudTarget({ api: flags.api }).url;\n const removed = removeCredential(api, process.cwd());\n if (flags.json) console.log(JSON.stringify({ ok: true, removed }));\n else console.log(removed ? `${c.green('✔')} removed the saved key for this directory` : c.dim('nothing saved for this directory'));\n}\n\nexport async function whoami(flags: Flags): Promise<void> {\n const target = cloudTarget(flags);\n if (!target.token) throw new Error('not logged in. Run `splithub login` or set SPLITHUB_API_KEY.');\n const res = await fetch(`${target.url}/status`, { headers: { authorization: `Bearer ${target.token}` } });\n const data = (await res.json().catch(() => ({}))) as { project?: string };\n if (!res.ok) throw new Error(apiErrorMessage(res.status, data, `${target.url}/status responded ${res.status}`));\n const saved = loadCredential(target.url);\n if (flags.json) console.log(JSON.stringify({ ok: true, api: target.url, project: data.project, projectId: saved?.projectId ?? null, publicKey: saved?.publicKey ?? null }));\n else console.log(`${c.bold('api')} ${target.url}\\n${c.bold('project')} ${c.cyan(data.project ?? '?')}\\n${c.bold('public key')} ${saved?.publicKey ?? c.dim('unknown (log in again to fetch it)')}\\n${c.bold('api key')} ${target.token.slice(0, 11)}…`);\n}\n\n/** `splithub projects`: what this machine is connected to, the current directory first. */\nexport async function projects(flags: Flags): Promise<void> {\n const api = cloudTarget({ api: flags.api }).url;\n const here = process.cwd();\n const rows = listCredentials(api).map((r) => ({ root: r.root, current: r.root === here, projectId: r.cred.projectId, projectName: r.cred.projectName, publicKey: r.cred.publicKey ?? null, savedAt: r.cred.savedAt }));\n if (flags.json) {\n console.log(JSON.stringify({ api, credentials: credentialsFile(), projects: rows }, null, 2));\n return;\n }\n if (rows.length === 0) {\n console.log(c.dim('no directory on this machine is connected yet. Run `splithub login` in your app.'));\n return;\n }\n for (const r of rows) console.log(`${r.current ? c.green('▸') : ' '} ${c.cyan(r.projectName ?? r.projectId ?? '?')} ${c.dim(`· ${r.root}`)}`);\n console.log(c.dim('\\nswitch: run `splithub login --yes --project <name>` in that directory · disconnect: `splithub logout`'));\n}\n","// Store templates for self-hosted mode: `splithub init --mode self --db postgres|mysql|custom`\n// writes splithub/store.ts from one of these. Each implements the Store interface\n// from @splithub/node (insertEvents, variantCounts, summaries) with the same\n// attribution rule as the cloud: a visitor counts once per experiment, in the\n// variant of their earliest exposure, and converts when a goal happened at or\n// after that exposure.\n\nexport type DbKind = 'sqlite' | 'postgres' | 'mysql' | 'custom';\nexport const DB_KINDS: DbKind[] = ['sqlite', 'postgres', 'mysql', 'custom'];\n\nexport const PG_STORE = `import type { ExperimentSummary, Store, StoredEvent } from '@splithub/node';\nimport type { VariantCounts } from '@splithub/stats';\nimport { Pool } from 'pg';\n\n// SplitHub events in your Postgres. Run once (or add to your migrations):\nexport const SCHEMA_SQL = \\`\nCREATE TABLE IF NOT EXISTS splithub_events (\n id text PRIMARY KEY,\n type text NOT NULL, -- exposure | goal\n experiment text,\n variant text,\n goal text,\n visitor_id text NOT NULL,\n session_id text NOT NULL,\n ts bigint NOT NULL, -- client clock, unix ms\n url text,\n props jsonb,\n received_at bigint NOT NULL, -- server clock, unix ms\n host text,\n country text,\n device text,\n browser text\n);\nCREATE INDEX IF NOT EXISTS splithub_events_exp ON splithub_events (type, experiment, visitor_id, ts);\nCREATE INDEX IF NOT EXISTS splithub_events_goal ON splithub_events (type, goal, visitor_id, ts);\n\\`;\n\nexport function pgStore(pool: Pool = new Pool({ connectionString: process.env.DATABASE_URL })): Store {\n return {\n async insertEvents(events: StoredEvent[]) {\n if (events.length === 0) return 0;\n const cols = 15;\n const values: unknown[] = [];\n const rows = events.map((e, i) => {\n values.push(e.id, e.type, e.experiment, e.variant, e.goal, e.visitorId, e.sessionId, e.ts, e.url, e.props ? JSON.stringify(e.props) : null, e.receivedAt, e.host ?? null, e.country ?? null, e.device ?? null, e.browser ?? null);\n return '(' + Array.from({ length: cols }, (_, j) => '$' + (i * cols + j + 1)).join(', ') + ')';\n });\n const r = await pool.query(\n 'INSERT INTO splithub_events (id, type, experiment, variant, goal, visitor_id, session_id, ts, url, props, received_at, host, country, device, browser) VALUES ' + rows.join(', ') + ' ON CONFLICT (id) DO NOTHING',\n values\n );\n return r.rowCount ?? 0;\n },\n async variantCounts(experiment: string, goal: string): Promise<VariantCounts[]> {\n const r = await pool.query(\n \\`WITH fv AS (\n SELECT visitor_id, MIN(ts) AS first_ts FROM splithub_events\n WHERE type = 'exposure' AND experiment = $1 GROUP BY visitor_id),\n first_exposure AS (\n SELECT MIN(e.variant) AS variant, fv.visitor_id, fv.first_ts\n FROM fv JOIN splithub_events e\n ON e.type = 'exposure' AND e.experiment = $1 AND e.visitor_id = fv.visitor_id AND e.ts = fv.first_ts\n GROUP BY fv.visitor_id, fv.first_ts),\n converted AS (\n SELECT fe.variant, fe.visitor_id, SUM(COALESCE((g.props->>'revenue')::numeric, 0)) AS revenue\n FROM first_exposure fe JOIN splithub_events g\n ON g.type = 'goal' AND g.goal = $2 AND g.visitor_id = fe.visitor_id AND g.ts >= fe.first_ts\n GROUP BY fe.variant, fe.visitor_id)\n SELECT fe.variant, COUNT(*)::int AS exposures,\n (SELECT COUNT(*)::int FROM converted c WHERE c.variant = fe.variant) AS conversions,\n (SELECT COALESCE(SUM(revenue), 0)::float FROM converted c WHERE c.variant = fe.variant) AS revenue\n FROM first_exposure fe GROUP BY fe.variant\\`,\n [experiment, goal]\n );\n return r.rows.map((x) => ({ variant: String(x.variant), exposures: Number(x.exposures), conversions: Number(x.conversions), revenue: Number(x.revenue) }));\n },\n async summaries(): Promise<ExperimentSummary[]> {\n const r = await pool.query(\n \\`SELECT experiment, COUNT(*)::int AS exposures, COUNT(DISTINCT visitor_id)::int AS visitors, MIN(ts)::bigint AS first_ts, MAX(ts)::bigint AS last_ts\n FROM splithub_events WHERE type = 'exposure' GROUP BY experiment\\`\n );\n return r.rows.map((x) => ({ experiment: String(x.experiment), exposures: Number(x.exposures), visitors: Number(x.visitors), firstExposureAt: x.first_ts == null ? null : Number(x.first_ts), lastExposureAt: x.last_ts == null ? null : Number(x.last_ts) }));\n },\n close: () => pool.end(),\n };\n}\n`;\n\nexport const MYSQL_STORE = `import type { ExperimentSummary, Store, StoredEvent } from '@splithub/node';\nimport type { VariantCounts } from '@splithub/stats';\nimport mysql, { type Pool } from 'mysql2/promise';\n\n// SplitHub events in your MySQL / MariaDB / PlanetScale. Run once (or add to your migrations):\nexport const SCHEMA_SQL = \\`\nCREATE TABLE IF NOT EXISTS splithub_events (\n id VARCHAR(64) PRIMARY KEY,\n type VARCHAR(16) NOT NULL,\n experiment VARCHAR(64) NULL,\n variant VARCHAR(64) NULL,\n goal VARCHAR(64) NULL,\n visitor_id VARCHAR(64) NOT NULL,\n session_id VARCHAR(64) NOT NULL,\n ts BIGINT NOT NULL,\n url VARCHAR(512) NULL,\n props JSON NULL,\n received_at BIGINT NOT NULL,\n host VARCHAR(255) NULL,\n country VARCHAR(8) NULL,\n device VARCHAR(16) NULL,\n browser VARCHAR(32) NULL,\n INDEX splithub_events_exp (type, experiment, visitor_id, ts),\n INDEX splithub_events_goal (type, goal, visitor_id, ts)\n);\n\\`;\n\nexport function mysqlStore(pool: Pool = mysql.createPool(process.env.DATABASE_URL ?? '')): Store {\n return {\n async insertEvents(events: StoredEvent[]) {\n if (events.length === 0) return 0;\n const values = events.map((e) => [e.id, e.type, e.experiment, e.variant, e.goal, e.visitorId, e.sessionId, e.ts, e.url, e.props ? JSON.stringify(e.props) : null, e.receivedAt, e.host ?? null, e.country ?? null, e.device ?? null, e.browser ?? null]);\n const [r] = await pool.query(\n 'INSERT IGNORE INTO splithub_events (id, type, experiment, variant, goal, visitor_id, session_id, ts, url, props, received_at, host, country, device, browser) VALUES ?',\n [values]\n );\n return (r as { affectedRows: number }).affectedRows;\n },\n async variantCounts(experiment: string, goal: string): Promise<VariantCounts[]> {\n const [rows] = await pool.query(\n // Derived tables only (no CTEs, no window functions) so this runs on MySQL 5.7.\n \\`SELECT v.variant, COUNT(*) AS exposures, SUM(v.converted) AS conversions, COALESCE(SUM(v.revenue), 0) AS revenue\n FROM (\n SELECT fe.variant, fe.visitor_id,\n CASE WHEN COUNT(g.id) > 0 THEN 1 ELSE 0 END AS converted,\n SUM(COALESCE(JSON_EXTRACT(g.props, '$.revenue'), 0)) AS revenue\n FROM (\n SELECT MIN(e.variant) AS variant, fv.visitor_id, fv.first_ts\n FROM (SELECT visitor_id, MIN(ts) AS first_ts FROM splithub_events WHERE type = 'exposure' AND experiment = ? GROUP BY visitor_id) fv\n JOIN splithub_events e ON e.type = 'exposure' AND e.experiment = ? AND e.visitor_id = fv.visitor_id AND e.ts = fv.first_ts\n GROUP BY fv.visitor_id, fv.first_ts) fe\n LEFT JOIN splithub_events g ON g.type = 'goal' AND g.goal = ? AND g.visitor_id = fe.visitor_id AND g.ts >= fe.first_ts\n GROUP BY fe.variant, fe.visitor_id) v\n GROUP BY v.variant\\`,\n [experiment, experiment, goal]\n );\n return (rows as Array<Record<string, unknown>>).map((x) => ({ variant: String(x.variant), exposures: Number(x.exposures), conversions: Number(x.conversions), revenue: Number(x.revenue) }));\n },\n async summaries(): Promise<ExperimentSummary[]> {\n const [rows] = await pool.query(\n \\`SELECT experiment, COUNT(*) AS exposures, COUNT(DISTINCT visitor_id) AS visitors, MIN(ts) AS first_ts, MAX(ts) AS last_ts\n FROM splithub_events WHERE type = 'exposure' GROUP BY experiment\\`\n );\n return (rows as Array<Record<string, unknown>>).map((x) => ({ experiment: String(x.experiment), exposures: Number(x.exposures), visitors: Number(x.visitors), firstExposureAt: x.first_ts == null ? null : Number(x.first_ts), lastExposureAt: x.last_ts == null ? null : Number(x.last_ts) }));\n },\n close: () => pool.end(),\n };\n}\n`;\n\nexport const CUSTOM_STORE = `import type { ExperimentSummary, Store, StoredEvent } from '@splithub/node';\nimport type { VariantCounts } from '@splithub/stats';\n\n/**\n * Your own store (Prisma, Drizzle, Supabase, Mongo, anything). Three methods.\n * Attribution rule (keep it, so results match the dashboard):\n * a visitor counts once per experiment, in the variant of their earliest\n * exposure (same ts: smallest variant key), and converts when they sent the\n * goal at or after that exposure; count unique visitors, not events.\n * Columns worth keeping: id (unique, dedupe on it), type, experiment, variant,\n * goal, visitor_id, session_id, ts, url, props (json), received_at, host,\n * country, device, browser.\n */\nexport function customStore(): Store {\n return {\n async insertEvents(events: StoredEvent[]): Promise<number> {\n // Insert, skipping ids that already exist. Return how many were inserted.\n throw new Error('implement insertEvents ' + events.length);\n },\n async variantCounts(experiment: string, goal: string): Promise<VariantCounts[]> {\n // For each variant: exposures = visitors whose earliest exposure in this experiment was to it;\n // conversions = those visitors with a goal event (goal === goal) at ts >= that earliest exposure;\n // revenue = sum of props.revenue over those goal events.\n throw new Error('implement variantCounts ' + experiment + ' ' + goal);\n },\n async summaries(): Promise<ExperimentSummary[]> {\n // Per experiment: exposures, unique visitors, first and last exposure ts (unix ms).\n throw new Error('implement summaries');\n },\n };\n}\n`;\n\nexport function storeTemplate(db: DbKind): string | null {\n return db === 'postgres' ? PG_STORE : db === 'mysql' ? MYSQL_STORE : db === 'custom' ? CUSTOM_STORE : null;\n}\n\n/** Import line + factory call used by the route template. */\nexport function storeUsage(db: DbKind, storeImport: string): { imports: string; factory: string } {\n switch (db) {\n case 'postgres':\n return { imports: `import { pgStore } from '${storeImport}';`, factory: 'pgStore()' };\n case 'mysql':\n return { imports: `import { mysqlStore } from '${storeImport}';`, factory: 'mysqlStore()' };\n case 'custom':\n return { imports: `import { customStore } from '${storeImport}';`, factory: 'customStore()' };\n default:\n return { imports: `import { sqliteStore } from '@splithub/adapter-sqlite';`, factory: `sqliteStore({ file: process.env.SPLITHUB_DB ?? './splithub.db' })` };\n }\n}\n\nexport function runtimePackages(db: DbKind): string[] {\n return db === 'postgres' ? ['pg'] : db === 'mysql' ? ['mysql2'] : db === 'sqlite' ? ['@splithub/adapter-sqlite'] : [];\n}\n","// `splithub skills [--mcp] [--force]`: install or refresh the agent skills in\n// this project (.claude/skills/<name>/SKILL.md, .cursor/rules/splithub.mdc,\n// an AGENTS.md section) and, with --mcp, register the SplitHub MCP server in\n// .mcp.json (Claude Code) and .cursor/mcp.json (Cursor). `init` calls this too.\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, join, relative } from 'node:path';\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}\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/.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 } = {}): SkillsResult {\n const out: SkillsResult = { written: [], skipped: [], mcp: [] };\n for (const s of SKILLS) writeFile(join(root, '.claude', 'skills', s.dir, 'SKILL.md'), s.body, Boolean(options.force), out);\n writeFile(join(root, '.cursor', 'rules', 'splithub.mdc'), CURSOR_RULE, Boolean(options.force), out);\n\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${AGENTS_SECTION}`, 'utf8');\n out.written.push(agentsFile);\n } else if (!/SplitHub/.test(readFileSync(agentsFile, 'utf8'))) {\n writeFileSync(agentsFile, readFileSync(agentsFile, 'utf8') + `\\n${AGENTS_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) });\n if (flags.json) {\n console.log(JSON.stringify(result, null, 2));\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 (!flags.mcp) console.log(c.dim(`add --mcp to register the SplitHub 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 test well), splithub-api (HTTP API), splithub-mcp (MCP tools), splithub-self-hosted (your own database), splithub-ship (keep the winner, remove the test)'));\n}\n","import type { ExperimentStatus } from '@splithub/core';\nimport { relative } from 'node:path';\nimport { apiErrorMessage, cloudTarget } from '../api';\nimport { loadConfig, readSource, setExperimentStatus, writeSource } from '../config-file';\nimport { detectProject } from '../project';\nimport { c } from '../ui';\nimport type { Flags } from './init';\n\nconst MAP: Record<string, ExperimentStatus> = { start: 'running', pause: 'paused', finish: 'finished' };\n\nexport async function lifecycle(command: string, id: string | undefined, flags: Flags): Promise<void> {\n const status = MAP[command];\n if (!status) throw new Error(`unknown command \"${command}\"`);\n if (!id) throw new Error(`usage: splithub ${command} <experiment>`);\n const project = detectProject();\n if (!project.configFile) throw new Error('splithub.config.ts not found. Run `npx splithub init` first.');\n const updated = setExperimentStatus(readSource(project.configFile), id, status);\n writeSource(project.configFile, updated);\n const file = relative(project.root, project.configFile);\n\n // Cloud mode: also apply it live through a remote override, so no deploy is needed.\n let live: 'applied' | 'skipped' | string = 'skipped';\n try {\n const config = await loadConfig(project.configFile);\n if (config.storage.mode === 'cloud') {\n const target = cloudTarget(flags);\n if (!target.token) live = 'no API key (set SPLITHUB_API_KEY to apply without a deploy)';\n else {\n const res = await fetch(`${target.url}/overrides/${encodeURIComponent(id)}`, {\n method: 'PUT',\n headers: { authorization: `Bearer ${target.token}`, 'content-type': 'application/json' },\n body: JSON.stringify({ status }),\n });\n const body: unknown = await res.json().catch(() => ({}));\n live = res.ok ? 'applied' : `cloud refused: ${apiErrorMessage(res.status, body, String(res.status))}`;\n }\n }\n } catch (error) {\n live = `could not apply live: ${error instanceof Error ? error.message : String(error)}`;\n }\n\n // A finished test keeps its numbers, but every variant is still in the code until someone decides.\n const next = status === 'finished' ? `Read the verdict (npx splithub results ${id}), decide which variant to keep, then remove the test from the code and the config: the splithub-ship skill walks an agent through it.` : null;\n if (flags.json) console.log(JSON.stringify({ experiment: id, status, configFile: file, live, ...(next ? { next } : {}) }));\n else {\n console.log(`${c.green('✔')} ${c.bold(id)} → ${status} ${c.dim(`(${file})`)}`);\n if (live === 'applied') console.log(`${c.green('✔')} live in the cloud within 60s, no deploy needed (the config change ships with your next deploy)`);\n else if (live !== 'skipped') console.log(c.yellow(`! ${live}`));\n if (next) console.log(c.dim(`Next: ${next}`));\n }\n}\n","// `npx splithub` with no arguments: a menu that walks through everything step\n// by step (like an interactive assistant), so nobody has to learn the flags.\n// Agents and scripts keep using the subcommands + --json.\nimport * as p from '@clack/prompts';\nimport { readFileSync } from 'node:fs';\nimport { cloudTarget, fetchStatus, resolveTarget } from '../api';\nimport { loadCredential } from '../credentials';\nimport { detectProject } from '../project';\nimport { c } from '../ui';\nimport { create } from './create';\nimport { dev } from './dev';\nimport { doctor } from './doctor';\nimport { init, type Flags } from './init';\nimport { lifecycle } from './lifecycle';\nimport { login, logout } from './login';\nimport { pull, push } from './push';\nimport { results } from './results';\nimport { skills } from './skills';\nimport { status } from './status';\n\ntype Action = 'init' | 'create' | 'status' | 'results' | 'start' | 'pause' | 'finish' | 'push' | 'pull' | 'login' | 'logout' | 'dev' | 'doctor' | 'skills' | 'exit';\n\nfunction state(flags: Flags) {\n const project = detectProject();\n const api = cloudTarget({ api: flags.api }).url;\n const cred = loadCredential(api, project.root);\n const mode = project.configFile ? (/mode\\s*:\\s*['\"]cloud['\"]/.test(readSafe(project.configFile)) ? 'cloud' : 'self') : null;\n return { project, cred, mode, connected: Boolean(cred || process.env.SPLITHUB_API_KEY) };\n}\n\nfunction readSafe(file: string): string {\n try {\n return readFileSync(file, 'utf8');\n } catch {\n return '';\n }\n}\n\nasync function pickExperiment(flags: Flags, message: string): Promise<string | null> {\n try {\n const data = await fetchStatus(resolveTarget(flags, detectProject()));\n if (data.experiments.length === 0) {\n p.log.warn('no experiments yet');\n return null;\n }\n const picked = await p.select({ message, options: data.experiments.map((e) => ({ value: e.experiment, label: e.experiment, hint: `${e.status} · ${e.visitors} visitors${e.headline ? ` · ${e.headline}` : ''}` })) });\n if (p.isCancel(picked)) return null;\n return picked as string;\n } catch (error) {\n p.log.error(error instanceof Error ? error.message : String(error));\n return null;\n }\n}\n\nexport async function menu(flags: Flags): Promise<void> {\n p.intro(c.bold('splithub'));\n for (;;) {\n const s = state(flags);\n const where = s.project.configFile ? `${c.green('config')} ${s.mode === 'cloud' ? 'cloud mode' : 'self-hosted'}` : c.yellow('no config yet');\n const who = s.cred ? `${c.green('connected')} to ${c.cyan(s.cred.projectName ?? s.cred.projectId ?? 'project')}` : s.mode === 'cloud' ? c.yellow('not connected') : c.dim('local only');\n p.log.info(`${c.bold(s.project.name)} (${s.project.framework}) · ${where} · ${who}`);\n\n const options: Array<{ value: Action; label: string; hint?: string }> = [];\n if (!s.project.configFile) options.push({ value: 'init', label: 'Set up this app', hint: 'config, framework files, agent docs, sign-in link' });\n else {\n if (s.mode === 'cloud' && !s.connected) options.push({ value: 'login', label: 'Connect to SplitHub Cloud', hint: 'opens a sign-in link' });\n options.push({ value: 'create', label: 'Create an experiment', hint: 'step by step' });\n options.push({ value: 'status', label: 'Status of all experiments' });\n options.push({ value: 'results', label: 'Results of one experiment', hint: 'verdict, lift, confidence' });\n options.push({ value: 'start', label: 'Start an experiment' }, { value: 'pause', label: 'Pause an experiment' }, { value: 'finish', label: 'Finish an experiment' });\n if (s.mode === 'cloud') options.push({ value: 'push', label: 'Push config to the cloud', hint: 'after editing splithub.config.ts' }, { value: 'pull', label: 'Pull dashboard changes into the file' });\n options.push({ value: 'dev', label: 'Test locally in the browser', hint: 'debug panel: variants, reasons, events' });\n options.push({ value: 'doctor', label: 'Check the installation' });\n options.push({ value: 'skills', label: 'Install agent skills + MCP server', hint: 'Claude Code, Cursor, Codex' });\n if (s.cred) options.push({ value: 'logout', label: 'Disconnect this folder' });\n }\n options.push({ value: 'exit', label: 'Exit' });\n\n const action = await p.select<Action>({ message: 'What do you want to do?', options });\n if (p.isCancel(action) || action === 'exit') break;\n try {\n switch (action) {\n case 'init':\n await init({ ...flags, mode: flags.mode ?? 'cloud' });\n break;\n case 'login':\n await login({ ...flags, yes: true });\n break;\n case 'create':\n await create(flags);\n break;\n case 'status':\n await status(flags);\n break;\n case 'results': {\n const key = await pickExperiment(flags, 'Which experiment?');\n if (key) await results(key, flags);\n break;\n }\n case 'start':\n case 'pause':\n case 'finish': {\n const key = await pickExperiment(flags, `Which experiment to ${action}?`);\n if (key) await lifecycle(action, key, flags);\n break;\n }\n case 'push':\n await push(flags);\n break;\n case 'pull':\n await pull(flags);\n break;\n case 'logout':\n await logout(flags);\n break;\n case 'dev':\n await dev(flags);\n break;\n case 'doctor':\n await doctor(flags);\n break;\n case 'skills':\n await skills({ ...flags, mcp: true });\n break;\n }\n } catch (error) {\n p.log.error(error instanceof Error ? error.message : String(error));\n }\n console.log();\n }\n p.outro(`Scripts and agents: ${c.cyan('splithub --help')} lists every command; add ${c.cyan('--json')} for machine output.`);\n}\n","import { relative } from 'node:path';\nimport { apiErrorMessage, cloudTarget } from '../api';\nimport { hasExperiment, insertExperiment, loadConfig, readSource, writeSource } from '../config-file';\nimport { detectProject } from '../project';\nimport { c } from '../ui';\nimport type { Flags } from './init';\n\ninterface CloudExperiment {\n key: string;\n kind: 'component' | 'value' | 'redirect' | 'mvt';\n status: 'draft' | 'running' | 'paused' | 'finished';\n goal: string | null;\n match: string | null;\n description: string | null;\n variants: Array<{ key: string; weight: number; value?: unknown; to?: string; levels?: Record<string, string> }>;\n /** Multivariate: the factors whose combinations the variants are. */\n factors?: Array<{ key: string; levels: string[] }>;\n flow?: unknown;\n traffic?: number;\n maxExposures?: number | null;\n schedule?: { startAt?: string | null; endAt?: string | null } | null;\n}\n\ninterface PushResponse {\n ok: boolean;\n project: string;\n version: number;\n pushedAt: string;\n publicKey: string;\n experiments: number;\n /** Experiments created in the dashboard that the local file does not have yet. */\n cloudOnly?: CloudExperiment[];\n}\n\n/** Write dashboard-created experiments into the local config file. Returns the keys written. */\n/** Factor → level → value, read back from the combinations the cloud generated. */\nfunction factorsOf(e: CloudExperiment): Record<string, Record<string, string>> {\n const out: Record<string, Record<string, string>> = {};\n for (const f of e.factors ?? []) {\n out[f.key] = {};\n for (const level of f.levels) {\n const combo = e.variants.find((v) => v.levels?.[f.key] === level);\n const value = (combo?.value as Record<string, unknown> | undefined)?.[f.key];\n out[f.key]![level] = typeof value === 'string' ? value : value === undefined ? level : JSON.stringify(value);\n }\n }\n return out;\n}\n\nfunction adoptCloudExperiments(file: string, cloudOnly: CloudExperiment[] | undefined): string[] {\n if (!cloudOnly || cloudOnly.length === 0) return [];\n let source = readSource(file);\n const written: string[] = [];\n for (const e of cloudOnly) {\n if (hasExperiment(source, e.key)) continue;\n const total = e.variants.reduce((s, v) => s + v.weight, 0) || 1;\n source = insertExperiment(source, {\n key: e.key,\n kind: e.kind,\n status: e.status,\n goal: e.goal ?? undefined,\n match: e.match ?? undefined,\n description: e.description ?? undefined,\n flow: e.flow ?? undefined,\n traffic: e.traffic,\n maxExposures: e.maxExposures ?? undefined,\n schedule: e.schedule ?? undefined,\n variants: e.variants.map((v) => ({ key: v.key, weight: Math.round((v.weight / total) * 100), value: typeof v.value === 'string' ? v.value : v.value === undefined ? undefined : JSON.stringify(v.value), to: v.to })),\n ...(e.kind === 'mvt' && e.factors ? { factors: factorsOf(e) } : {}),\n });\n written.push(e.key);\n }\n if (written.length) writeSource(file, source);\n return written;\n}\n\n/**\n * `splithub push`: upload the normalized splithub.config.ts to SplitHub Cloud.\n * Needs a project API key (sk_...) via --token or SPLITHUB_API_KEY. The first\n * push returns the public key (pk_...) which is written into the config's\n * `storage.key` when it is still empty.\n */\nexport async function push(flags: Flags): Promise<void> {\n const project = detectProject();\n if (!project.configFile) throw new Error('splithub.config.ts not found. Run `npx splithub init` first.');\n const config = await loadConfig(project.configFile);\n if (config.storage.mode !== 'cloud') {\n throw new Error(`storage.mode is \"${config.storage.mode}\". Set storage: { mode: 'cloud' } in splithub.config.ts to use SplitHub Cloud.`);\n }\n const target = cloudTarget(flags);\n if (!target.token) throw new Error('project API key required: run `npx splithub login`, or pass --token sk_... / SPLITHUB_API_KEY (dashboard → Settings → API keys).');\n\n const res = await fetch(`${target.url}/config`, {\n method: 'PUT',\n headers: { authorization: `Bearer ${target.token}`, 'content-type': 'application/json' },\n body: JSON.stringify({ config }),\n });\n const body = (await res.json().catch(() => ({}))) as Partial<PushResponse> & { error?: string };\n if (!res.ok) throw new Error(apiErrorMessage(res.status, body, `${target.url}/config responded ${res.status}`));\n\n // Write the public key into the config when it is missing.\n let keyWritten = false;\n if (body.publicKey && !config.storage.key) {\n const source = readSource(project.configFile);\n const updated = source.replace(/(mode\\s*:\\s*['\"]cloud['\"]\\s*)(,?)(\\s*\\})/, (_m, a: string, _comma: string, b: string) => `${a}, key: '${body.publicKey}'${b}`);\n if (updated !== source) {\n writeSource(project.configFile, updated);\n keyWritten = true;\n }\n }\n\n const adopted = adoptCloudExperiments(project.configFile, body.cloudOnly);\n const out = { ...body, configFile: relative(project.root, project.configFile), keyWritten, adopted };\n if (flags.json) {\n console.log(JSON.stringify(out, null, 2));\n return;\n }\n console.log(`${c.green('✔')} pushed ${c.bold(String(body.project))} v${body.version} · ${body.experiments} experiment(s) → ${target.url}`);\n if (adopted.length) console.log(`${c.green('✔')} written into ${out.configFile} from the dashboard: ${adopted.join(', ')} (wire them in code if they are value/component experiments)`);\n if (body.publicKey) {\n console.log(keyWritten ? `${c.green('✔')} public key written to ${out.configFile}` : `${c.dim('public key:')} ${body.publicKey}`);\n if (!keyWritten && !config.storage.key) console.log(c.yellow(`Add it to splithub.config.ts: storage: { mode: 'cloud', key: '${body.publicKey}' }`));\n }\n}\n\n/** `splithub pull`: print the config stored in the cloud (for inspection or recovery). */\nexport async function pull(flags: Flags): Promise<void> {\n const target = cloudTarget(flags);\n if (!target.token) throw new Error('project API key required: run `npx splithub login`, or pass --token sk_... / SPLITHUB_API_KEY');\n const res = await fetch(`${target.url}/config`, { headers: { authorization: `Bearer ${target.token}` } });\n const body = (await res.json().catch(() => ({}))) as { error?: string; config?: { experiments?: Array<CloudExperiment & { origin?: string }> }; version?: number; pushedAt?: string; publicKey?: string };\n if (!res.ok) throw new Error(apiErrorMessage(res.status, body, `${target.url}/config responded ${res.status}`));\n const project = detectProject();\n const dashboardOnes = (body.config?.experiments ?? []).filter((e) => e.origin === 'dashboard');\n const adopted = project.configFile ? adoptCloudExperiments(project.configFile, dashboardOnes) : [];\n if (flags.json) {\n console.log(JSON.stringify({ ...body, adopted }, null, 2));\n return;\n }\n console.log(`${c.bold('cloud config')} v${body.version} ${c.dim(`pushed ${body.pushedAt}`)} · public key ${body.publicKey}`);\n if (adopted.length) console.log(`${c.green('✔')} written into ${relative(project.root, project.configFile ?? '')}: ${adopted.join(', ')}`);\n else if (dashboardOnes.length) console.log(c.dim(`dashboard experiments already present locally: ${dashboardOnes.map((e) => e.key).join(', ')}`));\n else console.log(c.dim('no dashboard-created experiments to pull'));\n}\n","import { fetchResults, resolveTarget } from '../api';\nimport { detectProject } from '../project';\nimport { bar, c, pct, statusColor, table, verdictColor, verdictIcon } from '../ui';\n\nexport async function results(key: string | undefined, flags: Record<string, unknown>): Promise<void> {\n if (!key) throw new Error('usage: splithub results <experiment>');\n const target = resolveTarget(flags, detectProject());\n const r = await fetchResults(target, key);\n if (flags.json) {\n console.log(JSON.stringify(r.status === 'finished' ? { ...r, next: FINISHED_NEXT } : r, null, 2));\n return;\n }\n const v = r.verdict;\n console.log(`${c.bold(r.experiment)} ${c.dim(`· ${r.kind} · `)}${statusColor(r.status)} ${c.dim(`· goal: ${r.goal ?? 'none'}`)}`);\n if (r.description) console.log(c.dim(r.description));\n console.log();\n console.log(verdictColor(v.status, `${label(v.status)} ${v.message}`));\n console.log();\n\n const rates = new Map<string, number>();\n for (const cnt of v.sample.variants) rates.set(cnt.variant, cnt.exposures > 0 ? cnt.conversions / cnt.exposures : 0);\n\n console.log(\n table(\n ['VARIANT', 'VISITORS', 'CONV', 'RATE', 'LIFT', 'P(BEAT)', 'P-VALUE', '95% CI'],\n v.sample.variants.map((cnt, i) => {\n const cmp = v.comparisons.find((x) => x.variant === cnt.variant);\n const name = i === 0 ? `${cnt.variant} ${c.dim('(control)')}` : cnt.variant;\n const marked = v.winner === cnt.variant ? c.green(`★ ${name}`) : name;\n return [\n marked,\n String(cnt.exposures),\n String(cnt.conversions),\n pct(rates.get(cnt.variant)),\n cmp ? pct(cmp.relativeLift, true) : '–',\n cmp ? pct(cmp.probabilityToBeat) : '–',\n cmp ? cmp.pValue.toFixed(4) : '–',\n cmp ? `${pct(cmp.ci.low, true)} … ${pct(cmp.ci.high, true)}` : '–',\n ];\n })\n )\n );\n // Rates as bars, lift next to them; P(beat) as a second bar. Reads at a glance in a terminal.\n const maxRate = Math.max(0.0001, ...v.sample.variants.map((cnt) => rates.get(cnt.variant) ?? 0));\n const nameWidth = Math.max(...v.sample.variants.map((cnt) => cnt.variant.length));\n console.log();\n console.log(c.dim('RATE'));\n for (const cnt of v.sample.variants) {\n const cmp = v.comparisons.find((x) => x.variant === cnt.variant);\n const paint = v.winner === cnt.variant ? c.green : cmp && (cmp.relativeLift ?? 0) < 0 ? c.red : c.cyan;\n const lift = cmp ? (cmp.relativeLift ?? 0) >= 0 ? c.green(`▲ ${pct(cmp.relativeLift, true)}`) : c.red(`▼ ${pct(cmp.relativeLift, true)}`) : c.dim('baseline');\n console.log(`${cnt.variant.padEnd(nameWidth)} ${bar(rates.get(cnt.variant) ?? 0, maxRate, 24, paint)} ${pct(rates.get(cnt.variant)).padStart(6)} ${lift}`);\n }\n if (v.comparisons.length) {\n console.log();\n console.log(c.dim('CHANCE TO BEAT THE CONTROL'));\n for (const cmp of v.comparisons) {\n const paint = cmp.probabilityToBeat >= 0.95 ? c.green : cmp.probabilityToBeat <= 0.05 ? c.red : c.yellow;\n console.log(`${cmp.variant.padEnd(nameWidth)} ${bar(cmp.probabilityToBeat, 1, 24, paint)} ${pct(cmp.probabilityToBeat).padStart(6)}`);\n }\n }\n if (v.srm) {\n console.log();\n console.log(c.dim(`SRM check: chi²=${v.srm.chiSquare.toFixed(2)} p=${v.srm.pValue.toExponential(2)} ${v.srm.detected ? c.red('DETECTED') : 'ok'}`));\n }\n if (v.status === 'insufficient_sample' && v.sample.neededPerVariant) {\n console.log(c.dim(`Estimated ${v.sample.neededPerVariant} visitors per variant needed to confirm the current lift.`));\n }\n if (r.factors?.length) {\n console.log();\n console.log(c.bold('Each factor on its own') + c.dim(' (a level sums every combination that uses it, compared with the first level)'));\n for (const f of r.factors) {\n console.log(\n table(\n [f.key.toUpperCase(), 'VISITORS', 'CONV.', 'RATE', 'LIFT', 'P-VALUE'],\n f.levels.map((l) => [l.level + (f.best === l.level ? c.green(' ✔') : ''), String(l.exposures), String(l.conversions), pct(l.rate), l.relativeLift === null ? '–' : pct(l.relativeLift, true), l.pValue === null ? '–' : l.pValue.toFixed(3)])\n )\n );\n }\n }\n if (r.status === 'finished') {\n console.log();\n console.log(c.dim(FINISHED_NEXT));\n }\n}\n\n/** Printed for finished tests, so a human or an agent knows the code still carries every variant. */\nconst FINISHED_NEXT = 'This test is finished but its variants are still in the code. Decide which variant to keep, then remove the test from the code and the config (agents: the splithub-ship skill).';\n\nfunction label(status: string): string {\n const icon = verdictIcon(status);\n switch (status) {\n case 'winner_found':\n return `${icon} WINNER`;\n case 'srm_detected':\n return `${icon} SRM`;\n case 'insufficient_sample':\n return `${icon} TOO EARLY`;\n case 'no_significant_difference':\n return `${icon} NO DIFFERENCE`;\n default:\n return `${icon} NO DATA`;\n }\n}\n","import { fetchStatus, resolveTarget } from '../api';\nimport { detectProject } from '../project';\nimport { bar, c, statusColor, table, verdictColor, verdictIcon } from '../ui';\n\nexport async function status(flags: Record<string, unknown>): Promise<void> {\n const target = resolveTarget(flags, detectProject());\n const data = await fetchStatus(target);\n const finished = data.experiments.filter((e) => e.status === 'finished').map((e) => e.experiment);\n const next = finished.length ? `Finished but still in the code: ${finished.join(', ')}. Decide which variant to keep, then remove the test from the code and the config (agents: the splithub-ship skill).` : null;\n if (flags.json) {\n console.log(JSON.stringify(next ? { ...data, next } : data, null, 2));\n return;\n }\n console.log(`${c.bold('SplitHub')} ${c.dim('·')} project ${c.cyan(data.project)} ${c.dim(`· ${target.url}`)}\\n`);\n if (data.experiments.length === 0) {\n console.log(c.dim('No experiments in splithub.config.ts yet. Run `splithub create`.'));\n return;\n }\n // Visitors as a bar relative to the busiest experiment, verdict with its icon.\n const maxVisitors = Math.max(1, ...data.experiments.map((e) => e.visitors));\n console.log(\n table(\n ['EXPERIMENT', 'KIND', 'STATUS', 'VISITORS', '', 'DAYS', 'VERDICT'],\n data.experiments.map((e) => [\n c.bold(e.experiment),\n e.kind,\n statusColor(e.status),\n String(e.visitors),\n bar(e.visitors, maxVisitors, 12, e.status === 'running' ? c.green : c.dim),\n e.days ? String(e.days) : '–',\n verdictColor(e.verdict, `${verdictIcon(e.goal ? e.verdict : null)} ${e.headline ?? (e.goal ? 'no data' : 'no goal')}`),\n ])\n )\n );\n if (next) console.log(`\\n${c.dim(next)}`);\n}\n","import { apiErrorMessage, cloudTarget } from '../api';\nimport { c } from '../ui';\nimport type { Flags } from './init';\n\ninterface Review {\n id: string;\n experiment: string | null;\n kind: string;\n trigger: string;\n body: string;\n model: string | null;\n createdAt: string;\n}\n\n/** `splithub review [<experiment>]`: the AI reviews stored in the cloud (Pro), newest first. */\nexport async function review(key: string | undefined, flags: Flags): Promise<void> {\n const target = cloudTarget(flags);\n if (!target.token) throw new Error('project API key required: run `npx splithub login`, or set SPLITHUB_API_KEY');\n const res = await fetch(`${target.url}/reviews${key ? `/${encodeURIComponent(key)}` : ''}`, { headers: { authorization: `Bearer ${target.token}` } });\n const data = (await res.json().catch(() => ({}))) as { reviews?: Review[]; error?: string };\n if (!res.ok) throw new Error(apiErrorMessage(res.status, data, `${target.url}/reviews responded ${res.status}`));\n const reviews = data.reviews ?? [];\n if (flags.json) {\n console.log(JSON.stringify({ experiment: key ?? null, reviews }, null, 2));\n return;\n }\n if (reviews.length === 0) {\n console.log(c.dim(key ? `no reviews for ${key} yet (Pro writes one at the start, when the verdict changes while running, and on finish; or click \"Review now\" in the dashboard)` : 'no reviews yet'));\n return;\n }\n for (const r of reviews) {\n console.log(`${c.bold(r.experiment ?? 'project')} ${c.dim(`· ${r.kind}${r.trigger && r.trigger !== 'manual' ? ` · ${r.trigger}` : ''} · ${new Date(r.createdAt).toLocaleString()}`)}`);\n console.log(r.body.trim());\n console.log();\n }\n}\n"],"mappings":";;;AAAA,SAAS,iBAAiB;;;ACA1B,YAAY,OAAO;AACnB,SAAS,mBAA+D;AACxE,SAAS,cAAAA,aAAY,WAAW,iBAAAC,sBAAqB;AACrD,SAAS,QAAAC,OAAM,gBAAgB;;;ACH/B,SAAS,wBAAyF;AAClG,SAAS,cAAc,qBAAqB;AAC5C,SAAS,qBAAqB;AAG9B,eAAsB,WAAW,MAAuC;AACtE,QAAM,EAAE,WAAW,IAAI,MAAM,OAAO,MAAM;AAC1C,QAAM,OAAO,WAAW,cAAc,IAAI,EAAE,MAAM,EAAE,SAAS,OAAO,aAAa,MAAM,CAAC;AACxF,QAAM,MAAO,MAAM,KAAK,OAAO,MAAM,EAAE,SAAS,KAAK,CAAC;AACtD,MAAI,CAAC,iBAAiB,GAAG,GAAG;AAC1B,UAAM,IAAI,MAAM,GAAG,IAAI,mEAAmE;AAAA,EAC5F;AACA,SAAO;AACT;AAEA,SAAS,WAAW,KAAqB;AACvC,QAAM,MAAM,IAAI,QAAQ,uBAAuB,MAAM;AACrD,SAAO,IAAI,OAAO,0BAA0B,GAAG,uBAAuB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C;AACvF,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["existsSync","writeFileSync","join","status","readFileSync","p","dev","status","text","k","status","join","existsSync","writeFileSync","readFileSync","existsSync","mkdirSync","readFileSync","writeFileSync","join","resolve","readFileSync","status","text","resolve","existsSync","readFileSync","join","relative","relative","join","existsSync","readFileSync","label","p","existsSync","mkdirSync","writeFileSync","dirname","join","relative","label","existsSync","mkdirSync","readFileSync","writeFileSync","join","relative","existsSync","readFileSync","mkdirSync","writeFileSync","join","relative","str","existsSync","mkdirSync","dirname","writeFileSync","relative","cancel","k","join","relative","status","relative","p","readFileSync","relative","relative","status","readFileSync"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "splithub",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.9",
|
|
4
4
|
"description": "A/B testing for your app in one command. Create a test, start it, read a plain verdict. Works for you and for your coding agent.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -14,8 +14,8 @@
|
|
|
14
14
|
"dependencies": {
|
|
15
15
|
"@clack/prompts": "^0.9.1",
|
|
16
16
|
"jiti": "^2.4.2",
|
|
17
|
-
"@splithub/core": "0.1.
|
|
18
|
-
"@splithub/node": "0.1.
|
|
17
|
+
"@splithub/core": "0.1.9",
|
|
18
|
+
"@splithub/node": "0.1.9"
|
|
19
19
|
},
|
|
20
20
|
"devDependencies": {
|
|
21
21
|
"@types/node": "^22.13.0",
|