@trazum/core 1.36.0 → 1.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/plan.ts ADDED
@@ -0,0 +1,207 @@
1
+ /**
2
+ * Not a list of findings — a ranked, costed, non-additive plan of what to do.
3
+ *
4
+ * The report names findings; a person then decides what to do first by doing
5
+ * arithmetic in their head, and head-arithmetic on savings gets done by
6
+ * *adding* them — which the levers module has documented as wrong since it
7
+ * shipped ($12.60 plus $10.50 against a $21.00 slice). This module does the
8
+ * composition once, correctly, and attaches to every action the things the
9
+ * log cannot confirm, because a plan that hides its assumptions is advice
10
+ * pretending to be arithmetic.
11
+ *
12
+ * **Everything here is derived from figures the report already computed.**
13
+ * Route and batch come from `billLevers` (combined, never summed). The
14
+ * truncation action's stake is the retry bill `truncationRetries` measured.
15
+ * The cache action's stake is `cacheEconomics`' own delta. Nothing is
16
+ * invented, and each action carries how to check the part that is not
17
+ * arithmetic.
18
+ *
19
+ * **The total is stated honestly.** Actions on *different* slices add
20
+ * cleanly; the one composition that does not add — route and batch on the
21
+ * same slice — arrives already combined inside a single action, so the
22
+ * plan's total is a sum of non-overlapping figures by construction. Measured
23
+ * stakes (money already spent on retries, money already lost to caching) are
24
+ * totalled separately from projected savings: "what you would save" and
25
+ * "what you already paid" are different columns, and merging them makes a
26
+ * number that is neither.
27
+ */
28
+
29
+ import { UNLABELLED, cacheEconomics } from './usage.js';
30
+ import type { UsageProfileReport } from './usage.js';
31
+ import type { BillLevers } from './levers.js';
32
+
33
+ export type PlanActionKind = 'route' | 'batch' | 'route+batch' | 'fix-truncation' | 'fix-caching';
34
+
35
+ /**
36
+ * What the log cannot confirm, as data rather than prose.
37
+ *
38
+ * Rendering lives with whoever renders — the CLI localizes these, and 1.39's
39
+ * verification can match them structurally. An English sentence baked in here
40
+ * would be a browser-safe module deciding the reader's language.
41
+ */
42
+ export type PlanAssumption =
43
+ /** The cheaper model can actually do this work — quality, not arithmetic. */
44
+ | { kind: 'model-capability'; model: string }
45
+ /** These calls tolerate a batch window's latency. */
46
+ | { kind: 'batch-window' }
47
+ /** The truncation-retry pairing is real — the log sees shapes, not content. */
48
+ | { kind: 'retry-pattern-real' }
49
+ /** A max_tokens the answers fit inside removes the retry pair. */
50
+ | { kind: 'max-tokens-fits' }
51
+ /** The traffic pattern holds — a cache underwater on this log may pay on other traffic. */
52
+ | { kind: 'traffic-pattern-holds' };
53
+
54
+ export interface PlanAction {
55
+ kind: PlanActionKind;
56
+ /** The workload this acts on. `UNLABELLED` renders as the unlabelled bucket. */
57
+ label: string;
58
+ model: string;
59
+ /**
60
+ * Projected saving per the log's own period, for route/batch — or null for
61
+ * the measured-stake actions, whose money is in `stakeUsd` instead. Never
62
+ * both: a projection and a measurement in one field is a number that is
63
+ * neither.
64
+ */
65
+ savingUsd: number | null;
66
+ /**
67
+ * Money already measured against this problem — the retry bill, the cache
68
+ * loss. Null for the projected actions.
69
+ */
70
+ stakeUsd: number | null;
71
+ /** What the log cannot confirm. Every entry is a human's question to answer. */
72
+ assumes: PlanAssumption[];
73
+ /** How to check the assumption, when a Trazum command can. */
74
+ check: string | null;
75
+ /** What this action does, in one machine-stable keyword per detail. */
76
+ detail: {
77
+ /** Route target, when the action moves the calls. */
78
+ routeTo?: { id: string; displayName: string };
79
+ /** The measured pieces behind a stake. */
80
+ measured?: Record<string, number>;
81
+ };
82
+ }
83
+
84
+ export interface PlanDocument {
85
+ /** Same contract discipline as the profile JSON. */
86
+ schemaVersion: 1;
87
+ /** The period the plan's figures cover, or null when the log had no clock. */
88
+ span: { fromMs: number; toMs: number } | null;
89
+ /** The price table behind every dollar here. */
90
+ pricingLastReviewed: string;
91
+ /** Ranked: largest money first, projected or staked alike. */
92
+ actions: PlanAction[];
93
+ /**
94
+ * Projected savings summed — additive by construction, because same-slice
95
+ * compositions arrive pre-combined in one action.
96
+ */
97
+ projectedSavingUsd: number;
98
+ /** Measured stakes summed: money already paid to problems this plan names. */
99
+ measuredStakeUsd: number;
100
+ /** The bill the plan was made against. */
101
+ totalUsd: number;
102
+ }
103
+
104
+ /**
105
+ * Builds the plan from a report and its levers.
106
+ *
107
+ * `pricingLastReviewed` is passed in rather than imported so the plan records
108
+ * the catalogue that actually priced it — an overlay's date when one was in
109
+ * effect, which 1.39's verification needs to tell "the prediction was wrong"
110
+ * from "the prices changed".
111
+ */
112
+ export function buildPlan(
113
+ report: UsageProfileReport,
114
+ levers: BillLevers,
115
+ pricingLastReviewed: string,
116
+ ): PlanDocument {
117
+ const actions: PlanAction[] = [];
118
+
119
+ for (const slice of levers.slices) {
120
+ const assumes: PlanAssumption[] = [];
121
+ let kind: PlanActionKind;
122
+ if (slice.route !== null && slice.batch !== null) {
123
+ kind = 'route+batch';
124
+ assumes.push({ kind: 'model-capability', model: slice.route.candidate.displayName });
125
+ assumes.push({ kind: 'batch-window' });
126
+ } else if (slice.route !== null) {
127
+ kind = 'route';
128
+ assumes.push({ kind: 'model-capability', model: slice.route.candidate.displayName });
129
+ } else if (slice.batch !== null) {
130
+ kind = 'batch';
131
+ assumes.push({ kind: 'batch-window' });
132
+ } else {
133
+ continue;
134
+ }
135
+ actions.push({
136
+ kind,
137
+ label: slice.label,
138
+ model: slice.model,
139
+ savingUsd: slice.combinedUsd,
140
+ stakeUsd: null,
141
+ assumes,
142
+ check: slice.route !== null ? 'trazum route <log> --prompt-file <prompt> --cases <cases>' : null,
143
+ detail: slice.route !== null ? { routeTo: slice.route.candidate } : {},
144
+ });
145
+ }
146
+
147
+ for (const row of report.truncationRetries) {
148
+ actions.push({
149
+ kind: 'fix-truncation',
150
+ label: row.label,
151
+ model: row.model,
152
+ savingUsd: null,
153
+ stakeUsd: row.wastedUsd + row.retryUsd,
154
+ assumes: [{ kind: 'retry-pattern-real' }, { kind: 'max-tokens-fits' }],
155
+ check: null,
156
+ detail: {
157
+ measured: {
158
+ wastedUsd: row.wastedUsd,
159
+ retryUsd: row.retryUsd,
160
+ retried: row.retried,
161
+ truncatedCalls: row.truncatedCalls,
162
+ },
163
+ },
164
+ });
165
+ }
166
+
167
+ for (const slice of report.byLabelAndModel) {
168
+ const economics = cacheEconomics(slice.breakdown);
169
+ // Only a settled loss becomes an action: an unsettled verdict is a
170
+ // missing field, and "add the field" is the report's advice, not a plan's.
171
+ if (economics.verdict !== 'lost-money' || economics.worstCaseVerdict !== economics.verdict) continue;
172
+ actions.push({
173
+ kind: 'fix-caching',
174
+ label: slice.label,
175
+ model: slice.model,
176
+ savingUsd: null,
177
+ stakeUsd: economics.deltaUsd,
178
+ assumes: [{ kind: 'traffic-pattern-holds' }],
179
+ check: null,
180
+ detail: {
181
+ measured: {
182
+ spentUsd: economics.spentUsd,
183
+ withoutCachingUsd: economics.withoutCachingUsd,
184
+ },
185
+ },
186
+ });
187
+ }
188
+
189
+ actions.sort(
190
+ (a, b) => (b.savingUsd ?? b.stakeUsd ?? 0) - (a.savingUsd ?? a.stakeUsd ?? 0),
191
+ );
192
+
193
+ return {
194
+ schemaVersion: 1,
195
+ span: report.span === null ? null : { fromMs: report.span.fromMs, toMs: report.span.toMs },
196
+ pricingLastReviewed,
197
+ actions,
198
+ projectedSavingUsd: actions.reduce((sum, a) => sum + (a.savingUsd ?? 0), 0),
199
+ measuredStakeUsd: actions.reduce((sum, a) => sum + (a.stakeUsd ?? 0), 0),
200
+ totalUsd: report.total.totalUsd,
201
+ };
202
+ }
203
+
204
+ /** Renders `UNLABELLED` for humans without leaking the sentinel. */
205
+ export function planLabelName(label: string, unlabelled: string): string {
206
+ return label === UNLABELLED ? unlabelled : label;
207
+ }