@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,312 @@
1
+ /**
2
+ * Delivery-mode layer: recompute the same scope under four delivery models.
3
+ *
4
+ * human_only baseline, no AI in the loop
5
+ * human_with_ai developers keep the keyboard, AI assists inline
6
+ * ai_steered_human_supervised agent writes the change, human specifies+reviews
7
+ * agentic_hitl autonomous agents, human-in-the-loop oversight (ACEM)
8
+ *
9
+ * Two rules keep this honest:
10
+ * 1. AI compresses BUILD effort only. PM, client iteration, compliance, manual
11
+ * QA and security sign-off do not shrink because a model writes the code.
12
+ * 2. Every AI mode pays back review and rework. DORA 2025 found AI adoption
13
+ * raised instability even as throughput recovered — savings are never free.
14
+ */
15
+
16
+ import {
17
+ ACEM_DEFAULTS,
18
+ AGENT_LEVERAGE,
19
+ AI_SPEEDUP,
20
+ CODEBASE_MODIFIER,
21
+ DEFAULT_HOURS_PER_DAY,
22
+ DEFAULT_SENIORITY_MIX,
23
+ DEV_ROLES,
24
+ NON_DEV_AGENTIC_RETENTION,
25
+ REVIEW_OVERHEAD,
26
+ REWORK_UPLIFT,
27
+ SENIORITY_MODIFIER,
28
+ DEFAULT_SUBSCRIPTION_PLAN,
29
+ STEERING_OVERHEAD,
30
+ SUBSCRIPTION_PLANS,
31
+ USD_TO_CURRENCY,
32
+ WORKING_DAYS_PER_MONTH,
33
+ } from "./defaults.js";
34
+ import { computeRoles } from "./roles.js";
35
+ import type { DeliveryMode, EstimateInput, ModeResult, WorkItem } from "./types.js";
36
+
37
+ /** Share of total effort that is compressible build work. */
38
+ export function devShare(roleRatios: Record<string, number>): number {
39
+ return DEV_ROLES.reduce((sum, role) => sum + (roleRatios[role] ?? 0), 0);
40
+ }
41
+
42
+ /** Environment modifier: codebase maturity x seniority mix. */
43
+ export function environmentModifier(input: EstimateInput): number {
44
+ const codebase = CODEBASE_MODIFIER[input.context?.codebase ?? 'brownfield'] ?? 1;
45
+ const mix = input.team?.seniority_mix ?? DEFAULT_SENIORITY_MIX;
46
+ const weight = Object.values(mix).reduce((s, v) => s + v, 0) || 1;
47
+ const seniority =
48
+ Object.entries(mix).reduce((sum, [level, share]) => sum + (SENIORITY_MODIFIER[level] ?? 1) * share, 0) / weight;
49
+ return codebase * seniority;
50
+ }
51
+
52
+ /** Effort-weighted mean speedup across the work items, using the likely PERT value. */
53
+ export function weightedSpeedup(items: WorkItem[], modifier: number): number {
54
+ const total = items.reduce((s, it) => s + it.hours, 0);
55
+ if (total <= 0) return 1;
56
+ const weighted = items.reduce((s, it) => s + it.hours * AI_SPEEDUP[it.aiClass][1], 0) / total;
57
+ return weighted * modifier;
58
+ }
59
+
60
+ interface ModeContext {
61
+ input: EstimateInput;
62
+ items: WorkItem[];
63
+ /** Human-only total hours, contingency included. */
64
+ totalHours: number;
65
+ ucp: number;
66
+ roleRatios: Record<string, number>;
67
+ }
68
+
69
+ /** Compute every requested delivery mode. */
70
+ export function computeModes(ctx: ModeContext): ModeResult[] {
71
+ const modes = ctx.input.delivery_modes ?? [
72
+ 'human_only',
73
+ 'human_with_ai',
74
+ 'ai_steered_human_supervised',
75
+ 'agentic_hitl',
76
+ ];
77
+ return modes.map((mode) => computeMode(mode, ctx));
78
+ }
79
+
80
+ function computeMode(mode: DeliveryMode, ctx: ModeContext): ModeResult {
81
+ const { input, items, totalHours, ucp, roleRatios } = ctx;
82
+ const share = devShare(roleRatios);
83
+ const modifier = environmentModifier(input);
84
+ const speedup = weightedSpeedup(items, modifier);
85
+ const buildHours = totalHours * share;
86
+ const otherHours = totalHours * (1 - share);
87
+ const notes: string[] = [];
88
+
89
+ let engineeringHours: number;
90
+ let reviewHours = 0;
91
+ let reworkHours = 0;
92
+ let aiCost = 0;
93
+ /** Share of build work executed by agents; drives ACEM token volume. */
94
+ let agentShare = 0;
95
+ /**
96
+ * Hours the agent is actually running. Identical for both agent modes: the
97
+ * agent does the same build work, and what differs between the modes is how
98
+ * much of it a human watches.
99
+ */
100
+ const agentRunHours = buildHours * speedup * AGENT_LEVERAGE;
101
+
102
+ switch (mode) {
103
+ case 'human_only': {
104
+ engineeringHours = totalHours;
105
+ notes.push('Baseline. No AI tooling cost, no review or rework uplift.');
106
+ break;
107
+ }
108
+
109
+ case 'human_with_ai': {
110
+ const compressed = buildHours * speedup;
111
+ engineeringHours = compressed + otherHours;
112
+ reviewHours = engineeringHours * REVIEW_OVERHEAD.human_with_ai;
113
+ reworkHours = engineeringHours * REWORK_UPLIFT.human_with_ai;
114
+ engineeringHours += reviewHours + reworkHours;
115
+ notes.push(`Build effort x${speedup.toFixed(2)} (class mix x codebase x seniority).`);
116
+ notes.push('Non-build effort (PM, compliance, manual QA, client) unchanged.');
117
+ break;
118
+ }
119
+
120
+ case 'ai_steered_human_supervised': {
121
+ const steeringHours = agentRunHours;
122
+ const overhead = input.ai?.steering_overhead ?? STEERING_OVERHEAD.base;
123
+ engineeringHours = steeringHours * overhead;
124
+ reviewHours = engineeringHours * REVIEW_OVERHEAD.ai_steered_human_supervised;
125
+ reworkHours = engineeringHours * REWORK_UPLIFT.ai_steered_human_supervised;
126
+ // The steering-overhead multiplier is measured end-to-end and already carries
127
+ // review and non-build work, so it is reported but not added again.
128
+ notes.push(
129
+ `Steering hours = build x${(speedup * AGENT_LEVERAGE).toFixed(2)}; total = steering x${overhead} ` +
130
+ `(locally measured overhead multiplier).`,
131
+ );
132
+ notes.push('Review and non-build effort are embedded in the overhead multiplier, not added twice.');
133
+ agentShare = 0.5;
134
+ break;
135
+ }
136
+
137
+ case 'agentic_hitl': {
138
+ const hitlHours = buildHours * ACEM_DEFAULTS.hitlShareOfBuild[hitlLevel(input)];
139
+ const retained = otherHours * NON_DEV_AGENTIC_RETENTION;
140
+ engineeringHours = hitlHours + retained;
141
+ reviewHours = hitlHours;
142
+ reworkHours = engineeringHours * REWORK_UPLIFT.agentic_hitl;
143
+ engineeringHours += reworkHours;
144
+ agentShare = 1;
145
+ notes.push(`HITL oversight = ${(ACEM_DEFAULTS.hitlShareOfBuild[hitlLevel(input)] * 100).toFixed(0)}% of human build hours (HIS level ${hitlLevel(input)}).`);
146
+ notes.push('Human effort is HITL oversight plus retained PM/compliance/client work.');
147
+ notes.push('ACEM constants are SYMBOLIC in the source paper — calibrate before quoting.');
148
+ break;
149
+ }
150
+ }
151
+
152
+ const hoursPerDay = input.team?.hours_per_day ?? DEFAULT_HOURS_PER_DAY;
153
+ const { lines } = computeRoles(input, engineeringHours);
154
+ const labourCost = lines.reduce((s, l) => s + l.cost, 0);
155
+ const fte = input.team?.fte ?? 3;
156
+ const calendarMonths = engineeringHours / (fte * hoursPerDay * WORKING_DAYS_PER_MONTH);
157
+
158
+ // Agent cost. Three paths, in order of how much they are grounded in reality.
159
+ const basis = input.ai?.cost_basis ?? 'subscription';
160
+ let seatCostCharged = false;
161
+ if (agentShare > 0) {
162
+ const measuredRate = input.ai?.cost_per_steering_hour;
163
+
164
+ if (basis === 'subscription') {
165
+ // REALITY for most teams: flat seat plans. Cost is seats x months, NOT volume.
166
+ const seats = subscriptionCost(input, calendarMonths);
167
+ aiCost += seats.cost;
168
+ seatCostCharged = true;
169
+ notes.push(
170
+ `Agent cost on SUBSCRIPTION basis: ${seats.description} over ${calendarMonths.toFixed(1)} mo = ` +
171
+ `${Math.round(seats.cost)}. Scales with seats x duration, not work volume.`,
172
+ );
173
+ if (measuredRate != null && agentRunHours > 0) {
174
+ // The meter is what the same work would have cost on demand. The gap is the
175
+ // value the subscription captures, and it belongs in the business case.
176
+ const meterEquivalent = agentRunHours * measuredRate * currencyFactor(input);
177
+ const leverage = seats.cost > 0 ? meterEquivalent / seats.cost : 0;
178
+ notes.push(
179
+ `Metered equivalent would be ${Math.round(meterEquivalent)} ` +
180
+ `(${leverage.toFixed(1)}x the subscription cost) — subscription leverage, not a saving already banked.`,
181
+ );
182
+ if (leverage < 1) {
183
+ notes.push('! Subscription costs MORE than metering at this volume. Consider pay-as-you-go.');
184
+ }
185
+ }
186
+ } else if (measuredRate != null) {
187
+ // Metered, with a measured rate: already contains every revision, retry and
188
+ // context-growth effect, so no reconstruction is needed.
189
+ const rate = measuredRate * currencyFactor(input);
190
+ aiCost += agentRunHours * rate;
191
+ notes.push(
192
+ `Agent cost from MEASURED metered rate: ${Math.round(agentRunHours)} agent-hours x ` +
193
+ `${rate.toFixed(2)}/h = ${Math.round(agentRunHours * rate)}.`,
194
+ );
195
+ } else {
196
+ const acem = acemCost(input, ucp, calendarMonths, agentShare);
197
+ aiCost += acem.total;
198
+ notes.push(
199
+ `Agent cost reconstructed via ACEM: ${(acem.tokens / 1e6).toFixed(1)}M tokens ` +
200
+ `(RF ${acem.rf} x CF ${acem.cf}). Prefer a measured rate — run scripts/calibrate-sessions.ts.`,
201
+ );
202
+ }
203
+ const infra = (input.ai?.infra_monthly ?? ACEM_DEFAULTS.infraMonthly) * calendarMonths;
204
+ aiCost += infra;
205
+ }
206
+
207
+ // Per-seat licence cost applies wherever humans use AI tooling.
208
+ //
209
+ // NOT when the subscription already paid for those seats. A Claude Max seat IS
210
+ // the licence; charging both bills the same thing twice. This is the same
211
+ // single-path discipline the NFR router enforces.
212
+ if (mode !== 'human_only' && !seatCostCharged) {
213
+ const licence = input.ai?.licence_per_dev_month ?? ACEM_DEFAULTS.licencePerDevMonth;
214
+ aiCost += licence * fte * calendarMonths;
215
+ } else if (seatCostCharged) {
216
+ notes.push('Per-seat licence not charged separately: the subscription already covers those seats.');
217
+ }
218
+
219
+ return {
220
+ mode,
221
+ hours: engineeringHours,
222
+ reviewHours,
223
+ reworkHours,
224
+ labourCost,
225
+ aiCost,
226
+ totalCost: labourCost + aiCost,
227
+ calendarMonths,
228
+ roles: lines,
229
+ notes,
230
+ };
231
+ }
232
+
233
+ /** Resolved ACEM HITL Intensity Score level. */
234
+ function hitlLevel(input: EstimateInput): 1 | 2 | 3 | 4 {
235
+ return (input.ai?.hitl_intensity ?? ACEM_DEFAULTS.hitlIntensity) as 1 | 2 | 3 | 4;
236
+ }
237
+
238
+ interface AcemCost {
239
+ tokens: number;
240
+ llmCost: number;
241
+ infraCost: number;
242
+ total: number;
243
+ rf: number;
244
+ cf: number;
245
+ his: 1 | 2 | 3 | 4;
246
+ }
247
+
248
+ /**
249
+ * ACEM monetary dimensions: LLM tokens + infrastructure.
250
+ * `agentShare` scales token volume: 1 = agents do all build work, 0.5 = half.
251
+ * `months` is the calendar duration the agent platform must be paid for.
252
+ * HITL effort is handled as human hours by the caller, not priced here.
253
+ */
254
+ export function acemCost(input: EstimateInput, ucp: number, months: number, agentShare: number): AcemCost {
255
+ const ai = input.ai ?? {};
256
+ const rf = ai.revision_factor ?? ACEM_DEFAULTS.revisionFactor;
257
+ const cf = ai.context_factor ?? ACEM_DEFAULTS.contextFactor;
258
+ const his = hitlLevel(input);
259
+ const perUcp = ai.tokens_per_ucp ?? ACEM_DEFAULTS.tokensPerUcp;
260
+
261
+ const tokens = ucp * perUcp * rf * cf * agentShare;
262
+ const outTokens = tokens * ACEM_DEFAULTS.outputShare;
263
+ const inTokens = tokens - outTokens;
264
+ const llmCost =
265
+ (inTokens / 1e6) * (ai.price_per_mtok_in ?? ACEM_DEFAULTS.pricePerMtokIn) +
266
+ (outTokens / 1e6) * (ai.price_per_mtok_out ?? ACEM_DEFAULTS.pricePerMtokOut);
267
+
268
+ // Infrastructure is added by the caller so both cost paths charge it once.
269
+ return { tokens, llmCost, infraCost: 0, total: llmCost, rf, cf, his };
270
+ }
271
+
272
+ /** Convert a USD figure into the project currency. */
273
+ function currencyFactor(input: EstimateInput): number {
274
+ const currency = input.project.currency ?? 'EUR';
275
+ return USD_TO_CURRENCY[currency] ?? 1;
276
+ }
277
+
278
+ /**
279
+ * Cost of the seat plans held for this project, over the project duration.
280
+ *
281
+ * Seats are charged per calendar month regardless of how hard they are used, so
282
+ * a schedule extension is a real cost increase under this basis. `utilisation`
283
+ * apportions a seat shared across several projects.
284
+ */
285
+ function subscriptionCost(
286
+ input: EstimateInput,
287
+ months: number,
288
+ ): { cost: number; description: string; monthlyTotal: number } {
289
+ const factor = currencyFactor(input);
290
+ const declared = input.ai?.subscriptions;
291
+ const plans =
292
+ declared && declared.length > 0 ? declared : [{ plan: DEFAULT_SUBSCRIPTION_PLAN, seats: 1, utilisation: 1 }];
293
+
294
+ let monthlyTotal = 0;
295
+ const parts: string[] = [];
296
+ for (const entry of plans) {
297
+ const catalogue = entry.plan ? SUBSCRIPTION_PLANS[entry.plan] : undefined;
298
+ const monthly = entry.monthly ?? catalogue?.monthly ?? 0;
299
+ const seats = entry.seats ?? 1;
300
+ const utilisation = entry.utilisation ?? 1;
301
+ const line = monthly * seats * utilisation * factor;
302
+ monthlyTotal += line;
303
+ const label = entry.label ?? catalogue?.label ?? entry.plan ?? 'seat';
304
+ parts.push(`${seats}x ${label}${utilisation < 1 ? ` @${Math.round(utilisation * 100)}%` : ''}`);
305
+ }
306
+
307
+ return {
308
+ cost: monthlyTotal * Math.max(months, 0),
309
+ monthlyTotal,
310
+ description: `${parts.join(' + ')} = ${Math.round(monthlyTotal)}/mo`,
311
+ };
312
+ }
@@ -0,0 +1,239 @@
1
+ /**
2
+ * Markdown renderers for the four deliverables.
3
+ * Every table restates its inputs so a reader can re-derive the numbers by hand.
4
+ */
5
+
6
+ import { AI_SPEEDUP, DEFAULT_HOURS_PER_DAY } from "./defaults.js";
7
+ import type { DeliveryMode, EstimateResult, ModeResult } from "./types.js";
8
+
9
+ const MODE_LABEL: Record<DeliveryMode, string> = {
10
+ human_only: 'Human only',
11
+ human_with_ai: 'Human + AI assist',
12
+ ai_steered_human_supervised: 'AI-steered, human-supervised',
13
+ agentic_hitl: 'Agentic (HITL)',
14
+ };
15
+
16
+ function num(value: number, digits = 0): string {
17
+ return value.toLocaleString('en-US', { minimumFractionDigits: digits, maximumFractionDigits: digits });
18
+ }
19
+
20
+ function money(value: number, currency: string): string {
21
+ return `${num(Math.round(value))} ${currency}`;
22
+ }
23
+
24
+ /** The main estimate report: sizing workings, work items, roles, percentiles. */
25
+ export function renderEstimateReport(r: EstimateResult): string {
26
+ const hoursPerDay = r.input.team?.hours_per_day ?? DEFAULT_HOURS_PER_DAY;
27
+ const baseline = r.modes.find((m) => m.mode === 'human_only') ?? r.modes[0];
28
+ const out: string[] = [];
29
+
30
+ out.push(`# Effort & Cost Estimate — ${r.input.project.name}`, '');
31
+ if (r.input.project.client) out.push(`**Client:** ${r.input.project.client} `);
32
+ out.push(
33
+ `**Currency:** ${r.currency} `,
34
+ `**Phase:** ${r.cone.phase} `,
35
+ `**Codebase:** ${r.input.context?.codebase ?? 'brownfield'} `,
36
+ `**Generated:** ${new Date().toISOString().slice(0, 10)}`,
37
+ '',
38
+ '> This is an **estimate** — a probabilistic assessment. It is not a target and not a commitment.',
39
+ '',
40
+ );
41
+
42
+ out.push('## 1. Headline', '');
43
+ out.push('| Measure | Hours | Days | Cost |', '|---|---:|---:|---:|');
44
+ out.push(
45
+ `| P50 (even odds) | ${num(r.percentiles.p50)} | ${num(r.percentiles.p50 / hoursPerDay, 1)} | ${money(costAt(baseline, r.percentiles.p50, r.totalHours), r.currency)} |`,
46
+ );
47
+ out.push(
48
+ `| P85 (plan to this) | ${num(r.percentiles.p85)} | ${num(r.percentiles.p85 / hoursPerDay, 1)} | ${money(costAt(baseline, r.percentiles.p85, r.totalHours), r.currency)} |`,
49
+ );
50
+ out.push(
51
+ `| P95 (commit to this) | ${num(r.percentiles.p95)} | ${num(r.percentiles.p95 / hoursPerDay, 1)} | ${money(costAt(baseline, r.percentiles.p95, r.totalHours), r.currency)} |`,
52
+ );
53
+ out.push('');
54
+ out.push(
55
+ `**Cone of uncertainty at phase _${r.cone.phase}_:** ${num(r.cone.low)}–${num(r.cone.high)} h. ` +
56
+ 'The cone narrows when decisions are made, not when time passes.',
57
+ '',
58
+ `The point estimate is ${num(r.totalHours)} h. P50 sits above it because the risk distribution is ` +
59
+ 'right-skewed: work overruns more often, and by more, than it underruns.',
60
+ '',
61
+ );
62
+
63
+ out.push('## 2. Sizing workings (Use Case Points)', '');
64
+ out.push('| Element | Value |', '|---|---:|');
65
+ out.push(`| UUCW (unadjusted use case weight) | ${num(r.sizing.uucw, 1)} |`);
66
+ out.push(`| UAW (unadjusted actor weight) | ${num(r.sizing.uaw, 1)} |`);
67
+ out.push(`| TCF (technical complexity factor) | ${r.sizing.tcf.toFixed(3)} |`);
68
+ out.push(`| ECF (environmental complexity factor) | ${r.sizing.ecf.toFixed(3)} |`);
69
+ out.push(`| **UCP = (UUCW + UAW) × TCF × ECF** | **${num(r.sizing.ucp, 1)}** |`);
70
+ out.push(`| COCOMO II scale exponent E | ${r.scaleExponent.toFixed(3)} |`);
71
+ out.push(`| Diseconomy-of-scale adjustment | ×${r.scaleAdjustment.toFixed(3)} |`);
72
+ out.push(`| Residual NFR multiplier | ×${r.nfrMultiplier.toFixed(3)} |`);
73
+ out.push(`| Base effort | ${num(r.baseHours)} h |`);
74
+ out.push(`| Contingency | ${num(r.contingency)} h |`);
75
+ out.push(`| **Total (point estimate)** | **${num(r.totalHours)} h** |`);
76
+ out.push('');
77
+
78
+ out.push('## 3. Work items', '');
79
+ out.push('| ID | Item | Source | AI class | Risk | Hours | Days |', '|---|---|---|---|---|---:|---:|');
80
+ for (const item of r.items) {
81
+ out.push(
82
+ `| ${item.id} | ${item.name} | ${item.source} | ${item.aiClass} | ${item.risk} | ` +
83
+ `${num(item.hours, 1)} | ${num(item.hours / hoursPerDay, 1)} |`,
84
+ );
85
+ }
86
+ out.push('');
87
+
88
+ out.push('## 4. Effort by role', '');
89
+ out.push('| Role | Share | Hours | Days | Day rate | Cost |', '|---|---:|---:|---:|---:|---:|');
90
+ const totalRoleHours = baseline.roles.reduce((s, l) => s + l.hours, 0);
91
+ for (const line of baseline.roles) {
92
+ const share = totalRoleHours > 0 ? (line.hours / totalRoleHours) * 100 : 0;
93
+ out.push(
94
+ `| ${line.role} | ${share.toFixed(1)}% | ${num(line.hours)} | ${num(line.days, 1)} | ` +
95
+ `${money(line.dayRate, r.currency)} | ${money(line.cost, r.currency)} |`,
96
+ );
97
+ }
98
+ out.push(
99
+ `| **Total** | **100%** | **${num(totalRoleHours)}** | **${num(totalRoleHours / hoursPerDay, 1)}** | | ` +
100
+ `**${money(baseline.labourCost, r.currency)}** |`,
101
+ '',
102
+ );
103
+
104
+ if (r.warnings.length) {
105
+ out.push('## 5. Warnings', '');
106
+ for (const w of r.warnings) out.push(`- ⚠️ ${w}`);
107
+ out.push('');
108
+ }
109
+
110
+ out.push('## 6. Assumption register', '');
111
+ for (const a of r.assumptions) out.push(`- ${a}`);
112
+ out.push('');
113
+
114
+ return out.join('\n');
115
+ }
116
+
117
+ function costAt(mode: ModeResult, hours: number, totalHours: number): number {
118
+ return totalHours > 0 ? mode.totalCost * (hours / totalHours) : 0;
119
+ }
120
+
121
+ /** Side-by-side comparison of the delivery modes. */
122
+ export function renderModeComparison(r: EstimateResult): string {
123
+ const hoursPerDay = r.input.team?.hours_per_day ?? DEFAULT_HOURS_PER_DAY;
124
+ const baseline = r.modes.find((m) => m.mode === 'human_only');
125
+ const out: string[] = [];
126
+
127
+ out.push(`# Delivery-Mode Comparison — ${r.input.project.name}`, '');
128
+ out.push(
129
+ 'Same scope, four ways of building it. AI compresses **build** effort only; project management, ' +
130
+ 'client iteration, compliance and manual QA do not shrink because a model writes the code.',
131
+ '',
132
+ );
133
+
134
+ out.push('| Mode | Hours | Days | Labour | AI cost | Total | Calendar | vs human-only |');
135
+ out.push('|---|---:|---:|---:|---:|---:|---:|---:|');
136
+ for (const mode of r.modes) {
137
+ const delta = baseline && baseline.totalCost > 0 ? ((mode.totalCost - baseline.totalCost) / baseline.totalCost) * 100 : 0;
138
+ out.push(
139
+ `| ${MODE_LABEL[mode.mode]} | ${num(mode.hours)} | ${num(mode.hours / hoursPerDay, 1)} | ` +
140
+ `${money(mode.labourCost, r.currency)} | ${money(mode.aiCost, r.currency)} | ` +
141
+ `**${money(mode.totalCost, r.currency)}** | ${mode.calendarMonths.toFixed(1)} mo | ` +
142
+ `${delta >= 0 ? '+' : ''}${delta.toFixed(1)}% |`,
143
+ );
144
+ }
145
+ out.push('');
146
+
147
+ out.push('## Review and rework carried by each mode', '');
148
+ out.push('| Mode | Review hours | Rework hours | Share of mode effort |', '|---|---:|---:|---:|');
149
+ for (const mode of r.modes) {
150
+ const share = mode.hours > 0 ? ((mode.reviewHours + mode.reworkHours) / mode.hours) * 100 : 0;
151
+ out.push(
152
+ `| ${MODE_LABEL[mode.mode]} | ${num(mode.reviewHours)} | ${num(mode.reworkHours)} | ${share.toFixed(1)}% |`,
153
+ );
154
+ }
155
+ out.push(
156
+ '',
157
+ '> DORA 2025 found AI adoption raised instability and rework even as throughput recovered. ' +
158
+ 'A comparison that omits these lines is a sales document, not an estimate.',
159
+ '',
160
+ );
161
+
162
+ out.push('## Per-class AI speedup applied', '');
163
+ out.push('| AI class | Optimistic | Likely | Pessimistic | Hours in scope |', '|---|---:|---:|---:|---:|');
164
+ const byClass = new Map<string, number>();
165
+ for (const item of r.items) byClass.set(item.aiClass, (byClass.get(item.aiClass) ?? 0) + item.hours);
166
+ for (const [cls, hours] of [...byClass.entries()].sort((a, b) => b[1] - a[1])) {
167
+ const [o, m, p] = AI_SPEEDUP[cls as keyof typeof AI_SPEEDUP];
168
+ out.push(`| ${cls} | ×${o.toFixed(2)} | ×${m.toFixed(2)} | ×${p.toFixed(2)} | ${num(hours)} |`);
169
+ }
170
+ out.push(
171
+ '',
172
+ '> ×1.00 = no change. Above 1.00 means AI makes it **slower** — the METR regime for experienced ' +
173
+ 'developers changing mature code they already know well.',
174
+ '',
175
+ );
176
+
177
+ out.push('## Mode notes', '');
178
+ for (const mode of r.modes) {
179
+ out.push(`### ${MODE_LABEL[mode.mode]}`, '');
180
+ for (const note of mode.notes) out.push(`- ${note}`);
181
+ out.push('');
182
+ }
183
+
184
+ return out.join('\n');
185
+ }
186
+
187
+ /** The business case. */
188
+ export function renderBusinessCase(r: EstimateResult): string {
189
+ const bc = r.businessCase;
190
+ if (!bc) return `# Business Case — ${r.input.project.name}\n\nNo \`business:\` block in the input; nothing to compute.\n`;
191
+
192
+ const out: string[] = [];
193
+ out.push(`# Business Case — ${r.input.project.name}`, '');
194
+ out.push('## Headline', '');
195
+ out.push('| Metric | Value |', '|---|---:|');
196
+ out.push(`| Build cost | ${money(bc.buildCost, bc.currency)} |`);
197
+ out.push(`| Annual run cost | ${money(bc.annualRunCost, bc.currency)} |`);
198
+ out.push(`| Annual benefit (confidence-weighted) | ${money(bc.annualBenefit, bc.currency)} |`);
199
+ out.push(`| TCO over ${bc.horizonYears} years | ${money(bc.tco, bc.currency)} |`);
200
+ out.push(`| NPV @ ${(bc.discountRate * 100).toFixed(0)}% | **${money(bc.npv, bc.currency)}** |`);
201
+ out.push(`| ROI | ${(bc.roi * 100).toFixed(1)}% |`);
202
+ out.push(`| Payback | ${bc.paybackYears == null ? 'never within horizon' : `${bc.paybackYears.toFixed(1)} years`} |`);
203
+ out.push('');
204
+
205
+ out.push('## Cash flow', '');
206
+ out.push('| Year | Cost | Benefit | Net | Discounted | Cumulative |', '|---:|---:|---:|---:|---:|---:|');
207
+ for (const y of bc.yearly) {
208
+ out.push(
209
+ `| ${y.year} | ${money(y.cost, bc.currency)} | ${money(y.benefit, bc.currency)} | ${money(y.net, bc.currency)} | ` +
210
+ `${money(y.discounted, bc.currency)} | ${money(y.cumulative, bc.currency)} |`,
211
+ );
212
+ }
213
+ out.push('');
214
+
215
+ out.push('## Sensitivity', '');
216
+ out.push('| Driver | Downside NPV | Base NPV | Upside NPV |', '|---|---:|---:|---:|');
217
+ for (const s of bc.sensitivity) {
218
+ out.push(`| ${s.driver} | ${money(s.low, bc.currency)} | ${money(s.base, bc.currency)} | ${money(s.high, bc.currency)} |`);
219
+ }
220
+ out.push('');
221
+
222
+ if (bc.scopeLadder.length) {
223
+ out.push('## Scope ladder — what you get for what you spend', '');
224
+ out.push('| Tier | Hours | Tier cost | Cumulative |', '|---|---:|---:|---:|');
225
+ for (const tier of bc.scopeLadder) {
226
+ out.push(
227
+ `| ${tier.tier} | ${num(tier.hours)} | ${money(tier.cost, bc.currency)} | ${money(tier.cumulativeCost, bc.currency)} |`,
228
+ );
229
+ }
230
+ out.push('');
231
+ }
232
+
233
+ out.push('## Caveats', '');
234
+ out.push('- Benefits are confidence-weighted; unweighted benefit claims are the usual failure mode of a business case.');
235
+ out.push('- Build cost is the point estimate for the chosen delivery mode. Fund to P85, not P50.');
236
+ out.push('- Agentic run costs are variable and retry-driven; treat the AI cost line as a range, not a price.');
237
+ out.push('');
238
+ return out.join('\n');
239
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Role layer: distribute total effort across delivery roles and price it.
3
+ *
4
+ * Role split is a DISTRIBUTION of the single effort estimate, never a second
5
+ * independent estimate — that is what keeps the totals reconcilable.
6
+ */
7
+
8
+ import {
9
+ DEFAULT_HOURS_PER_DAY,
10
+ DEFAULT_ROLE_RATIOS,
11
+ DEFAULT_SENIORITY_MIX,
12
+ ROLE_RATIO_SIZE_TILT,
13
+ } from "./defaults.js";
14
+ import type { EstimateInput, RateEntry, RoleLine } from "./types.js";
15
+
16
+ /** Normalise a ratio map so the shares sum to exactly 1. */
17
+ export function normalize(ratios: Record<string, number>): Record<string, number> {
18
+ const total = Object.values(ratios).reduce((s, v) => s + v, 0);
19
+ if (total <= 0) throw new Error('Role ratios must sum to a positive number');
20
+ return Object.fromEntries(Object.entries(ratios).map(([k, v]) => [k, v / total]));
21
+ }
22
+
23
+ /**
24
+ * Size-aware role ratios. Larger projects spend proportionally more on
25
+ * coordination and test — a fixed table is a prior, not a truth.
26
+ */
27
+ export function roleRatios(input: EstimateInput, totalHours: number): Record<string, number> {
28
+ const base = { ...(input.team?.role_ratios ?? DEFAULT_ROLE_RATIOS) };
29
+ if (input.team?.role_ratios) return normalize(base);
30
+ if (totalHours < ROLE_RATIO_SIZE_TILT.largeThresholdHours) return normalize(base);
31
+
32
+ const tilt = ROLE_RATIO_SIZE_TILT.tilt as Record<string, number>;
33
+ const moved = Object.values(tilt).reduce((s, v) => s + v, 0);
34
+ for (const [role, delta] of Object.entries(tilt)) base[role] = (base[role] ?? 0) + delta;
35
+ const donors = ROLE_RATIO_SIZE_TILT.takeFrom.filter((r) => base[r] != null);
36
+ for (const donor of donors) base[donor] -= moved / donors.length;
37
+ return normalize(base);
38
+ }
39
+
40
+ /** Blended day rate for a role, weighted by the seniority mix. */
41
+ export function blendedDayRate(role: string, rates: RateEntry[], mix: Record<string, number>): number {
42
+ const forRole = rates.filter((r) => r.role === role);
43
+ if (forRole.length === 0) return 0;
44
+
45
+ const withSeniority = forRole.filter((r) => r.seniority);
46
+ if (withSeniority.length === 0) return forRole[0].day_rate;
47
+
48
+ let total = 0;
49
+ let weight = 0;
50
+ for (const entry of withSeniority) {
51
+ const share = mix[entry.seniority!] ?? 0;
52
+ total += entry.day_rate * share;
53
+ weight += share;
54
+ }
55
+ return weight > 0 ? total / weight : withSeniority[0].day_rate;
56
+ }
57
+
58
+ /** Distribute hours across roles and price each line. */
59
+ export function computeRoles(input: EstimateInput, totalHours: number): { lines: RoleLine[]; missingRates: string[] } {
60
+ const ratios = roleRatios(input, totalHours);
61
+ const hoursPerDay = input.team?.hours_per_day ?? DEFAULT_HOURS_PER_DAY;
62
+ const mix = input.team?.seniority_mix ?? DEFAULT_SENIORITY_MIX;
63
+ const rates = input.rates ?? [];
64
+ const missingRates: string[] = [];
65
+
66
+ const lines = Object.entries(ratios).map(([role, share]) => {
67
+ const hours = totalHours * share;
68
+ const days = hours / hoursPerDay;
69
+ const dayRate = blendedDayRate(role, rates, mix);
70
+ if (dayRate === 0 && rates.length > 0) missingRates.push(role);
71
+ return { role, hours, days, dayRate, cost: days * dayRate };
72
+ });
73
+
74
+ return { lines, missingRates };
75
+ }
76
+
77
+ /** Blended project day rate implied by the role split — the number a client asks for. */
78
+ export function blendedProjectDayRate(lines: RoleLine[]): number {
79
+ const days = lines.reduce((s, l) => s + l.days, 0);
80
+ const cost = lines.reduce((s, l) => s + l.cost, 0);
81
+ return days > 0 ? cost / days : 0;
82
+ }