@blackbelt-technology/pi-dashboard-cost-estimator 0.7.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.
Files changed (38) hide show
  1. package/.pi/skills/software-cost-estimator/SKILL.md +200 -0
  2. package/.pi/skills/software-cost-estimator/assets/calibration/reference-classes.md +126 -0
  3. package/.pi/skills/software-cost-estimator/assets/calibration/wms-reference.yaml +217 -0
  4. package/.pi/skills/software-cost-estimator/assets/example-quality-hub.yaml +230 -0
  5. package/.pi/skills/software-cost-estimator/assets/rates.default.yaml +106 -0
  6. package/.pi/skills/software-cost-estimator/assets/templates/architecture-plan.md +115 -0
  7. package/.pi/skills/software-cost-estimator/assets/templates/offer-summary.md +99 -0
  8. package/.pi/skills/software-cost-estimator/references/ai-delivery-modes.md +276 -0
  9. package/.pi/skills/software-cost-estimator/references/business-case.md +134 -0
  10. package/.pi/skills/software-cost-estimator/references/nfr-catalog.md +112 -0
  11. package/.pi/skills/software-cost-estimator/references/rates.md +84 -0
  12. package/.pi/skills/software-cost-estimator/references/role-model.md +109 -0
  13. package/.pi/skills/software-cost-estimator/references/sizing-methods.md +147 -0
  14. package/README.md +113 -0
  15. package/bin/calibrate-sessions.mjs +12 -0
  16. package/bin/calibrate.mjs +12 -0
  17. package/bin/estimate.mjs +12 -0
  18. package/package.json +96 -0
  19. package/src/bin/calibrate-sessions.ts +247 -0
  20. package/src/bin/calibrate.ts +77 -0
  21. package/src/bin/estimate.ts +129 -0
  22. package/src/client/index.tsx +300 -0
  23. package/src/configSchema.json +56 -0
  24. package/src/engine/businesscase.ts +139 -0
  25. package/src/engine/defaults.ts +354 -0
  26. package/src/engine/effort.ts +119 -0
  27. package/src/engine/estimate.ts +135 -0
  28. package/src/engine/modes.ts +312 -0
  29. package/src/engine/report.ts +239 -0
  30. package/src/engine/roles.ts +82 -0
  31. package/src/engine/simulate.ts +114 -0
  32. package/src/engine/sizing.ts +108 -0
  33. package/src/engine/types.ts +288 -0
  34. package/src/engine/workbook.ts +143 -0
  35. package/src/engine/xlsx.ts +228 -0
  36. package/src/engine/yaml.ts +205 -0
  37. package/src/server/index.ts +123 -0
  38. package/src/telemetry/sessions.ts +380 -0
