@open-product-primer/cli 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Eshane
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,31 @@
1
+ # @open-product-primer/cli
2
+
3
+ Global CLI for [Open Product Primer](https://github.com/eshraw/open-product-primer) — product decisions, sequencing, and KPI tracking in your repository.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install -g @open-product-primer/cli@latest
9
+ ```
10
+
11
+ ## Quick start
12
+
13
+ ```bash
14
+ cd your-project
15
+ oprim init
16
+ oprim doctor
17
+ oprim update
18
+ ```
19
+
20
+ Bin aliases: `open-product-primer`, `oprim`.
21
+
22
+ ## Commands
23
+
24
+ | Command | Description |
25
+ |---------|-------------|
26
+ | `oprim init` | Scaffold `primer/` workspace (idempotent) |
27
+ | `oprim update` | Refresh `/oprim:*` assistant commands and skills |
28
+ | `oprim doctor` | Verify scaffold, integrations, and measurement env |
29
+ | `oprim measure` | Run KPI measurement pipeline for a bet |
30
+
31
+ Full documentation: [github.com/eshraw/open-product-primer](https://github.com/eshraw/open-product-primer).
package/bin/oprim.js ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ require('../dist/cli.js');
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,22 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __importDefault = (this && this.__importDefault) || function (mod) {
4
+ return (mod && mod.__esModule) ? mod : { "default": mod };
5
+ };
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ const commander_1 = require("commander");
8
+ const init_1 = require("./commands/init");
9
+ const update_1 = require("./commands/update");
10
+ const doctor_1 = require("./commands/doctor");
11
+ const measure_1 = require("./commands/measure");
12
+ const package_json_1 = __importDefault(require("../package.json"));
13
+ const program = new commander_1.Command();
14
+ program
15
+ .name('open-product-primer')
16
+ .description('Open Product Primer — product decisions, sequencing, and KPI tracking')
17
+ .version(package_json_1.default.version);
18
+ program.addCommand((0, init_1.initCommand)());
19
+ program.addCommand((0, update_1.updateCommand)());
20
+ program.addCommand((0, doctor_1.doctorCommand)());
21
+ program.addCommand((0, measure_1.measureCommand)());
22
+ program.parse();
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare function doctorCommand(): Command;
@@ -0,0 +1,176 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.doctorCommand = doctorCommand;
40
+ const commander_1 = require("commander");
41
+ const path = __importStar(require("path"));
42
+ const fs = __importStar(require("fs"));
43
+ const chalk_1 = __importDefault(require("chalk"));
44
+ const detect_1 = require("../lib/detect");
45
+ const measure_1 = require("../lib/measure");
46
+ const AGENT_DIRS = {
47
+ claude: '.claude',
48
+ cursor: '.cursor',
49
+ };
50
+ function doctorCommand() {
51
+ return new commander_1.Command('doctor')
52
+ .description('Check Open Product Primer install health and integration readiness')
53
+ .action(() => {
54
+ const projectRoot = process.cwd();
55
+ const checks = [];
56
+ const primerDir = path.join(projectRoot, 'primer');
57
+ for (const dir of ['primer', 'primer/decisions', 'primer/bets', 'primer/reviews', 'primer/templates']) {
58
+ const exists = fs.existsSync(path.join(projectRoot, dir));
59
+ checks.push({
60
+ name: `scaffold: ${dir}/`,
61
+ pass: exists,
62
+ note: exists ? undefined : "Run 'oprim init' to create",
63
+ required: true,
64
+ });
65
+ }
66
+ const configPath = path.join(primerDir, 'config.yaml');
67
+ const configExists = fs.existsSync(configPath);
68
+ checks.push({
69
+ name: 'config: primer/config.yaml',
70
+ pass: configExists,
71
+ note: configExists ? undefined : "Run 'oprim init' to create",
72
+ required: true,
73
+ });
74
+ const sequenceExists = fs.existsSync(path.join(primerDir, 'sequence.yaml'));
75
+ checks.push({
76
+ name: 'config: primer/sequence.yaml',
77
+ pass: sequenceExists,
78
+ note: sequenceExists ? undefined : "Run 'oprim init' to create",
79
+ required: true,
80
+ });
81
+ const openspecPresent = fs.existsSync(path.join(projectRoot, 'openspec'));
82
+ checks.push({
83
+ name: 'integration: OpenSpec',
84
+ pass: openspecPresent,
85
+ note: openspecPresent ? undefined : 'Optional — install OpenSpec to enable change linking',
86
+ required: false,
87
+ });
88
+ const graphifyPresent = fs.existsSync(path.join(projectRoot, 'graphify-out'));
89
+ checks.push({
90
+ name: 'integration: Graphify',
91
+ pass: graphifyPresent,
92
+ note: graphifyPresent ? undefined : 'Optional — install Graphify for traceability',
93
+ required: false,
94
+ });
95
+ // 7.1–7.3: criteria-aware credential checks
96
+ const hasAmplitudeMetrics = (0, measure_1.scanCriteriaForSourceType)(projectRoot, 'amplitude');
97
+ const hasBigQueryMetrics = (0, measure_1.scanCriteriaForSourceType)(projectRoot, 'bigquery');
98
+ const amplitudeKeySet = !!process.env['AMPLITUDE_API_KEY'];
99
+ const googleCredsSet = !!process.env['GOOGLE_APPLICATION_CREDENTIALS'];
100
+ checks.push({
101
+ name: 'measurement: AMPLITUDE_API_KEY',
102
+ pass: !hasAmplitudeMetrics || amplitudeKeySet,
103
+ note: hasAmplitudeMetrics && !amplitudeKeySet
104
+ ? 'Required for amplitude metrics — set AMPLITUDE_API_KEY to enable oprim measure'
105
+ : hasAmplitudeMetrics
106
+ ? undefined
107
+ : 'No amplitude metrics in criteria.yaml — not required',
108
+ required: false,
109
+ });
110
+ checks.push({
111
+ name: 'measurement: GOOGLE_APPLICATION_CREDENTIALS',
112
+ pass: !hasBigQueryMetrics || googleCredsSet,
113
+ note: hasBigQueryMetrics && !googleCredsSet
114
+ ? 'Required for bigquery metrics — set GOOGLE_APPLICATION_CREDENTIALS to enable oprim measure'
115
+ : hasBigQueryMetrics
116
+ ? undefined
117
+ : 'No bigquery metrics in criteria.yaml — not required',
118
+ required: false,
119
+ });
120
+ // ── Agent environment checks ──────────────────────────────────────────────
121
+ const configAgents = (0, detect_1.readAgentsFromConfig)(projectRoot);
122
+ if (configAgents !== null) {
123
+ // Config-declared agents: check each declared agent's directory exists
124
+ for (const agent of configAgents) {
125
+ const dir = AGENT_DIRS[agent];
126
+ if (!dir)
127
+ continue;
128
+ const exists = fs.existsSync(path.join(projectRoot, dir));
129
+ checks.push({
130
+ name: `agent: ${agent} environment (${dir}/)`,
131
+ pass: exists,
132
+ note: exists
133
+ ? undefined
134
+ : `${dir}/ directory not found — declared in config but missing`,
135
+ required: false,
136
+ });
137
+ }
138
+ }
139
+ else {
140
+ // Legacy: check for installed commands by directory presence
141
+ const claudeInstalled = fs.existsSync(path.join(projectRoot, '.claude', 'commands', 'oprim'));
142
+ checks.push({
143
+ name: 'agent: Claude /oprim:* commands',
144
+ pass: claudeInstalled,
145
+ note: claudeInstalled ? undefined : "Run 'oprim update' to install",
146
+ required: false,
147
+ });
148
+ const cursorInstalled = fs.existsSync(path.join(projectRoot, '.cursor', 'commands', 'oprim-promote.md')) ||
149
+ fs.existsSync(path.join(projectRoot, '.cursor', 'commands', 'oprim-sequence.md'));
150
+ checks.push({
151
+ name: 'agent: Cursor /oprim-* commands',
152
+ pass: cursorInstalled,
153
+ note: cursorInstalled ? undefined : "Run 'oprim update' to install",
154
+ required: false,
155
+ });
156
+ }
157
+ console.log(chalk_1.default.bold('Open Product Primer') + ' — health check\n');
158
+ for (const check of checks) {
159
+ const icon = check.pass ? chalk_1.default.green('✓') : check.required ? chalk_1.default.red('✗') : chalk_1.default.yellow('○');
160
+ const label = check.pass ? chalk_1.default.white(check.name) : chalk_1.default.gray(check.name);
161
+ const note = check.note ? chalk_1.default.dim(` (${check.note})`) : '';
162
+ console.log(` ${icon} ${label}${note}`);
163
+ }
164
+ const passed = checks.filter((c) => c.pass).length;
165
+ const requiredFailed = checks.filter((c) => c.required && !c.pass).length;
166
+ console.log(`\n${passed}/${checks.length} checks passed.`);
167
+ if (requiredFailed === 0) {
168
+ console.log(chalk_1.default.green('Core setup is healthy.'));
169
+ }
170
+ else {
171
+ console.log(chalk_1.default.yellow(`${requiredFailed} required check(s) failed. Run `) +
172
+ chalk_1.default.cyan('oprim init') +
173
+ chalk_1.default.yellow(' to fix.'));
174
+ }
175
+ });
176
+ }
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare function initCommand(): Command;
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.initCommand = initCommand;
40
+ const commander_1 = require("commander");
41
+ const path = __importStar(require("path"));
42
+ const chalk_1 = __importDefault(require("chalk"));
43
+ const detect_1 = require("../lib/detect");
44
+ const scaffold_1 = require("../lib/scaffold");
45
+ const install_agent_1 = require("../lib/install-agent");
46
+ const templates_1 = require("../lib/templates");
47
+ function initCommand() {
48
+ return new commander_1.Command('init')
49
+ .description('Initialize Open Product Primer in the current repository')
50
+ .option('--name <name>', 'project name (defaults to directory name)')
51
+ .option('--agent <name>', 'AI agent to install skills for (repeatable; supported: claude, cursor)', (val, prev) => [...prev, val], [])
52
+ .action(async (opts) => {
53
+ const projectRoot = process.cwd();
54
+ const projectName = opts.name ?? path.basename(projectRoot);
55
+ console.log(chalk_1.default.bold('Open Product Primer') + ' — initializing project workspace...\n');
56
+ const openspec = (0, detect_1.detectOpenSpec)(projectRoot);
57
+ const graphify = (0, detect_1.detectGraphify)(projectRoot);
58
+ if (openspec.detected)
59
+ console.log(chalk_1.default.green('✓') + ' OpenSpec detected');
60
+ if (graphify.detected)
61
+ console.log(chalk_1.default.green('✓') + ' Graphify detected');
62
+ const primerDir = path.join(projectRoot, 'primer');
63
+ (0, scaffold_1.ensureDir)(path.join(primerDir, 'decisions'));
64
+ (0, scaffold_1.ensureDir)(path.join(primerDir, 'bets'));
65
+ (0, scaffold_1.ensureDir)(path.join(primerDir, 'reviews'));
66
+ (0, scaffold_1.ensureDir)(path.join(primerDir, 'templates'));
67
+ const configWritten = (0, scaffold_1.writeFileIfAbsent)(path.join(primerDir, 'config.yaml'), (0, templates_1.configTemplate)(projectName, openspec.detected, graphify.detected));
68
+ const sequenceWritten = (0, scaffold_1.writeFileIfAbsent)(path.join(primerDir, 'sequence.yaml'), templates_1.sequenceTemplate);
69
+ (0, scaffold_1.writeFile)(path.join(primerDir, 'templates', 'pdr.md'), templates_1.pdrTemplate);
70
+ (0, scaffold_1.writeFile)(path.join(primerDir, 'templates', 'bet-decision.md'), templates_1.betDecisionTemplate);
71
+ (0, scaffold_1.writeFile)(path.join(primerDir, 'templates', 'criteria.yaml'), templates_1.criteriaTemplate);
72
+ (0, scaffold_1.writeFile)(path.join(primerDir, 'templates', 'kpi-review.md'), templates_1.kpiReviewTemplate);
73
+ (0, scaffold_1.writeFileIfAbsent)(path.join(primerDir, 'decisions', '.gitkeep'), '');
74
+ (0, scaffold_1.writeFileIfAbsent)(path.join(primerDir, 'bets', '.gitkeep'), '');
75
+ (0, scaffold_1.writeFileIfAbsent)(path.join(primerDir, 'reviews', '.gitkeep'), '');
76
+ console.log('\n' + chalk_1.default.green('✓') + ' primer/ workspace created');
77
+ const configStatus = configWritten ? 'written' : 'preserved (already exists)';
78
+ const sequenceStatus = sequenceWritten ? 'written' : 'preserved (already exists)';
79
+ console.log(' ' + chalk_1.default.gray('primer/config.yaml') + ' — ' + configStatus);
80
+ console.log(' ' + chalk_1.default.gray('primer/sequence.yaml') + ' — ' + sequenceStatus);
81
+ console.log(' ' + chalk_1.default.gray('primer/templates/') + ' — refreshed');
82
+ // ── Agent selection ───────────────────────────────────────────────────────
83
+ let selectedAgents;
84
+ const flaggedAgents = opts.agent;
85
+ if (flaggedAgents.length > 0) {
86
+ const invalid = flaggedAgents.filter((a) => !install_agent_1.SUPPORTED_AGENTS.includes(a));
87
+ if (invalid.length > 0) {
88
+ console.error(chalk_1.default.red(`\nUnknown agent(s): ${invalid.join(', ')}`));
89
+ console.error(`Supported agents: ${install_agent_1.SUPPORTED_AGENTS.join(', ')}`);
90
+ process.exit(1);
91
+ }
92
+ selectedAgents = flaggedAgents;
93
+ }
94
+ else {
95
+ const existingAgents = (0, detect_1.readAgentsFromConfig)(projectRoot);
96
+ if (existingAgents !== null) {
97
+ selectedAgents = existingAgents;
98
+ if (selectedAgents.length > 0) {
99
+ console.log('\n' + chalk_1.default.dim(`Re-installing for configured agents: ${selectedAgents.join(', ')}`));
100
+ }
101
+ }
102
+ else {
103
+ console.log('');
104
+ const { checkbox } = await Promise.resolve().then(() => __importStar(require('@inquirer/prompts')));
105
+ selectedAgents = await checkbox({
106
+ message: 'Which AI tools should /oprim:* skills be installed for?',
107
+ choices: [
108
+ { name: 'Claude Code', value: 'claude' },
109
+ { name: 'Cursor', value: 'cursor' },
110
+ ],
111
+ });
112
+ }
113
+ }
114
+ (0, detect_1.writeAgentsToConfig)(selectedAgents, projectRoot);
115
+ if (selectedAgents.length === 0) {
116
+ console.log('\n' +
117
+ chalk_1.default.yellow('No agents selected.') +
118
+ ' Run ' +
119
+ chalk_1.default.cyan('oprim update') +
120
+ ' after configuring an AI tool to install /oprim:* skills.');
121
+ }
122
+ else {
123
+ console.log('\n' + chalk_1.default.bold('Installing agent skills...'));
124
+ for (const agent of selectedAgents) {
125
+ (0, install_agent_1.installAgentSkills)(agent, projectRoot);
126
+ }
127
+ console.log('\n' + chalk_1.default.green('✓') + ` Agent skills installed: ${selectedAgents.join(', ')}`);
128
+ }
129
+ console.log('\nRun ' + chalk_1.default.cyan('oprim doctor') + ' to verify your setup.');
130
+ });
131
+ }
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare function measureCommand(): Command;
@@ -0,0 +1,207 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.measureCommand = measureCommand;
40
+ const commander_1 = require("commander");
41
+ const fs = __importStar(require("fs"));
42
+ const path = __importStar(require("path"));
43
+ const yaml = __importStar(require("js-yaml"));
44
+ const chalk_1 = __importDefault(require("chalk"));
45
+ const measure_1 = require("../lib/measure");
46
+ function measureCommand() {
47
+ return new commander_1.Command('measure')
48
+ .description('Generate and run KPI measurements for a bet')
49
+ .argument('<bet-id>', 'BET ID (e.g. BET-042)')
50
+ .option('--dry-run', 'generate definition files without calling APIs')
51
+ .action(async (betId, opts) => {
52
+ const projectRoot = process.cwd();
53
+ const betDir = path.join(projectRoot, 'primer', 'bets', betId);
54
+ // 1.3 — bet directory validation
55
+ if (!fs.existsSync(betDir)) {
56
+ console.error(chalk_1.default.red(`Bet not found: primer/bets/${betId}/`));
57
+ console.error(`Use ${chalk_1.default.cyan('/oprim:bet')} to create the bet first.`);
58
+ process.exit(1);
59
+ }
60
+ // 1.4 — criteria.yaml validation
61
+ const criteriaPath = path.join(betDir, 'criteria.yaml');
62
+ if (!fs.existsSync(criteriaPath)) {
63
+ console.error(chalk_1.default.red(`No criteria.yaml found for ${betId}.`));
64
+ console.error(`Run ${chalk_1.default.cyan('/oprim:criteria ' + betId)} to create one.`);
65
+ process.exit(1);
66
+ }
67
+ let criteria;
68
+ try {
69
+ const raw = fs.readFileSync(criteriaPath, 'utf-8');
70
+ const parsed = yaml.load(raw);
71
+ if (!parsed?.metrics)
72
+ throw new Error('Missing metrics field');
73
+ criteria = parsed;
74
+ }
75
+ catch (err) {
76
+ console.error(chalk_1.default.red(`Invalid criteria.yaml: ${err.message}`));
77
+ process.exit(1);
78
+ }
79
+ // 2.5 — create measurements/ directory
80
+ const measurementsDir = path.join(betDir, 'measurements');
81
+ if (!fs.existsSync(measurementsDir)) {
82
+ fs.mkdirSync(measurementsDir, { recursive: true });
83
+ }
84
+ console.log(chalk_1.default.bold(`oprim measure ${betId}`) + '\n');
85
+ // 2.1–2.4 — generate definition files
86
+ for (const metric of criteria.metrics) {
87
+ if (metric.source.type === 'amplitude') {
88
+ const def = (0, measure_1.generateAmplitudeDefinition)(metric);
89
+ const outPath = path.join(measurementsDir, `amplitude-${metric.id}.json`);
90
+ fs.writeFileSync(outPath, JSON.stringify(def, null, 2), 'utf-8');
91
+ console.log(chalk_1.default.green('✓') + ` Generated amplitude-${metric.id}.json`);
92
+ }
93
+ else if (metric.source.type === 'bigquery') {
94
+ const sql = (0, measure_1.generateBigQuerySQL)(metric);
95
+ const outPath = path.join(measurementsDir, `bigquery-${metric.id}.sql`);
96
+ fs.writeFileSync(outPath, sql, 'utf-8');
97
+ console.log(chalk_1.default.green('✓') + ` Generated bigquery-${metric.id}.sql`);
98
+ }
99
+ }
100
+ // 2.6 — dry-run exits after generation
101
+ if (opts.dryRun) {
102
+ console.log('\n' + chalk_1.default.dim('--dry-run: skipping API execution'));
103
+ console.log(`\nDefinition files written to primer/bets/${betId}/measurements/`);
104
+ return;
105
+ }
106
+ // Execute metrics sequentially
107
+ console.log('\nExecuting metrics...');
108
+ const results = [];
109
+ const amplitudeKey = process.env['AMPLITUDE_API_KEY'];
110
+ const hasGoogleCreds = !!process.env['GOOGLE_APPLICATION_CREDENTIALS'];
111
+ for (const metric of criteria.metrics) {
112
+ if (metric.source.type === 'amplitude') {
113
+ results.push(await executeAmplitudeMetric(metric, measurementsDir, amplitudeKey));
114
+ }
115
+ else if (metric.source.type === 'bigquery') {
116
+ results.push(await executeBigQueryMetric(metric, measurementsDir, hasGoogleCreds));
117
+ }
118
+ }
119
+ // 5.2–5.3 — write run result (overwrites existing file for same date)
120
+ const runDate = new Date().toISOString().slice(0, 10);
121
+ (0, measure_1.writeRunResult)(betId, measurementsDir, results, runDate);
122
+ console.log('\n' + chalk_1.default.green('✓') + ` Run result: measurements/run-${runDate}.yaml`);
123
+ const hits = results.filter((r) => r.status === 'hit').length;
124
+ const misses = results.filter((r) => r.status === 'missed').length;
125
+ const pending = results.filter((r) => r.status === 'pending').length;
126
+ console.log(`\n ${chalk_1.default.green(`${hits} hit`)} ${chalk_1.default.red(`${misses} missed`)} ${chalk_1.default.yellow(`${pending} pending`)}`);
127
+ console.log(`\nRun ${chalk_1.default.cyan('/oprim:review ' + betId)} to create a review.`);
128
+ });
129
+ }
130
+ // ─── Amplitude execution (3.1–3.4) ───────────────────────────────────────────
131
+ async function executeAmplitudeMetric(metric, measurementsDir, apiKey) {
132
+ // 3.1 — skip if no API key
133
+ if (!apiKey) {
134
+ console.log(chalk_1.default.yellow('○') + ` ${metric.name} — skipped (AMPLITUDE_API_KEY not set)`);
135
+ return {
136
+ id: metric.id,
137
+ name: metric.name,
138
+ source: 'amplitude',
139
+ actual: null,
140
+ target: metric.target,
141
+ status: 'pending',
142
+ notes: 'AMPLITUDE_API_KEY not set — metric skipped',
143
+ };
144
+ }
145
+ const defPath = path.join(measurementsDir, `amplitude-${metric.id}.json`);
146
+ try {
147
+ // 3.2–3.3 — call API and extract scalar
148
+ const { actual, notes } = await (0, measure_1.runAmplitudeMetric)(defPath, apiKey);
149
+ const status = (0, measure_1.classifyStatus)(actual, metric.target);
150
+ const icon = status === 'hit' ? chalk_1.default.green('✓') : status === 'missed' ? chalk_1.default.red('✗') : chalk_1.default.yellow('○');
151
+ console.log(`${icon} ${metric.name}: actual=${actual ?? 'n/a'} target=${metric.target} (${status})`);
152
+ return { id: metric.id, name: metric.name, source: 'amplitude', actual, target: metric.target, status, notes };
153
+ }
154
+ catch (err) {
155
+ // 3.4 — non-2xx or network error: mark pending, continue
156
+ const notes = `Amplitude error: ${err.message}`;
157
+ console.log(chalk_1.default.yellow('○') + ` ${metric.name} — ${notes}`);
158
+ return {
159
+ id: metric.id,
160
+ name: metric.name,
161
+ source: 'amplitude',
162
+ actual: null,
163
+ target: metric.target,
164
+ status: 'pending',
165
+ notes,
166
+ };
167
+ }
168
+ }
169
+ // ─── BigQuery execution (4.1–4.4) ────────────────────────────────────────────
170
+ async function executeBigQueryMetric(metric, measurementsDir, hasCredentials) {
171
+ // 4.1 — skip if no credentials
172
+ if (!hasCredentials) {
173
+ console.log(chalk_1.default.yellow('○') + ` ${metric.name} — skipped (GOOGLE_APPLICATION_CREDENTIALS not set)`);
174
+ return {
175
+ id: metric.id,
176
+ name: metric.name,
177
+ source: 'bigquery',
178
+ actual: null,
179
+ target: metric.target,
180
+ status: 'pending',
181
+ notes: 'GOOGLE_APPLICATION_CREDENTIALS not set — metric skipped',
182
+ };
183
+ }
184
+ const sqlPath = path.join(measurementsDir, `bigquery-${metric.id}.sql`);
185
+ try {
186
+ // 4.2–4.3 — submit job, poll, extract first-row scalar
187
+ const { actual, notes } = await (0, measure_1.runBigQueryMetric)(sqlPath);
188
+ const status = (0, measure_1.classifyStatus)(actual, metric.target);
189
+ const icon = status === 'hit' ? chalk_1.default.green('✓') : status === 'missed' ? chalk_1.default.red('✗') : chalk_1.default.yellow('○');
190
+ console.log(`${icon} ${metric.name}: actual=${actual ?? 'n/a'} target=${metric.target} (${status})`);
191
+ return { id: metric.id, name: metric.name, source: 'bigquery', actual, target: metric.target, status, notes };
192
+ }
193
+ catch (err) {
194
+ // 4.4 — job failure or zero rows: mark pending, continue
195
+ const notes = `BigQuery error: ${err.message}`;
196
+ console.log(chalk_1.default.yellow('○') + ` ${metric.name} — ${notes}`);
197
+ return {
198
+ id: metric.id,
199
+ name: metric.name,
200
+ source: 'bigquery',
201
+ actual: null,
202
+ target: metric.target,
203
+ status: 'pending',
204
+ notes,
205
+ };
206
+ }
207
+ }
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare function updateCommand(): Command;