@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,114 @@
1
+ /**
2
+ * Uncertainty layer: Beta-PERT sampling per work item, Monte Carlo aggregation,
3
+ * and the cone-of-uncertainty band for the current project phase.
4
+ *
5
+ * A single number is not an estimate. This module is what turns the point value
6
+ * into P50/P85/P95, which is the only defensible thing to put in front of a client.
7
+ */
8
+
9
+ import {
10
+ CONE_OF_UNCERTAINTY,
11
+ CORRELATED_SHOCK,
12
+ DEFAULT_ITERATIONS,
13
+ DEFAULT_SEED,
14
+ PERT_LAMBDA,
15
+ PERT_SPREAD,
16
+ } from "./defaults.js";
17
+ import type { Percentiles, Phase, WorkItem } from "./types.js";
18
+
19
+ /** Deterministic RNG (mulberry32) so a run is reproducible from a seed. */
20
+ export function rng(seed: number): () => number {
21
+ let a = seed >>> 0;
22
+ return () => {
23
+ a = (a + 0x6d2b79f5) >>> 0;
24
+ let t = a;
25
+ t = Math.imul(t ^ (t >>> 15), t | 1);
26
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
27
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
28
+ };
29
+ }
30
+
31
+ /** Sample from Gamma(shape, 1) — Marsaglia & Tsang, used to build Beta variates. */
32
+ function sampleGamma(shape: number, random: () => number): number {
33
+ if (shape < 1) {
34
+ const u = random();
35
+ return sampleGamma(shape + 1, random) * Math.pow(u, 1 / shape);
36
+ }
37
+ const d = shape - 1 / 3;
38
+ const c = 1 / Math.sqrt(9 * d);
39
+ for (;;) {
40
+ let x: number;
41
+ let v: number;
42
+ do {
43
+ x = gaussian(random);
44
+ v = 1 + c * x;
45
+ } while (v <= 0);
46
+ v = v * v * v;
47
+ const u = random();
48
+ if (u < 1 - 0.0331 * x * x * x * x) return d * v;
49
+ if (Math.log(u) < 0.5 * x * x + d * (1 - v + Math.log(v))) return d * v;
50
+ }
51
+ }
52
+
53
+ /** Box-Muller standard normal. */
54
+ function gaussian(random: () => number): number {
55
+ let u = 0;
56
+ let v = 0;
57
+ while (u === 0) u = random();
58
+ while (v === 0) v = random();
59
+ return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
60
+ }
61
+
62
+ /** Draw one Beta-PERT sample on [min, max] with mode `mode`. */
63
+ export function samplePert(min: number, mode: number, max: number, random: () => number): number {
64
+ if (max <= min) return mode;
65
+ const alpha = 1 + (PERT_LAMBDA * (mode - min)) / (max - min);
66
+ const beta = 1 + (PERT_LAMBDA * (max - mode)) / (max - min);
67
+ const x = sampleGamma(alpha, random);
68
+ const y = sampleGamma(beta, random);
69
+ return min + ((x / (x + y)) * (max - min));
70
+ }
71
+
72
+ /**
73
+ * Monte Carlo over the work-item tree.
74
+ * Each item's three-point range comes from its risk level, so risk is priced
75
+ * where it lives rather than as a flat project-wide buffer.
76
+ */
77
+ export function simulate(
78
+ items: WorkItem[],
79
+ options: { iterations?: number; seed?: number; scale?: number } = {},
80
+ ): Percentiles {
81
+ const iterations = options.iterations ?? DEFAULT_ITERATIONS;
82
+ const random = rng(options.seed ?? DEFAULT_SEED);
83
+ const scale = options.scale ?? 1;
84
+ const totals = new Float64Array(iterations);
85
+
86
+ for (let i = 0; i < iterations; i++) {
87
+ // One correlated project-level shock per iteration, applied to every item.
88
+ // Independent item sampling alone understates tail risk badly.
89
+ const shock = samplePert(CORRELATED_SHOCK.optimistic, CORRELATED_SHOCK.likely, CORRELATED_SHOCK.pessimistic, random);
90
+ let total = 0;
91
+ for (const item of items) {
92
+ const spread = PERT_SPREAD[item.risk];
93
+ total += samplePert(item.hours * spread.optimistic, item.hours, item.hours * spread.pessimistic, random);
94
+ }
95
+ totals[i] = total * scale * shock;
96
+ }
97
+
98
+ const sorted = Array.from(totals).sort((a, b) => a - b);
99
+ const at = (p: number) => sorted[Math.min(sorted.length - 1, Math.floor(p * sorted.length))];
100
+ return {
101
+ p10: at(0.1),
102
+ p50: at(0.5),
103
+ p85: at(0.85),
104
+ p95: at(0.95),
105
+ mean: sorted.reduce((s, v) => s + v, 0) / sorted.length,
106
+ };
107
+ }
108
+
109
+ /** Cone-of-uncertainty band for the phase the project is actually in. */
110
+ export function coneBand(phase: Phase | undefined, value: number): { phase: Phase; low: number; high: number } {
111
+ const resolved = phase ?? 'approved-product-definition';
112
+ const [low, high] = CONE_OF_UNCERTAINTY[resolved] ?? CONE_OF_UNCERTAINTY['approved-product-definition'];
113
+ return { phase: resolved, low: value * low, high: value * high };
114
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Sizing layer: Use Case Points (Karner) plus the COCOMO II scale exponent.
3
+ *
4
+ * UCP is linear in scope. Real projects are not: COCOMO II's exponent E > 1
5
+ * encodes diseconomy of scale. We therefore size with UCP and then apply the
6
+ * COCOMO exponent relative to a reference size, so a 4x bigger project costs
7
+ * more than 4x. Both steps are reported separately so the arithmetic is auditable.
8
+ */
9
+
10
+ import {
11
+ COCOMO,
12
+ ECF_BASE,
13
+ ECF_COEFF,
14
+ ENVIRONMENTAL_FACTORS,
15
+ SCALE_FACTORS,
16
+ TCF_BASE,
17
+ TCF_COEFF,
18
+ TECHNICAL_FACTORS,
19
+ UAW_WEIGHTS,
20
+ UUCW_BANDS,
21
+ } from "./defaults.js";
22
+ import type { EstimateInput, SizingResult } from "./types.js";
23
+
24
+ /** Map a transaction count to its Karner UUCW weight and band name. */
25
+ export function useCaseWeight(transactions: number): { weight: number; band: string } {
26
+ const band = UUCW_BANDS.find((b) => transactions <= b.max)!;
27
+ return { weight: band.weight, band: band.band };
28
+ }
29
+
30
+ /** Compute the Technical Complexity Factor from T1..T13 ratings (0-5 each). */
31
+ export function technicalComplexityFactor(ratings: Record<string, number> = {}): { tcf: number; tf: number } {
32
+ let tf = 0;
33
+ for (const [key, meta] of Object.entries(TECHNICAL_FACTORS)) {
34
+ const rating = clampRating(ratings[key] ?? 3);
35
+ tf += meta.weight * rating;
36
+ }
37
+ return { tcf: TCF_BASE + TCF_COEFF * tf, tf };
38
+ }
39
+
40
+ /** Compute the Environmental Complexity Factor from E1..E8 ratings (0-5 each). */
41
+ export function environmentalComplexityFactor(ratings: Record<string, number> = {}): { ecf: number; ef: number } {
42
+ let ef = 0;
43
+ for (const [key, meta] of Object.entries(ENVIRONMENTAL_FACTORS)) {
44
+ const rating = clampRating(ratings[key] ?? 3);
45
+ ef += meta.weight * rating;
46
+ }
47
+ return { ecf: ECF_BASE + ECF_COEFF * ef, ef };
48
+ }
49
+
50
+ function clampRating(value: number): number {
51
+ if (Number.isNaN(value)) return 3;
52
+ return Math.min(5, Math.max(0, value));
53
+ }
54
+
55
+ /** Full UCP sizing including NFR-derived scope items. */
56
+ export function computeSizing(input: EstimateInput): SizingResult {
57
+ const perUseCase = input.use_cases.map((uc) => {
58
+ const { weight, band } = useCaseWeight(uc.transactions ?? 4);
59
+ return { id: uc.id, name: uc.name, weight, band };
60
+ });
61
+
62
+ const derivedItems: SizingResult['derivedItems'] = [];
63
+ for (const nfr of input.nfrs ?? []) {
64
+ if (nfr.path !== 'derived-scope') continue;
65
+ for (const [i, comp] of (nfr.derived_components ?? []).entries()) {
66
+ // A derived component sized in hours contributes no UCP weight; it is added
67
+ // directly as a work item later. Only transaction-sized components add UCP.
68
+ if (comp.hours != null) continue;
69
+ const { weight } = useCaseWeight(comp.transactions ?? 3);
70
+ derivedItems.push({ id: `${nfr.id}-D${i + 1}`, name: comp.name, weight, fromNfr: nfr.id });
71
+ }
72
+ }
73
+
74
+ const uucw = [...perUseCase, ...derivedItems].reduce((sum, item) => sum + item.weight, 0);
75
+ const uaw = (input.actors ?? []).reduce((sum, a) => sum + (UAW_WEIGHTS[a.type] ?? 2), 0);
76
+ const { tcf } = technicalComplexityFactor(input.factors?.technical);
77
+ const { ecf } = environmentalComplexityFactor(input.factors?.environmental);
78
+
79
+ return { uucw, uaw, tcf, ecf, ucp: (uucw + uaw) * tcf * ecf, perUseCase, derivedItems };
80
+ }
81
+
82
+ /** COCOMO II exponent E = B + 0.01 * sum(scale factors). */
83
+ export function scaleExponent(ratings: Record<string, string> = {}): number {
84
+ let sum = 0;
85
+ for (const [name, table] of Object.entries(SCALE_FACTORS)) {
86
+ const rating = ratings[name] ?? 'nominal';
87
+ const value = table[rating];
88
+ if (value == null) throw new Error(`Unknown COCOMO scale rating "${rating}" for ${name}`);
89
+ sum += value;
90
+ }
91
+ return COCOMO.B + 0.01 * sum;
92
+ }
93
+
94
+ /**
95
+ * Diseconomy-of-scale adjustment applied to a linear UCP effort.
96
+ * At ucp === referenceUcp the adjustment is exactly 1.0, so calibration of
97
+ * hours-per-UCP stays meaningful.
98
+ */
99
+ export function scaleAdjustment(ucp: number, referenceUcp: number, exponent: number): number {
100
+ if (ucp <= 0 || referenceUcp <= 0) return 1;
101
+ return Math.pow(ucp / referenceUcp, exponent - 1);
102
+ }
103
+
104
+ /** COCOMO II schedule equation, used for a sanity check on calendar time. */
105
+ export function nominalScheduleMonths(personMonths: number, exponent: number): number {
106
+ if (personMonths <= 0) return 0;
107
+ return COCOMO.C * Math.pow(personMonths, COCOMO.D + 0.2 * (exponent - COCOMO.B));
108
+ }
@@ -0,0 +1,288 @@
1
+ /**
2
+ * Input contract and result types for the software cost estimator.
3
+ *
4
+ * Every numeric constant that is not supplied here comes from `defaults.ts`,
5
+ * where each value carries a cited source or an explicit UNCALIBRATED marker.
6
+ */
7
+
8
+ /** How a work item responds to AI assistance. Drives the delivery-mode speedups. */
9
+ export type AiClass =
10
+ | 'boilerplate' // scaffolding, CRUD screens, DTOs, config, migrations
11
+ | 'crud' // standard create/read/update/delete + validation
12
+ | 'integration' // third-party APIs, protocols, undocumented systems
13
+ | 'algorithmic' // non-trivial domain logic, optimisation, concurrency
14
+ | 'legacy-change' // change inside a large mature codebase (METR regime)
15
+ | 'ux-heavy' // design-led interaction work, accessibility
16
+ | 'docs' // documentation, specs, runbooks
17
+ | 'ops'; // infrastructure, CI/CD, observability wiring
18
+
19
+ /** Delivery modes compared side by side. */
20
+ export type DeliveryMode =
21
+ | 'human_only'
22
+ | 'human_with_ai'
23
+ | 'ai_steered_human_supervised'
24
+ | 'agentic_hitl';
25
+
26
+ export type ActorType = 'api' | 'protocol' | 'human';
27
+ export type RiskLevel = 'low' | 'medium' | 'high';
28
+ export type NfrPath = 'derived-scope' | 'multiplier';
29
+
30
+ /** Project phase, used to apply the cone-of-uncertainty band. */
31
+ export type Phase =
32
+ | 'initial-concept'
33
+ | 'approved-product-definition'
34
+ | 'requirements-complete'
35
+ | 'ui-design-complete'
36
+ | 'detailed-design-complete';
37
+
38
+ export interface UseCaseInput {
39
+ id: string;
40
+ name: string;
41
+ /** Number of transactions/steps in the success + alternate scenarios. Drives UUCW weight. */
42
+ transactions: number;
43
+ ai_class?: AiClass;
44
+ risk?: RiskLevel;
45
+ /** Optional direct override in hours; when set, UCP sizing is bypassed for this item. */
46
+ hours_override?: number;
47
+ notes?: string;
48
+ }
49
+
50
+ export interface ActorInput {
51
+ name: string;
52
+ type: ActorType;
53
+ }
54
+
55
+ export interface NfrInput {
56
+ id: string;
57
+ /** ISO/IEC 25010 quality attribute, e.g. availability, security, performance-efficiency. */
58
+ attribute: string;
59
+ target?: string;
60
+ /** Routing decision: expand into extra scope, or apply as a residual multiplier. Never both. */
61
+ path: NfrPath;
62
+ /** For `derived-scope`: extra work items this NFR forces into existence. */
63
+ derived_components?: Array<{
64
+ name: string;
65
+ transactions?: number;
66
+ hours?: number;
67
+ ai_class?: AiClass;
68
+ risk?: RiskLevel;
69
+ }>;
70
+ /** For `multiplier`: effort multiplier applied to the whole estimate (1.0 = neutral). */
71
+ multiplier?: number;
72
+ }
73
+
74
+ export interface FactorsInput {
75
+ /** UCP technical factors T1..T13, each rated 0-5. */
76
+ technical?: Record<string, number>;
77
+ /** UCP environmental factors E1..E8, each rated 0-5. */
78
+ environmental?: Record<string, number>;
79
+ /** COCOMO II scale factors, each a rating name (very-low..extra-high). */
80
+ cocomo_scale?: Record<string, string>;
81
+ }
82
+
83
+ export interface RateEntry {
84
+ role: string;
85
+ seniority?: string;
86
+ /** Cost per day in the project currency. */
87
+ day_rate: number;
88
+ }
89
+
90
+ export interface AiConfig {
91
+ /** Price per 1M input tokens, project currency. */
92
+ price_per_mtok_in?: number;
93
+ /** Price per 1M output tokens, project currency. */
94
+ price_per_mtok_out?: number;
95
+ /** ACEM Revision Factor: token overhead from rejected output and retries (>= 1). */
96
+ revision_factor?: number;
97
+ /** ACEM Context Factor: token growth as context accumulates (>= 1). */
98
+ context_factor?: number;
99
+ /** ACEM HITL Intensity Score, level 1-4. Higher = more human oversight per agent action. */
100
+ hitl_intensity?: 1 | 2 | 3 | 4;
101
+ /** Tokens consumed per UCP of delivered scope (input+output combined). */
102
+ tokens_per_ucp?: number;
103
+ /** Monthly agent infrastructure + tooling + licence cost. */
104
+ infra_monthly?: number;
105
+ /** Per-seat AI tool licence per developer per month. */
106
+ licence_per_dev_month?: number;
107
+ /** Steering-hour overhead multiplier for ai_steered mode (calibrated locally). */
108
+ steering_overhead?: number;
109
+ /**
110
+ * MEASURED billed agent cost per agent-running hour, in USD.
111
+ * When set, this replaces the ACEM token reconstruction entirely, because a
112
+ * measured rate already contains every revision, retry and context effect.
113
+ * Produced by scripts/calibrate-sessions.ts.
114
+ */
115
+ cost_per_steering_hour?: number;
116
+
117
+ /**
118
+ * How agent capacity is actually PAID FOR.
119
+ * 'subscription' — flat per-seat plans (the common reality). Cost scales with
120
+ * seats x calendar months and is capped by quota.
121
+ * 'metered' — pay-as-you-go API billing. Cost scales with work volume.
122
+ * Default: 'subscription'.
123
+ */
124
+ cost_basis?: 'subscription' | 'metered';
125
+
126
+ /** Seat plans held for this project. Used when cost_basis is 'subscription'. */
127
+ subscriptions?: SubscriptionInput[];
128
+ }
129
+
130
+ export interface SubscriptionInput {
131
+ /** Catalogue key, e.g. 'anthropic-max-20x'. See SUBSCRIPTION_PLANS. */
132
+ plan?: string;
133
+ /** Explicit USD per seat per month; overrides the catalogue price. */
134
+ monthly?: number;
135
+ /** Number of seats. Default 1. */
136
+ seats?: number;
137
+ /**
138
+ * Share of each seat chargeable to THIS project (0–1). Default 1.
139
+ * A seat shared across three projects should not bill fully to one of them.
140
+ */
141
+ utilisation?: number;
142
+ /** Free-text label for the report. */
143
+ label?: string;
144
+ }
145
+
146
+ export interface BusinessCaseInput {
147
+ discount_rate?: number;
148
+ horizon_years?: number;
149
+ /** Recurring annual benefit lines. */
150
+ benefits?: Array<{ name: string; annual_value: number; confidence?: number; start_year?: number }>;
151
+ /** Recurring annual run cost lines (hosting, licences, support). */
152
+ run_costs?: Array<{ name: string; annual_value: number }>;
153
+ /** Scope ladder tiers used to answer "what can we cut". */
154
+ scope_tiers?: Array<{ tier: 'must' | 'should' | 'could'; use_cases: string[] }>;
155
+ }
156
+
157
+ export interface EstimateInput {
158
+ project: {
159
+ name: string;
160
+ client?: string;
161
+ currency?: string;
162
+ region?: string;
163
+ phase?: Phase;
164
+ };
165
+ context?: {
166
+ codebase?: 'greenfield' | 'brownfield' | 'legacy';
167
+ domain?: string;
168
+ compliance?: string[];
169
+ };
170
+ stack?: Record<string, unknown>;
171
+ actors?: ActorInput[];
172
+ use_cases: UseCaseInput[];
173
+ nfrs?: NfrInput[];
174
+ factors?: FactorsInput;
175
+ delivery_modes?: DeliveryMode[];
176
+ team?: {
177
+ role_ratios?: Record<string, number>;
178
+ seniority_mix?: Record<string, number>;
179
+ hours_per_day?: number;
180
+ fte?: number;
181
+ };
182
+ rates?: RateEntry[];
183
+ ai?: AiConfig;
184
+ business?: BusinessCaseInput;
185
+ calibration?: {
186
+ /** Hours per UCP. Karner's original is 20; project actuals should override. */
187
+ hours_per_ucp?: number;
188
+ /** Reference project size in UCP for the COCOMO scale adjustment. */
189
+ reference_ucp?: number;
190
+ /** Contingency applied on top of the base estimate. */
191
+ contingency?: number;
192
+ /** Monte Carlo iterations. */
193
+ iterations?: number;
194
+ /** Fixed RNG seed for reproducible runs. */
195
+ seed?: number;
196
+ };
197
+ }
198
+
199
+ // ---------------------------------------------------------------------------
200
+ // Result types
201
+ // ---------------------------------------------------------------------------
202
+
203
+ export interface SizingResult {
204
+ uucw: number;
205
+ uaw: number;
206
+ tcf: number;
207
+ ecf: number;
208
+ ucp: number;
209
+ perUseCase: Array<{ id: string; name: string; weight: number; band: string }>;
210
+ derivedItems: Array<{ id: string; name: string; weight: number; fromNfr: string }>;
211
+ }
212
+
213
+ export interface WorkItem {
214
+ id: string;
215
+ name: string;
216
+ aiClass: AiClass;
217
+ risk: RiskLevel;
218
+ /** Baseline human-only hours, before contingency. */
219
+ hours: number;
220
+ source: 'use-case' | 'nfr-derived';
221
+ }
222
+
223
+ export interface RoleLine {
224
+ role: string;
225
+ hours: number;
226
+ days: number;
227
+ dayRate: number;
228
+ cost: number;
229
+ }
230
+
231
+ export interface ModeResult {
232
+ mode: DeliveryMode;
233
+ /** Engineering hours after mode-specific speedups, review and rework. */
234
+ hours: number;
235
+ /** Hours added back for review of AI output. */
236
+ reviewHours: number;
237
+ /** Hours added back for AI-induced rework (DORA instability finding). */
238
+ reworkHours: number;
239
+ labourCost: number;
240
+ aiCost: number;
241
+ totalCost: number;
242
+ calendarMonths: number;
243
+ roles: RoleLine[];
244
+ notes: string[];
245
+ }
246
+
247
+ export interface Percentiles {
248
+ p10: number;
249
+ p50: number;
250
+ p85: number;
251
+ p95: number;
252
+ mean: number;
253
+ }
254
+
255
+ export interface BusinessCaseResult {
256
+ currency: string;
257
+ buildCost: number;
258
+ annualRunCost: number;
259
+ annualBenefit: number;
260
+ horizonYears: number;
261
+ discountRate: number;
262
+ npv: number;
263
+ roi: number;
264
+ paybackYears: number | null;
265
+ tco: number;
266
+ yearly: Array<{ year: number; cost: number; benefit: number; net: number; discounted: number; cumulative: number }>;
267
+ sensitivity: Array<{ driver: string; low: number; base: number; high: number }>;
268
+ scopeLadder: Array<{ tier: string; hours: number; cost: number; cumulativeCost: number }>;
269
+ }
270
+
271
+ export interface EstimateResult {
272
+ input: EstimateInput;
273
+ currency: string;
274
+ sizing: SizingResult;
275
+ items: WorkItem[];
276
+ nfrMultiplier: number;
277
+ scaleExponent: number;
278
+ scaleAdjustment: number;
279
+ baseHours: number;
280
+ contingency: number;
281
+ totalHours: number;
282
+ cone: { phase: Phase; low: number; high: number };
283
+ percentiles: Percentiles;
284
+ modes: ModeResult[];
285
+ businessCase: BusinessCaseResult | null;
286
+ assumptions: string[];
287
+ warnings: string[];
288
+ }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Assemble the estimate workbook: one sheet per model layer so a client can
3
+ * change an assumption and see where it lands.
4
+ */
5
+
6
+ import { AI_SPEEDUP, DEFAULT_HOURS_PER_DAY, ENVIRONMENTAL_FACTORS, TECHNICAL_FACTORS } from "./defaults.js";
7
+ import type { Sheet } from "./xlsx.js";
8
+ import type { EstimateResult } from "./types.js";
9
+
10
+ export function buildSheets(r: EstimateResult): Sheet[] {
11
+ const hoursPerDay = r.input.team?.hours_per_day ?? DEFAULT_HOURS_PER_DAY;
12
+ const baseline = r.modes.find((m) => m.mode === 'human_only') ?? r.modes[0];
13
+ const sheets: Sheet[] = [];
14
+
15
+ sheets.push({
16
+ name: 'Summary',
17
+ rows: [
18
+ ['Metric', 'Value', 'Unit'],
19
+ ['Project', r.input.project.name, ''],
20
+ ['Currency', r.currency, ''],
21
+ ['Phase', r.cone.phase, ''],
22
+ ['UCP', round(r.sizing.ucp, 2), 'points'],
23
+ ['COCOMO scale exponent E', round(r.scaleExponent, 3), ''],
24
+ ['Scale adjustment', round(r.scaleAdjustment, 3), 'x'],
25
+ ['NFR multiplier', round(r.nfrMultiplier, 3), 'x'],
26
+ ['Base effort', round(r.baseHours), 'h'],
27
+ ['Contingency', round(r.contingency), 'h'],
28
+ ['Total point estimate', round(r.totalHours), 'h'],
29
+ ['P50', round(r.percentiles.p50), 'h'],
30
+ ['P85', round(r.percentiles.p85), 'h'],
31
+ ['P95', round(r.percentiles.p95), 'h'],
32
+ ['Cone low', round(r.cone.low), 'h'],
33
+ ['Cone high', round(r.cone.high), 'h'],
34
+ ['Baseline labour cost', round(baseline.labourCost), r.currency],
35
+ ],
36
+ });
37
+
38
+ sheets.push({
39
+ name: 'Work items',
40
+ rows: [
41
+ ['ID', 'Item', 'Source', 'AI class', 'Risk', 'Hours', 'Days', 'AI speedup (likely)'],
42
+ ...r.items.map((it) => [
43
+ it.id,
44
+ it.name,
45
+ it.source,
46
+ it.aiClass,
47
+ it.risk,
48
+ round(it.hours, 2),
49
+ round(it.hours / hoursPerDay, 2),
50
+ AI_SPEEDUP[it.aiClass][1],
51
+ ]),
52
+ ],
53
+ });
54
+
55
+ sheets.push({
56
+ name: 'Sizing',
57
+ rows: [
58
+ ['Use case', 'Band', 'UUCW weight'],
59
+ ...r.sizing.perUseCase.map((uc) => [`${uc.id} ${uc.name}`, uc.band, uc.weight]),
60
+ [],
61
+ ['NFR-derived scope', 'From NFR', 'UUCW weight'],
62
+ ...r.sizing.derivedItems.map((d) => [d.name, d.fromNfr, d.weight]),
63
+ [],
64
+ ['Technical factor', 'Weight', 'Rating', 'Contribution'],
65
+ ...Object.entries(TECHNICAL_FACTORS).map(([key, meta]) => {
66
+ const rating = r.input.factors?.technical?.[key] ?? 3;
67
+ return [`${key} ${meta.label}`, meta.weight, rating, round(meta.weight * rating, 2)];
68
+ }),
69
+ [],
70
+ ['Environmental factor', 'Weight', 'Rating', 'Contribution'],
71
+ ...Object.entries(ENVIRONMENTAL_FACTORS).map(([key, meta]) => {
72
+ const rating = r.input.factors?.environmental?.[key] ?? 3;
73
+ return [`${key} ${meta.label}`, meta.weight, rating, round(meta.weight * rating, 2)];
74
+ }),
75
+ ],
76
+ });
77
+
78
+ sheets.push({
79
+ name: 'Roles',
80
+ rows: [
81
+ ['Role', 'Hours', 'Days', 'Day rate', 'Cost'],
82
+ ...baseline.roles.map((l) => [l.role, round(l.hours), round(l.days, 2), l.dayRate, round(l.cost)]),
83
+ ],
84
+ });
85
+
86
+ sheets.push({
87
+ name: 'Delivery modes',
88
+ rows: [
89
+ ['Mode', 'Hours', 'Days', 'Review h', 'Rework h', 'Labour', 'AI cost', 'Total', 'Calendar months'],
90
+ ...r.modes.map((m) => [
91
+ m.mode,
92
+ round(m.hours),
93
+ round(m.hours / hoursPerDay, 1),
94
+ round(m.reviewHours),
95
+ round(m.reworkHours),
96
+ round(m.labourCost),
97
+ round(m.aiCost),
98
+ round(m.totalCost),
99
+ round(m.calendarMonths, 1),
100
+ ]),
101
+ ],
102
+ });
103
+
104
+ if (r.businessCase) {
105
+ const bc = r.businessCase;
106
+ sheets.push({
107
+ name: 'Business case',
108
+ rows: [
109
+ ['Metric', 'Value'],
110
+ ['Build cost', round(bc.buildCost)],
111
+ ['Annual run cost', round(bc.annualRunCost)],
112
+ ['Annual benefit', round(bc.annualBenefit)],
113
+ ['Discount rate', bc.discountRate],
114
+ ['Horizon (years)', bc.horizonYears],
115
+ ['NPV', round(bc.npv)],
116
+ ['ROI', round(bc.roi, 4)],
117
+ ['Payback (years)', bc.paybackYears == null ? 'never' : round(bc.paybackYears, 2)],
118
+ ['TCO', round(bc.tco)],
119
+ [],
120
+ ['Year', 'Cost', 'Benefit', 'Net', 'Discounted', 'Cumulative'],
121
+ ...bc.yearly.map((y) => [y.year, round(y.cost), round(y.benefit), round(y.net), round(y.discounted), round(y.cumulative)]),
122
+ [],
123
+ ['Sensitivity driver', 'Downside NPV', 'Base NPV', 'Upside NPV'],
124
+ ...bc.sensitivity.map((s) => [s.driver, round(s.low), round(s.base), round(s.high)]),
125
+ [],
126
+ ['Scope tier', 'Hours', 'Tier cost', 'Cumulative cost'],
127
+ ...bc.scopeLadder.map((t) => [t.tier, round(t.hours), round(t.cost), round(t.cumulativeCost)]),
128
+ ],
129
+ });
130
+ }
131
+
132
+ sheets.push({
133
+ name: 'Assumptions',
134
+ rows: [['#', 'Assumption'], ...r.assumptions.map((a, i) => [i + 1, a]), [], ['#', 'Warning'], ...r.warnings.map((w, i) => [i + 1, w])],
135
+ });
136
+
137
+ return sheets;
138
+ }
139
+
140
+ function round(value: number, digits = 0): number {
141
+ const factor = Math.pow(10, digits);
142
+ return Math.round(value * factor) / factor;
143
+ }