@@ -0,0 +1,247 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Calibrate the AI delivery modes from real pi session telemetry.
4
+ *
5
+ * node scripts/calibrate-sessions.ts
6
+ * node scripts/calibrate-sessions.ts --project pi-agent-dashboard --actual-days 58
7
+ * node scripts/calibrate-sessions.ts --since 2026-01-01 --gap-cap 15 --json
8
+ *
9
+ * This is the strongest calibration available, because it measures rather than
10
+ * assumes the two things the model otherwise guesses:
11
+ *
12
+ * 1. STEERING TIME — active human hours, from per-record timestamps with long
13
+ * gaps capped (a gap is a break, not work).
14
+ * 2. AGENT COST — real billed cost and token mix, from the session metadata.
15
+ *
16
+ * Supplying `--actual-days` for a project additionally solves the AI-steered
17
+ * OVERHEAD MULTIPLIER directly: total delivered man-days ÷ measured steering days.
18
+ * That single number is what turns an AI-assisted quote from a guess into a
19
+ * measurement.
20
+ */
21
+
22
+ import { writeFileSync } from 'node:fs';
23
+
24
+ import { aggregateByProject, compareSubscription, defaultSessionRoot, measureConstants, scanSessions } from "../telemetry/sessions.js";
25
+ import { ACEM_DEFAULTS, DEFAULT_HOURS_PER_DAY, STEERING_OVERHEAD, SUBSCRIPTION_PLANS } from "../engine/defaults.js";
26
+
27
+ interface Options {
28
+ root: string;
29
+ gapCap: number;
30
+ project?: string;
31
+ since?: string;
32
+ actualDays?: number;
33
+ hoursPerDay: number;
34
+ json?: string;
35
+ top: number;
36
+ plan?: string;
37
+ seatMonthly?: number;
38
+ seats: number;
39
+ }
40
+
41
+ function parseArgs(argv: string[]): Options {
42
+ const opts: Options = {
43
+ root: defaultSessionRoot(),
44
+ gapCap: 15,
45
+ hoursPerDay: DEFAULT_HOURS_PER_DAY,
46
+ top: 15,
47
+ seats: 1,
48
+ };
49
+ for (let i = 0; i < argv.length; i++) {
50
+ const arg = argv[i];
51
+ if (arg === '--root') opts.root = argv[++i];
52
+ else if (arg === '--gap-cap') opts.gapCap = Number(argv[++i]);
53
+ else if (arg === '--project') opts.project = argv[++i];
54
+ else if (arg === '--since') opts.since = argv[++i];
55
+ else if (arg === '--actual-days') opts.actualDays = Number(argv[++i]);
56
+ else if (arg === '--hours-per-day') opts.hoursPerDay = Number(argv[++i]);
57
+ else if (arg === '--top') opts.top = Number(argv[++i]);
58
+ else if (arg === '--json') opts.json = argv[++i];
59
+ else if (arg === '--plan') opts.plan = argv[++i];
60
+ else if (arg === '--seat-monthly') opts.seatMonthly = Number(argv[++i]);
61
+ else if (arg === '--seats') opts.seats = Number(argv[++i]);
62
+ else if (arg === '--plans') {
63
+ console.log('\nSubscription plans (USD per seat per month):');
64
+ for (const [key, plan] of Object.entries(SUBSCRIPTION_PLANS)) {
65
+ console.log(` ${key.padEnd(20)} $${String(plan.monthly).padStart(4)} ${plan.label} (${plan.src})`);
66
+ }
67
+ console.log('');
68
+ process.exit(0);
69
+ }
70
+ else if (arg === '-h' || arg === '--help') {
71
+ usage();
72
+ process.exit(0);
73
+ }
74
+ }
75
+ return opts;
76
+ }
77
+
78
+ function usage(): void {
79
+ console.log(
80
+ [
81
+ 'Usage: calibrate-sessions.ts [options]',
82
+ '',
83
+ ' --project SUBSTR filter to projects whose path contains SUBSTR',
84
+ ' --actual-days N delivered man-days for that project; solves the overhead multiplier',
85
+ ' --since ISO-DATE ignore sessions started before this date',
86
+ ' --gap-cap MIN gap above which time counts as a break (default 15)',
87
+ ' --hours-per-day N productive hours per man-day (default 8)',
88
+ ' --plan KEY seat plan to compare against (see --plans)',
89
+ ' --seat-monthly N explicit USD per seat per month, overrides --plan',
90
+ ' --seats N number of seats (default 1)',
91
+ ' --plans list the seat-plan catalogue and exit',
92
+ ' --top N projects to list (default 15)',
93
+ ' --root DIR session store (default ~/.pi/agent/sessions)',
94
+ ' --json FILE also write the full result as JSON',
95
+ ].join('\n'),
96
+ );
97
+ }
98
+
99
+ const n = (v: number, d = 0) => v.toLocaleString('en-US', { minimumFractionDigits: d, maximumFractionDigits: d });
100
+
101
+ function main(): void {
102
+ const opts = parseArgs(process.argv.slice(2));
103
+ const records = scanSessions({
104
+ root: opts.root,
105
+ gapCapMinutes: opts.gapCap,
106
+ project: opts.project,
107
+ since: opts.since,
108
+ });
109
+
110
+ if (records.length === 0) {
111
+ console.log(`\nNo usable sessions found under ${opts.root}`);
112
+ console.log('Check --root, or relax --project / --since.\n');
113
+ process.exit(1);
114
+ }
115
+
116
+ const measured = measureConstants(records, opts.hoursPerDay);
117
+ const projects = aggregateByProject(records, opts.hoursPerDay);
118
+
119
+ console.log(`\nSession calibration — ${records.length} sessions${opts.project ? ` matching "${opts.project}"` : ''}`);
120
+ console.log(` gap cap ${opts.gapCap} min · ${opts.hoursPerDay} h/man-day · root ${opts.root}`);
121
+
122
+ console.log('\n--- MEASURED EFFORT ---');
123
+ console.log(` active steering time ${n(measured.activeHours, 1)} h (${n(measured.steeringDays, 1)} steering-days)`);
124
+ console.log(` human turns per hour ${n(measured.assistantPerHumanTurn, 1)} assistant turns per human turn`);
125
+ console.log(` tool calls per hour ${n(measured.toolCallsPerHour, 1)}`);
126
+
127
+ console.log('\n--- METER-EQUIVALENT COST (theoretical pay-as-you-go) ---');
128
+ console.log(` total meter-equivalent $${n(measured.totalCost, 2)}`);
129
+ console.log(` per steering hour $${n(measured.costPerSteeringHour, 2)}`);
130
+ console.log(` per steering day $${n(measured.costPerSteeringDay, 2)}`);
131
+ console.log(` per active month $${n(measured.meterPerMonth, 2)} over ${measured.activeMonths} active months`);
132
+ console.log(` output tokens per hour ${n(measured.outputTokensPerHour)}`);
133
+ console.log(' NOTE: this is what the meter WOULD have charged. It is not cash out when');
134
+ console.log(' capacity is bought on a flat subscription.');
135
+ if (measured.unmeteredHourShare > 0.01) {
136
+ console.log(
137
+ ` ! ${(measured.unmeteredHourShare * 100).toFixed(1)}% of hours ran on models the meter priced at $0 ` +
138
+ '(routed/subscription-billed). The $/h above is understated by that much.',
139
+ );
140
+ }
141
+
142
+ // --- what it actually costs on a seat plan ---
143
+ const catalogue = opts.plan ? SUBSCRIPTION_PLANS[opts.plan] : undefined;
144
+ if (opts.plan && !catalogue && opts.seatMonthly == null) {
145
+ console.log(`\n ! Unknown plan "${opts.plan}". Run with --plans to list the catalogue.`);
146
+ }
147
+ const seatMonthly = opts.seatMonthly ?? catalogue?.monthly;
148
+ if (seatMonthly != null) {
149
+ const monthlyTotal = seatMonthly * opts.seats;
150
+ const cmp = compareSubscription(measured, monthlyTotal);
151
+ const label = catalogue ? catalogue.label : 'custom plan';
152
+ console.log('\n--- ACTUAL COST ON A SUBSCRIPTION ---');
153
+ console.log(` plan ${opts.seats}x ${label} @ $${n(seatMonthly, 0)}/seat/mo = $${n(monthlyTotal, 0)}/mo`);
154
+ console.log(` over ${cmp.months} active months $${n(cmp.subscriptionCost, 2)} <-- CASH OUT`);
155
+ console.log(` effective per steering h $${n(cmp.effectiveCostPerHour, 2)} (vs $${n(cmp.meteredCostPerHour, 2)} metered)`);
156
+ console.log(` SUBSCRIPTION LEVERAGE ${cmp.leverage.toFixed(1)}x`);
157
+ if (cmp.leverage >= 1) {
158
+ console.log(` => the plan captured $${n(cmp.meterEquivalent - cmp.subscriptionCost, 0)} of on-demand value.`);
159
+ console.log(' This is leverage, NOT a saving to show a client as a discount.');
160
+ } else {
161
+ console.log(' ! The plan costs MORE than metering at this volume. Pay-as-you-go is cheaper.');
162
+ }
163
+ console.log(` utilisation ${n(measured.hoursPerMonth, 1)} steering h/month per seat`);
164
+ console.log(' Quota risk: exceeding a plan quota throttles delivery. That is a SCHEDULE');
165
+ console.log(' risk, not a cost overrun — subscription cost is capped by design.');
166
+ } else {
167
+ console.log('\n--- ACTUAL COST ON A SUBSCRIPTION ---');
168
+ console.log(' Not computed. Pass --plan <key> (see --plans) or --seat-monthly N.');
169
+ console.log(' Without it the figures above remain THEORETICAL meter-equivalents.');
170
+ }
171
+
172
+ console.log('\n--- ACEM PARAMETERS: measured vs default ---');
173
+ row('Context Factor', ACEM_DEFAULTS.contextFactor, measured.contextFactor);
174
+ row('Revision Factor', ACEM_DEFAULTS.revisionFactor, measured.revisionFactorLowerBound, 'lower bound');
175
+ row('Output share', ACEM_DEFAULTS.outputShare, measured.outputShare);
176
+ console.log(` cache-read share of all tokens ${(measured.cacheReadShare * 100).toFixed(1)}%`);
177
+ console.log(` tool error rate ${(measured.toolErrorRate * 100).toFixed(1)}%`);
178
+ console.log(` human correction rate ${(measured.correctionRate * 100).toFixed(1)}%`);
179
+
180
+ console.log(`\n--- TOP ${Math.min(opts.top, projects.length)} PROJECTS BY STEERING TIME ---`);
181
+ console.log(` ${'project'.padEnd(46)}${'sess'.padStart(6)}${'active h'.padStart(10)}${'days'.padStart(8)}${'cost $'.padStart(10)}${'$/h'.padStart(8)}`);
182
+ for (const p of projects.slice(0, opts.top)) {
183
+ console.log(
184
+ ` ${p.project.slice(0, 45).padEnd(46)}${String(p.sessions).padStart(6)}` +
185
+ `${n(p.activeHours, 1).padStart(10)}${n(p.steeringDays, 1).padStart(8)}` +
186
+ `${n(p.cost, 0).padStart(10)}${n(p.costPerHour, 2).padStart(8)}`,
187
+ );
188
+ }
189
+
190
+ if (opts.actualDays != null && Number.isFinite(opts.actualDays)) {
191
+ const steeringDays = measured.steeringDays;
192
+ const overhead = steeringDays > 0 ? opts.actualDays / steeringDays : 0;
193
+ console.log('\n--- SOLVED: AI-STEERED OVERHEAD MULTIPLIER ---');
194
+ console.log(` delivered man-days ${n(opts.actualDays, 1)}`);
195
+ console.log(` measured steering-days ${n(steeringDays, 1)}`);
196
+ console.log(` => OVERHEAD MULTIPLIER ${overhead.toFixed(2)}x`);
197
+ console.log(` (skill defaults: ${STEERING_OVERHEAD.low} light / ${STEERING_OVERHEAD.base} base / ${STEERING_OVERHEAD.high} heavy)`);
198
+ if (overhead < 1.2) {
199
+ console.log(' ! Below 1.2x is implausible — it implies almost no work happened outside the agent.');
200
+ console.log(' Check that the delivered man-days cover the same roles (PM, QA, compliance, client).');
201
+ }
202
+ console.log('\n Put this in the estimate input:');
203
+ console.log(` ai:\n steering_overhead: ${overhead.toFixed(2)}`);
204
+ }
205
+
206
+ console.log('\n--- READY TO PASTE INTO AN ESTIMATE INPUT ---');
207
+ console.log(' ai:');
208
+ console.log(` cost_basis: ${seatMonthly != null ? 'subscription' : 'metered'}`);
209
+ if (seatMonthly != null) {
210
+ console.log(' subscriptions:');
211
+ console.log(` - plan: ${opts.plan ?? 'custom'}`);
212
+ console.log(` seats: ${opts.seats}`);
213
+ if (opts.seatMonthly != null) console.log(` monthly: ${opts.seatMonthly}`);
214
+ }
215
+ console.log(` context_factor: ${measured.contextFactor.toFixed(2)} # measured`);
216
+ console.log(` revision_factor: ${Math.max(measured.revisionFactorLowerBound, 1).toFixed(2)} # measured lower bound`);
217
+ console.log(` cost_per_steering_hour: ${measured.costPerSteeringHour.toFixed(2)} # meter-equivalent, for the leverage line`);
218
+ if (opts.actualDays == null) {
219
+ console.log(' # run again with --actual-days N to solve steering_overhead');
220
+ }
221
+
222
+ console.log('\n Caveats:');
223
+ console.log(' - Revision Factor here is a LOWER BOUND: it counts tool errors and explicit human');
224
+ console.log(' corrections, not tokens the agent silently redid on its own.');
225
+ console.log(' - Cost per steering hour already contains all revision and context effects, so');
226
+ console.log(' prefer it over reconstructing cost from RF x CF.');
227
+ console.log(' - Active time counts hours where a human was engaged; it is not billable-hours truth.');
228
+ console.log(' - The meter figure is THEORETICAL when capacity is bought on a subscription.');
229
+ console.log(' Quote the subscription cost; use the meter only for the leverage argument.');
230
+ console.log('');
231
+
232
+ if (opts.json) {
233
+ writeFileSync(opts.json, JSON.stringify({ measured, projects, sessions: records.length }, null, 2));
234
+ console.log(` JSON written to ${opts.json}\n`);
235
+ }
236
+ }
237
+
238
+ function row(label: string, defaultValue: number, measuredValue: number, note = ''): void {
239
+ const ratio = defaultValue > 0 ? measuredValue / defaultValue : 0;
240
+ const verdict =
241
+ ratio > 1.5 ? `default UNDERSTATES by ${ratio.toFixed(1)}x` : ratio < 0.67 ? `default OVERSTATES by ${(1 / ratio).toFixed(1)}x` : 'default is close';
242
+ console.log(
243
+ ` ${label.padEnd(20)} default ${defaultValue.toString().padStart(6)} measured ${measuredValue.toFixed(3).padStart(8)} ${verdict}${note ? ` (${note})` : ''}`,
244
+ );
245
+ }
246
+
247
+ main();
@@ -0,0 +1,77 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Calibrate `hours_per_ucp` against a completed project.
4
+ *
5
+ * node scripts/calibrate.ts <input.yaml> --actual-hours 3832
6
+ * node scripts/calibrate.ts <input.yaml> --actual-days 479
7
+ *
8
+ * Reference-class forecasting is the single largest accuracy win available in
9
+ * software estimation. This solves for the hours-per-UCP that reproduces a known
10
+ * outcome, so the next estimate is anchored on your own delivery history rather
11
+ * than on Karner's 1993 constant.
12
+ *
13
+ * Effort is linear in hours_per_ucp for a fixed scope, so the solve is a ratio —
14
+ * but the scale adjustment depends on it only through the reference size, which
15
+ * is held fixed, so no iteration is needed.
16
+ */
17
+
18
+ import { readFileSync } from 'node:fs';
19
+ import { dirname, isAbsolute, resolve } from 'node:path';
20
+
21
+ import { DEFAULT_HOURS_PER_DAY, DEFAULT_HOURS_PER_UCP } from "../engine/defaults.js";
22
+ import { estimate } from "../engine/estimate.js";
23
+ import { parseDataFile } from "../engine/yaml.js";
24
+ import type { EstimateInput, RateEntry } from "../engine/types.js";
25
+
26
+ function main(): void {
27
+ const argv = process.argv.slice(2);
28
+ if (argv.length === 0) {
29
+ console.log('Usage: calibrate.ts <input.yaml> (--actual-hours N | --actual-days N) [--exclude-contingency]');
30
+ process.exit(1);
31
+ }
32
+
33
+ const inputPath = resolve(argv[0]);
34
+ let actualHours: number | null = null;
35
+ let excludeContingency = false;
36
+
37
+ for (let i = 1; i < argv.length; i++) {
38
+ if (argv[i] === '--actual-hours') actualHours = Number(argv[++i]);
39
+ else if (argv[i] === '--actual-days') actualHours = Number(argv[++i]) * DEFAULT_HOURS_PER_DAY;
40
+ else if (argv[i] === '--exclude-contingency') excludeContingency = true;
41
+ }
42
+ if (!actualHours || !Number.isFinite(actualHours)) throw new Error('Provide --actual-hours or --actual-days');
43
+
44
+ const input = parseDataFile(inputPath, readFileSync(inputPath, 'utf8')) as unknown as EstimateInput;
45
+ const ratesFile = (input as unknown as { rates_file?: string }).rates_file;
46
+ if (ratesFile) {
47
+ const full = isAbsolute(ratesFile) ? ratesFile : resolve(dirname(inputPath), ratesFile);
48
+ const parsed = parseDataFile(full, readFileSync(full, 'utf8')) as unknown;
49
+ const list = Array.isArray(parsed) ? parsed : (parsed as { rates?: unknown }).rates;
50
+ if (Array.isArray(list)) input.rates = list as RateEntry[];
51
+ }
52
+
53
+ const assumed = input.calibration?.hours_per_ucp ?? DEFAULT_HOURS_PER_UCP;
54
+ const result = estimate(input);
55
+ const modelled = excludeContingency ? result.baseHours : result.totalHours;
56
+ const implied = (assumed * actualHours) / modelled;
57
+ const error = (modelled - actualHours) / actualHours;
58
+
59
+ const fmt = (n: number, d = 1) => n.toLocaleString('en-US', { maximumFractionDigits: d });
60
+
61
+ console.log(`\nCalibration — ${input.project.name}`);
62
+ console.log(` UCP ${fmt(result.sizing.ucp)}`);
63
+ console.log(` Assumed hours/UCP ${fmt(assumed, 2)}`);
64
+ console.log(` Modelled effort ${fmt(modelled, 0)} h (${fmt(modelled / DEFAULT_HOURS_PER_DAY)} md)${excludeContingency ? ' [excl. contingency]' : ''}`);
65
+ console.log(` Actual effort ${fmt(actualHours, 0)} h (${fmt(actualHours / DEFAULT_HOURS_PER_DAY)} md)`);
66
+ console.log(` Model error ${(error * 100).toFixed(1)}%`);
67
+ console.log(`\n => IMPLIED hours/UCP ${fmt(implied, 2)}`);
68
+ console.log(` Write this into calibration.hours_per_ucp for the next estimate of this class of work.\n`);
69
+
70
+ if (implied < 10 || implied > 45) {
71
+ console.log(' ! Implied value is outside the 10-45 h/UCP band seen in practice.');
72
+ console.log(' Check that the scope in this file really matches what the actual hours cover');
73
+ console.log(' (roles included, contingency, support, PM) before adopting it.\n');
74
+ }
75
+ }
76
+
77
+ main();
@@ -0,0 +1,129 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * CLI entry point for the software cost estimator.
4
+ *
5
+ * node scripts/estimate.ts <input.yaml> [--out DIR] [--rates FILE] [--json] [--quiet]
6
+ * bun scripts/estimate.ts <input.yaml> --out ./out
7
+ *
8
+ * Writes estimate-report.md, delivery-mode-comparison.md, business-case.md and
9
+ * estimate.xlsx into the output directory, and prints a short console summary.
10
+ */
11
+
12
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
13
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
14
+
15
+ import { estimate } from "../engine/estimate.js";
16
+ import { parseDataFile } from "../engine/yaml.js";
17
+ import { renderBusinessCase, renderEstimateReport, renderModeComparison } from "../engine/report.js";
18
+ import { buildSheets } from "../engine/workbook.js";
19
+ import { buildXlsx } from "../engine/xlsx.js";
20
+ import type { EstimateInput, RateEntry } from "../engine/types.js";
21
+
22
+ interface Options {
23
+ input: string;
24
+ out: string;
25
+ rates?: string;
26
+ json: boolean;
27
+ quiet: boolean;
28
+ }
29
+
30
+ function parseArgs(argv: string[]): Options {
31
+ const positional: string[] = [];
32
+ const opts: Partial<Options> = { json: false, quiet: false };
33
+ for (let i = 0; i < argv.length; i++) {
34
+ const arg = argv[i];
35
+ if (arg === '--out') opts.out = argv[++i];
36
+ else if (arg === '--rates') opts.rates = argv[++i];
37
+ else if (arg === '--json') opts.json = true;
38
+ else if (arg === '--quiet') opts.quiet = true;
39
+ else if (arg === '-h' || arg === '--help') { usage(); process.exit(0); }
40
+ else positional.push(arg);
41
+ }
42
+ if (positional.length === 0) { usage(); process.exit(1); }
43
+ const input = resolve(positional[0]);
44
+ return {
45
+ input,
46
+ out: resolve(opts.out ?? dirname(input)),
47
+ rates: opts.rates,
48
+ json: opts.json ?? false,
49
+ quiet: opts.quiet ?? false,
50
+ };
51
+ }
52
+
53
+ function usage(): void {
54
+ console.log(
55
+ [
56
+ 'Usage: estimate.ts <input.yaml|input.json> [options]',
57
+ '',
58
+ ' --out DIR output directory (default: next to the input file)',
59
+ ' --rates FILE rate card file; merged into input.rates',
60
+ ' --json also write estimate.json with the full result object',
61
+ ' --quiet suppress the console summary',
62
+ ].join('\n'),
63
+ );
64
+ }
65
+
66
+ /** Load a rate card file that is either a bare list or `{ rates: [...] }`. */
67
+ function loadRates(path: string, relativeTo: string): RateEntry[] {
68
+ const full = isAbsolute(path) ? path : resolve(relativeTo, path);
69
+ const parsed = parseDataFile(full, readFileSync(full, 'utf8')) as unknown;
70
+ const list = Array.isArray(parsed) ? parsed : (parsed as { rates?: unknown }).rates;
71
+ if (!Array.isArray(list)) throw new Error(`Rate file ${full} must be a list, or an object with a "rates" list`);
72
+ return list as RateEntry[];
73
+ }
74
+
75
+ function main(): void {
76
+ const opts = parseArgs(process.argv.slice(2));
77
+ const raw = readFileSync(opts.input, 'utf8');
78
+ const input = parseDataFile(opts.input, raw) as unknown as EstimateInput;
79
+
80
+ // Rates may come from the CLI, or from a `rates_file:` pointer inside the input.
81
+ const inline = (input as unknown as { rates_file?: string }).rates_file;
82
+ const ratePath = opts.rates ?? inline;
83
+ if (ratePath) input.rates = loadRates(ratePath, dirname(opts.input));
84
+
85
+ const result = estimate(input);
86
+
87
+ mkdirSync(opts.out, { recursive: true });
88
+ const write = (name: string, body: string | Uint8Array) => {
89
+ writeFileSync(join(opts.out, name), body as never);
90
+ return join(opts.out, name);
91
+ };
92
+
93
+ write('estimate-report.md', renderEstimateReport(result));
94
+ write('delivery-mode-comparison.md', renderModeComparison(result));
95
+ write('business-case.md', renderBusinessCase(result));
96
+ write('estimate.xlsx', buildXlsx(buildSheets(result)));
97
+ if (opts.json) write('estimate.json', JSON.stringify(result, null, 2));
98
+
99
+ if (opts.quiet) return;
100
+
101
+ const hoursPerDay = input.team?.hours_per_day ?? 8;
102
+ const fmt = (n: number) => Math.round(n).toLocaleString('en-US');
103
+ console.log(`\n${input.project.name} — ${basename(opts.input)}`);
104
+ console.log(` UCP ${result.sizing.ucp.toFixed(1)} | scale E ${result.scaleExponent.toFixed(3)} (x${result.scaleAdjustment.toFixed(3)})`);
105
+ console.log(` Point estimate ${fmt(result.totalHours)} h = ${fmt(result.totalHours / hoursPerDay)} md`);
106
+ console.log(` P50 ${fmt(result.percentiles.p50)} h | P85 ${fmt(result.percentiles.p85)} h | P95 ${fmt(result.percentiles.p95)} h`);
107
+ console.log(` Cone (${result.cone.phase}): ${fmt(result.cone.low)} – ${fmt(result.cone.high)} h`);
108
+ console.log('\n Delivery modes:');
109
+ for (const mode of result.modes) {
110
+ console.log(
111
+ ` ${mode.mode.padEnd(28)} ${fmt(mode.hours).padStart(8)} h ` +
112
+ `${fmt(mode.totalCost).padStart(10)} ${result.currency} ${mode.calendarMonths.toFixed(1)} mo`,
113
+ );
114
+ }
115
+ if (result.businessCase) {
116
+ const bc = result.businessCase;
117
+ console.log(
118
+ `\n Business case: NPV ${fmt(bc.npv)} ${bc.currency}, ROI ${(bc.roi * 100).toFixed(1)}%, ` +
119
+ `payback ${bc.paybackYears == null ? 'never' : `${bc.paybackYears.toFixed(1)} y`}`,
120
+ );
121
+ }
122
+ if (result.warnings.length) {
123
+ console.log('\n Warnings:');
124
+ for (const w of result.warnings) console.log(` ! ${w}`);
125
+ }
126
+ console.log(`\n Written to ${opts.out}\n`);
127
+ }
128
+
129
+ main();