@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,380 @@
1
+ /**
2
+ * Read pi session logs and derive measured delivery constants.
3
+ *
4
+ * THE ONLY MODULE IN THIS PACKAGE THAT TOUCHES THE SESSION STORE.
5
+ * The engine under ../engine stays zero-dependency and portable; this adapter
6
+ * is where the workspace dependencies live. Keep that seam intact — it is what
7
+ * lets the estimator run in a project with no dashboard installed.
8
+ *
9
+ * Session store layout:
10
+ * ~/.pi/agent/sessions/<slugified-cwd>/<timestamp>_<uuid>.jsonl
11
+ * ~/.pi/agent/sessions/<slugified-cwd>/<timestamp>_<uuid>.meta.json
12
+ *
13
+ * The `.jsonl` carries per-record timestamps (active-time measurement); the
14
+ * `.meta.json` carries token counts and the real billed cost. Both are read
15
+ * through the shared readers rather than re-parsed here, so a session-schema
16
+ * change lands in one place instead of silently rotting the calibration.
17
+ *
18
+ * ACTIVE TIME METHOD: sum the gaps between consecutive records, capping any gap
19
+ * longer than `gapCapMinutes` at the cap. A long gap is a break, not work.
20
+ * This is the same method that produced the locally measured steering figures.
21
+ */
22
+
23
+ import { readdirSync, statSync } from "node:fs";
24
+ import { homedir } from "node:os";
25
+ import { join } from "node:path";
26
+
27
+ import { readSessionMeta } from "@blackbelt-technology/pi-dashboard-shared/session-meta.js";
28
+ import type { SessionMeta } from "@blackbelt-technology/pi-dashboard-shared/session-meta.js";
29
+ import { readSession } from "@blackbelt-technology/pi-dashboard-session-distiller/jsonl-reader.js";
30
+
31
+ export interface SessionRecord {
32
+ file: string;
33
+ project: string;
34
+ name: string | null;
35
+ startedAt: number | null;
36
+ activeHours: number;
37
+ wallHours: number;
38
+ humanTurns: number;
39
+ assistantTurns: number;
40
+ toolCalls: number;
41
+ toolResults: number;
42
+ toolErrors: number;
43
+ corrections: number;
44
+ tokensIn: number;
45
+ tokensOut: number;
46
+ cacheRead: number;
47
+ cacheWrite: number;
48
+ cost: number;
49
+ model: string | null;
50
+ }
51
+
52
+ export interface ScanOptions {
53
+ root?: string;
54
+ gapCapMinutes?: number;
55
+ /** Case-insensitive substring filter on the project path. */
56
+ project?: string;
57
+ /** Only sessions started on or after this ISO date. */
58
+ since?: string;
59
+ /** Ignore trivial sessions below this active-hour threshold. */
60
+ minActiveHours?: number;
61
+ /** Ignore sessions with fewer assistant turns than this. */
62
+ minAssistantTurns?: number;
63
+ }
64
+
65
+ const CORRECTION =
66
+ /(^|\s)(no,|nope|wrong|instead|revert|undo|don't|do not|stop|that's not|thats not|not what|fix that|redo|again,|rather)/i;
67
+ const TOOL_ERROR = /^(error|Error:|Traceback|command failed|exit code [1-9]|FAIL|not found|Cannot |ENOENT)/i;
68
+
69
+ export function defaultSessionRoot(): string {
70
+ return join(homedir(), ".pi", "agent", "sessions");
71
+ }
72
+
73
+ /** Collapse a worktree path back to its parent repository. */
74
+ export function normalizeProject(cwd: string | undefined): string {
75
+ if (!cwd) return '(unknown)';
76
+ const home = homedir();
77
+ let path = cwd.startsWith(home) ? cwd.slice(home.length + 1) : cwd;
78
+ const worktree = path.indexOf('/.worktrees/');
79
+ if (worktree >= 0) path = path.slice(0, worktree);
80
+ return path;
81
+ }
82
+
83
+ /** Scan the session store and return one record per usable session. */
84
+ export function scanSessions(options: ScanOptions = {}): SessionRecord[] {
85
+ const root = options.root ?? defaultSessionRoot();
86
+ const gapCap = (options.gapCapMinutes ?? 15) * 60_000;
87
+ const minActive = options.minActiveHours ?? 0.25;
88
+ const minTurns = options.minAssistantTurns ?? 3;
89
+ const since = options.since ? Date.parse(options.since) : null;
90
+ const filter = options.project?.toLowerCase();
91
+
92
+ const out: SessionRecord[] = [];
93
+ for (const dir of safeReaddir(root)) {
94
+ const dirPath = join(root, dir);
95
+ if (!isDirectory(dirPath)) continue;
96
+ for (const file of safeReaddir(dirPath)) {
97
+ if (!file.endsWith(".jsonl")) continue;
98
+ const record = readSessionRecord(join(dirPath, file), gapCap);
99
+ if (!record) continue;
100
+ if (record.activeHours < minActive) continue;
101
+ if (record.assistantTurns < minTurns) continue;
102
+ if (since && (record.startedAt ?? 0) < since) continue;
103
+ if (filter && !record.project.toLowerCase().includes(filter)) continue;
104
+ out.push(record);
105
+ }
106
+ }
107
+ return out.sort((a, b) => (a.startedAt ?? 0) - (b.startedAt ?? 0));
108
+ }
109
+
110
+ function safeReaddir(path: string): string[] {
111
+ try {
112
+ return readdirSync(path);
113
+ } catch {
114
+ return [];
115
+ }
116
+ }
117
+
118
+ function isDirectory(path: string): boolean {
119
+ try {
120
+ return statSync(path).isDirectory();
121
+ } catch {
122
+ return false;
123
+ }
124
+ }
125
+
126
+ function readSessionRecord(jsonlPath: string, gapCap: number): SessionRecord | null {
127
+ // `readSessionMeta` resolves the sibling .meta.json itself.
128
+ const meta: SessionMeta | undefined = readSessionMeta(jsonlPath);
129
+ if (!meta) return null;
130
+
131
+ const { events } = readSession(jsonlPath);
132
+ if (!events || events.length === 0) return null;
133
+
134
+ const stamps: number[] = [];
135
+ let humanTurns = 0;
136
+ let assistantTurns = 0;
137
+ let toolCalls = 0;
138
+ let toolResults = 0;
139
+ let toolErrors = 0;
140
+ let corrections = 0;
141
+
142
+ for (const entry of events as Array<Record<string, unknown>>) {
143
+ if (entry.type !== "message") continue;
144
+
145
+ const stamp = typeof entry.timestamp === "string" ? Date.parse(entry.timestamp) : NaN;
146
+ if (Number.isFinite(stamp)) stamps.push(stamp);
147
+
148
+ const message = entry.message as { role?: string; content?: unknown } | undefined;
149
+ if (!message) continue;
150
+
151
+ let text = "";
152
+ if (Array.isArray(message.content)) {
153
+ for (const block of message.content as Array<Record<string, unknown>>) {
154
+ if (block?.type === "text") text += (block.text as string) ?? "";
155
+ else if (block?.type === "toolCall") toolCalls++;
156
+ }
157
+ } else if (typeof message.content === "string") {
158
+ text = message.content;
159
+ }
160
+
161
+ if (message.role === "assistant") assistantTurns++;
162
+ else if (message.role === "user") {
163
+ humanTurns++;
164
+ if (CORRECTION.test(text.slice(0, 300))) corrections++;
165
+ } else if (message.role === "toolResult") {
166
+ toolResults++;
167
+ if (TOOL_ERROR.test(text.trim().slice(0, 120))) toolErrors++;
168
+ }
169
+ }
170
+
171
+ if (stamps.length < 2) return null;
172
+ stamps.sort((a, b) => a - b);
173
+
174
+ let active = 0;
175
+ for (let i = 1; i < stamps.length; i++) active += Math.min(stamps[i] - stamps[i - 1], gapCap);
176
+
177
+ return {
178
+ file: jsonlPath,
179
+ project: normalizeProject(meta.cwd),
180
+ name: meta.name ?? null,
181
+ startedAt: meta.startedAt ?? stamps[0],
182
+ activeHours: active / 3_600_000,
183
+ wallHours: (stamps[stamps.length - 1] - stamps[0]) / 3_600_000,
184
+ humanTurns,
185
+ assistantTurns,
186
+ toolCalls,
187
+ toolResults,
188
+ toolErrors,
189
+ corrections,
190
+ tokensIn: meta.tokensIn ?? 0,
191
+ tokensOut: meta.tokensOut ?? 0,
192
+ cacheRead: meta.cacheRead ?? 0,
193
+ cacheWrite: meta.cacheWrite ?? 0,
194
+ cost: meta.cost ?? 0,
195
+ model: meta.model ?? null,
196
+ };
197
+ }
198
+
199
+ export interface ProjectAggregate {
200
+ project: string;
201
+ sessions: number;
202
+ activeHours: number;
203
+ steeringDays: number;
204
+ cost: number;
205
+ costPerHour: number;
206
+ tokensOut: number;
207
+ cacheRead: number;
208
+ humanTurns: number;
209
+ assistantTurns: number;
210
+ toolCalls: number;
211
+ }
212
+
213
+ /** Aggregate sessions per project. */
214
+ export function aggregateByProject(records: SessionRecord[], hoursPerDay = 8): ProjectAggregate[] {
215
+ const map = new Map<string, ProjectAggregate>();
216
+ for (const record of records) {
217
+ let agg = map.get(record.project);
218
+ if (!agg) {
219
+ agg = {
220
+ project: record.project,
221
+ sessions: 0,
222
+ activeHours: 0,
223
+ steeringDays: 0,
224
+ cost: 0,
225
+ costPerHour: 0,
226
+ tokensOut: 0,
227
+ cacheRead: 0,
228
+ humanTurns: 0,
229
+ assistantTurns: 0,
230
+ toolCalls: 0,
231
+ };
232
+ map.set(record.project, agg);
233
+ }
234
+ agg.sessions++;
235
+ agg.activeHours += record.activeHours;
236
+ agg.cost += record.cost;
237
+ agg.tokensOut += record.tokensOut;
238
+ agg.cacheRead += record.cacheRead;
239
+ agg.humanTurns += record.humanTurns;
240
+ agg.assistantTurns += record.assistantTurns;
241
+ agg.toolCalls += record.toolCalls;
242
+ }
243
+ for (const agg of map.values()) {
244
+ agg.steeringDays = agg.activeHours / hoursPerDay;
245
+ agg.costPerHour = agg.activeHours > 0 ? agg.cost / agg.activeHours : 0;
246
+ }
247
+ return [...map.values()].sort((a, b) => b.activeHours - a.activeHours);
248
+ }
249
+
250
+ export interface MeasuredConstants {
251
+ sessions: number;
252
+ activeHours: number;
253
+ steeringDays: number;
254
+ totalCost: number;
255
+ /** Real billed cost per active steering hour — the most robust agentic cost driver. */
256
+ costPerSteeringHour: number;
257
+ costPerSteeringDay: number;
258
+ /** ACEM Context Factor, measured as cache-read per turn in long vs short sessions. */
259
+ contextFactor: number;
260
+ /** ACEM Revision Factor LOWER BOUND: tool-error rate + human-correction rate. */
261
+ revisionFactorLowerBound: number;
262
+ toolErrorRate: number;
263
+ correctionRate: number;
264
+ /** Output tokens as a share of all tokens billed. */
265
+ outputShare: number;
266
+ outputTokensPerHour: number;
267
+ assistantPerHumanTurn: number;
268
+ toolCallsPerHour: number;
269
+ cacheReadShare: number;
270
+ /** Calendar months with meaningful activity. */
271
+ activeMonths: number;
272
+ /** Mean active steering hours per active month. */
273
+ hoursPerMonth: number;
274
+ /** Mean meter-equivalent spend per active month — what a subscription must beat. */
275
+ meterPerMonth: number;
276
+ /** Share of active hours on models the meter priced at zero (routed/subscription-billed). */
277
+ unmeteredHourShare: number;
278
+ }
279
+
280
+ export interface SubscriptionComparison {
281
+ monthlySeatCost: number;
282
+ months: number;
283
+ subscriptionCost: number;
284
+ meterEquivalent: number;
285
+ /** Meter-equivalent divided by subscription cost. Above 1 means the plan pays for itself. */
286
+ leverage: number;
287
+ effectiveCostPerHour: number;
288
+ meteredCostPerHour: number;
289
+ }
290
+
291
+ /**
292
+ * Compare what the measured work actually cost on a seat plan against what the
293
+ * same work would have cost on the token meter.
294
+ *
295
+ * The gap is subscription LEVERAGE. It is not a saving already banked — it is the
296
+ * on-demand value the flat plan captured.
297
+ */
298
+ export function compareSubscription(
299
+ measured: MeasuredConstants,
300
+ monthlySeatCost: number,
301
+ months?: number,
302
+ ): SubscriptionComparison {
303
+ const period = months ?? measured.activeMonths;
304
+ const subscriptionCost = monthlySeatCost * period;
305
+ return {
306
+ monthlySeatCost,
307
+ months: period,
308
+ subscriptionCost,
309
+ meterEquivalent: measured.totalCost,
310
+ leverage: subscriptionCost > 0 ? measured.totalCost / subscriptionCost : 0,
311
+ effectiveCostPerHour: measured.activeHours > 0 ? subscriptionCost / measured.activeHours : 0,
312
+ meteredCostPerHour: measured.costPerSteeringHour,
313
+ };
314
+ }
315
+
316
+ /** Derive the measured constants the estimator needs. */
317
+ export function measureConstants(records: SessionRecord[], hoursPerDay = 8): MeasuredConstants {
318
+ const sum = (pick: (r: SessionRecord) => number) => records.reduce((s, r) => s + pick(r), 0);
319
+
320
+ const activeHours = sum((r) => r.activeHours);
321
+ const totalCost = sum((r) => r.cost);
322
+ const tokensOut = sum((r) => r.tokensOut);
323
+ const tokensIn = sum((r) => r.tokensIn);
324
+ const cacheRead = sum((r) => r.cacheRead);
325
+ const cacheWrite = sum((r) => r.cacheWrite);
326
+ const allTokens = tokensOut + tokensIn + cacheRead + cacheWrite;
327
+ const toolResults = sum((r) => r.toolResults);
328
+ const toolErrors = sum((r) => r.toolErrors);
329
+ const humanTurns = sum((r) => r.humanTurns);
330
+ const corrections = sum((r) => r.corrections);
331
+
332
+ // Context Factor: how much more context a long session re-reads per turn.
333
+ const short = records.filter((r) => r.assistantTurns <= 20);
334
+ const long = records.filter((r) => r.assistantTurns >= 60);
335
+ const perTurn = (group: SessionRecord[]) => {
336
+ const turns = group.reduce((s, r) => s + r.assistantTurns, 0);
337
+ return turns > 0 ? group.reduce((s, r) => s + r.cacheRead, 0) / turns : 0;
338
+ };
339
+ const shortPerTurn = perTurn(short);
340
+ const longPerTurn = perTurn(long);
341
+ const contextFactor = shortPerTurn > 0 && longPerTurn > 0 ? longPerTurn / shortPerTurn : 1;
342
+
343
+ const toolErrorRate = toolResults > 0 ? toolErrors / toolResults : 0;
344
+ const correctionRate = humanTurns > 0 ? corrections / humanTurns : 0;
345
+
346
+ // Calendar spread: subscription cost is per month, so months are a cost driver.
347
+ const monthly = new Map<string, number>();
348
+ for (const record of records) {
349
+ if (!record.startedAt) continue;
350
+ const key = new Date(record.startedAt).toISOString().slice(0, 7);
351
+ monthly.set(key, (monthly.get(key) ?? 0) + record.activeHours);
352
+ }
353
+ const activeMonths = [...monthly.values()].filter((h) => h >= 1).length || monthly.size || 1;
354
+
355
+ // Hours the meter priced at zero: routed or subscription-billed models where
356
+ // token cost is not reported. These deflate any $/h figure computed naively.
357
+ const unmeteredHours = records.filter((r) => r.cost === 0).reduce((s, r) => s + r.activeHours, 0);
358
+
359
+ return {
360
+ sessions: records.length,
361
+ activeHours,
362
+ steeringDays: activeHours / hoursPerDay,
363
+ totalCost,
364
+ costPerSteeringHour: activeHours > 0 ? totalCost / activeHours : 0,
365
+ costPerSteeringDay: activeHours > 0 ? (totalCost / activeHours) * hoursPerDay : 0,
366
+ contextFactor,
367
+ revisionFactorLowerBound: 1 + toolErrorRate + correctionRate,
368
+ toolErrorRate,
369
+ correctionRate,
370
+ outputShare: allTokens > 0 ? tokensOut / allTokens : 0,
371
+ outputTokensPerHour: activeHours > 0 ? tokensOut / activeHours : 0,
372
+ assistantPerHumanTurn: humanTurns > 0 ? sum((r) => r.assistantTurns) / humanTurns : 0,
373
+ toolCallsPerHour: activeHours > 0 ? sum((r) => r.toolCalls) / activeHours : 0,
374
+ cacheReadShare: allTokens > 0 ? cacheRead / allTokens : 0,
375
+ activeMonths,
376
+ hoursPerMonth: activeHours / activeMonths,
377
+ meterPerMonth: totalCost / activeMonths,
378
+ unmeteredHourShare: activeHours > 0 ? unmeteredHours / activeHours : 0,
379
+ };
380
+ }