@trazum/core 1.38.0 → 1.40.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/dist/verify.js ADDED
@@ -0,0 +1,193 @@
1
+ /**
2
+ * Did it work? — the plan held to the log that came after it.
3
+ *
4
+ * Every optimisation tool says what you *would* save; almost none says what
5
+ * you *did*. This module takes a saved plan and a newer report and answers
6
+ * per action, with **three outcomes and never two**: the change arrived, the
7
+ * change did not arrive, or *it cannot be told* — because the workload
8
+ * vanished, the fields the detection needs stopped being recorded, or the
9
+ * log simply cannot see the thing (tokens do not say which tier billed
10
+ * them). The third outcome is the honest one, and the one every other tool
11
+ * renders as the first.
12
+ *
13
+ * **Differences are attributed, not just stated.** A predicted saving that
14
+ * did not appear in the bill is decomposed against the plan's recorded
15
+ * baseline: the calls moved, the output per call moved, the input per call
16
+ * moved — measured ratios with names, never a single number that blames
17
+ * nobody. And a plan priced under one catalogue verified under another says
18
+ * so: the tool must not blame a team for a saving that arithmetic revoked.
19
+ *
20
+ * Browser-safe like everything here: two documents in, one verdict out.
21
+ */
22
+ import { cacheEconomics } from './usage.js';
23
+ /** Newer-log slices for one label, dearest first. */
24
+ function slicesForLabel(report, label) {
25
+ return report.byLabelAndModel
26
+ .filter((s) => s.label === label && s.breakdown.calls > 0)
27
+ .sort((a, b) => b.breakdown.totalUsd - a.breakdown.totalUsd);
28
+ }
29
+ function attributionFrom(action, after) {
30
+ const before = action.detail.baseline;
31
+ if (before === undefined || after === null)
32
+ return null;
33
+ return {
34
+ calls: { before: before.calls, after: after.calls },
35
+ inputPerCallTokens: { before: before.inputPerCallTokens, after: after.inputPerCallTokens },
36
+ outputPerCallTokens: { before: before.outputPerCallTokens, after: after.outputPerCallTokens },
37
+ };
38
+ }
39
+ function perCall(breakdown) {
40
+ return {
41
+ calls: breakdown.calls,
42
+ inputPerCallTokens: (breakdown.inputTokens + breakdown.cacheReadTokens + breakdown.cacheWriteTokens) / breakdown.calls,
43
+ outputPerCallTokens: breakdown.outputTokens / breakdown.calls,
44
+ };
45
+ }
46
+ export function verifyPlan(plan, report, options) {
47
+ const actions = [];
48
+ for (const action of plan.actions) {
49
+ const slices = slicesForLabel(report, action.label);
50
+ const total = slices.reduce((sum, s) => sum + s.breakdown.totalUsd, 0);
51
+ const allCalls = slices.reduce((sum, s) => sum + s.breakdown.calls, 0);
52
+ /** The label carries no priced traffic any more: nothing can be told. */
53
+ if (slices.length === 0) {
54
+ actions.push({
55
+ action,
56
+ outcome: 'cannot-tell',
57
+ reason: 'workload-vanished',
58
+ observed: {},
59
+ attribution: null,
60
+ gateFailing: false,
61
+ });
62
+ continue;
63
+ }
64
+ if (action.kind === 'route' || action.kind === 'route+batch') {
65
+ const target = action.detail.routeTo;
66
+ const dearest = slices[0];
67
+ const onTarget = slices.find((s) => s.model === target.id);
68
+ const stillOnOld = slices.find((s) => s.model === action.model);
69
+ const moved = dearest.model === target.id;
70
+ const after = perCall(moved ? dearest.breakdown : (stillOnOld ?? dearest).breakdown);
71
+ actions.push({
72
+ action,
73
+ outcome: moved ? 'arrived' : 'not-arrived',
74
+ reason: null,
75
+ observed: {
76
+ dearestModel: dearest.model,
77
+ onTargetUsd: onTarget?.breakdown.totalUsd ?? 0,
78
+ onOldModelUsd: stillOnOld?.breakdown.totalUsd ?? 0,
79
+ labelUsd: total,
80
+ labelCalls: allCalls,
81
+ // The batch half of route+batch cannot be seen in token counts;
82
+ // the rendering names it instead of counting it as arrived.
83
+ ...(action.kind === 'route+batch' ? { batchObservable: 0 } : {}),
84
+ },
85
+ attribution: attributionFrom(action, after),
86
+ gateFailing: !moved,
87
+ });
88
+ continue;
89
+ }
90
+ if (action.kind === 'batch') {
91
+ // Tokens do not say which tier billed them. Not the team's silence,
92
+ // so it cannot fail the gate — but it is said, never assumed arrived.
93
+ actions.push({
94
+ action,
95
+ outcome: 'cannot-tell',
96
+ reason: 'tier-not-recorded',
97
+ observed: { labelUsd: total, labelCalls: allCalls },
98
+ attribution: null,
99
+ gateFailing: false,
100
+ });
101
+ continue;
102
+ }
103
+ const slice = slices.find((s) => s.model === action.model);
104
+ if (action.kind === 'fix-truncation') {
105
+ // The detection needs sessions and timestamps; a log that dropped them
106
+ // reads as "no retries" for the wrong reason, and that must not pass.
107
+ if (!report.hasSessions || report.span === null) {
108
+ actions.push({
109
+ action,
110
+ outcome: 'cannot-tell',
111
+ reason: 'fields-stopped',
112
+ observed: {},
113
+ attribution: attributionFrom(action, slice ? perCall(slice.breakdown) : null),
114
+ gateFailing: true,
115
+ });
116
+ continue;
117
+ }
118
+ const row = report.truncationRetries.find((r) => r.label === action.label && r.model === action.model);
119
+ const newStake = row === undefined ? 0 : row.wastedUsd + row.retryUsd;
120
+ actions.push({
121
+ action,
122
+ outcome: row === undefined ? 'arrived' : 'not-arrived',
123
+ reason: null,
124
+ observed: {
125
+ retryBillUsd: newStake,
126
+ retried: row?.retried ?? 0,
127
+ truncatedCalls: row?.truncatedCalls ?? 0,
128
+ },
129
+ attribution: attributionFrom(action, slice ? perCall(slice.breakdown) : null),
130
+ gateFailing: row !== undefined,
131
+ });
132
+ continue;
133
+ }
134
+ // fix-caching.
135
+ if (slice === undefined) {
136
+ actions.push({
137
+ action,
138
+ outcome: 'cannot-tell',
139
+ reason: 'workload-vanished',
140
+ observed: {},
141
+ attribution: null,
142
+ gateFailing: false,
143
+ });
144
+ continue;
145
+ }
146
+ const economics = cacheEconomics(slice.breakdown);
147
+ if (economics.verdict === 'lost-money' && economics.worstCaseVerdict === economics.verdict) {
148
+ actions.push({
149
+ action,
150
+ outcome: 'not-arrived',
151
+ reason: null,
152
+ observed: { deltaUsd: economics.deltaUsd, spentUsd: economics.spentUsd },
153
+ attribution: attributionFrom(action, perCall(slice.breakdown)),
154
+ gateFailing: true,
155
+ });
156
+ }
157
+ else if (economics.worstCaseVerdict !== economics.verdict) {
158
+ // The verdict cannot settle on this log: the fields that would settle
159
+ // it are not there, and an unverifiable fix is not a verified one.
160
+ actions.push({
161
+ action,
162
+ outcome: 'cannot-tell',
163
+ reason: 'fields-stopped',
164
+ observed: {},
165
+ attribution: attributionFrom(action, perCall(slice.breakdown)),
166
+ gateFailing: true,
167
+ });
168
+ }
169
+ else {
170
+ actions.push({
171
+ action,
172
+ outcome: 'arrived',
173
+ reason: null,
174
+ observed: { deltaUsd: economics.deltaUsd, spentUsd: economics.spentUsd },
175
+ attribution: attributionFrom(action, perCall(slice.breakdown)),
176
+ gateFailing: false,
177
+ });
178
+ }
179
+ }
180
+ return {
181
+ schemaVersion: 1,
182
+ planCreatedAt: plan.createdAt ?? null,
183
+ planPricing: plan.pricingLastReviewed,
184
+ currentPricing: options.currentPricingLastReviewed,
185
+ pricesChanged: plan.pricingLastReviewed !== options.currentPricingLastReviewed,
186
+ actions,
187
+ arrived: actions.filter((a) => a.outcome === 'arrived').length,
188
+ notArrived: actions.filter((a) => a.outcome === 'not-arrived').length,
189
+ cannotTell: actions.filter((a) => a.outcome === 'cannot-tell').length,
190
+ gateFailures: actions.filter((a) => a.gateFailing).length,
191
+ };
192
+ }
193
+ //# sourceMappingURL=verify.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verify.js","sourceRoot":"","sources":["../src/verify.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AA8D5C,qDAAqD;AACrD,SAAS,cAAc,CAAC,MAA0B,EAAE,KAAa;IAC/D,OAAO,MAAM,CAAC,eAAe;SAC1B,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,KAAK,KAAK,IAAI,CAAC,CAAC,SAAS,CAAC,KAAK,GAAG,CAAC,CAAC;SACzD,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,QAAQ,GAAG,CAAC,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;AACjE,CAAC;AAED,SA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AAE;gBACxE,WAAW,EAAE,eAAe,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;gBAC9D,WAAW,EAAE,KAAK;aACnB,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,OAAO;QACL,aAAa,EAAE,CAAC;QAChB,aAAa,EAAE,IAAI,CAAC,SAAS,IAAI,IAAI;QACrC,WAAW,EAAE,IAAI,CAAC,mBAAmB;QACrC,cAAc,EAAE,OAAO,CAAC,0BAA0B;QAClD,aAAa,EAAE,IAAI,CAAC,mBAAmB,KAAK,OAAO,CAAC,0BAA0B;QAC9E,OAAO;QACP,OAAO,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,MAAM;QAC9D,UAAU,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,KAAK,aAAa,CAAC,CAAC,MAAM;QACrE,UAAU,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,KAAK,aAAa,CAAC,CAAC,MAAM;QACrE,YAAY,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,MAAM;KAC1D,CAAC;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trazum/core",
3
- "version": "1.38.0",
3
+ "version": "1.40.0",
4
4
  "description": "Trazum core: priced advisories for LLM prompts (caching, model tier, batching, schemas), plus deterministic trimming, token counting and pricing.",
5
5
  "license": "MIT",
6
6
  "author": "David Mu\u00f1oz Rey",
package/src/history.ts ADDED
@@ -0,0 +1,284 @@
1
+ /**
2
+ * The long run: many reports over many periods, as one series.
3
+ *
4
+ * Every comparison in Trazum is between two logs, and a product's cost
5
+ * problem is rarely visible in two — it is visible in twenty. This module
6
+ * takes *stored reports* (the `--json` documents a team already keeps) and
7
+ * builds the series no pairwise comparison can see: the workload that grew a
8
+ * little every week, the model share that has been climbing since a date,
9
+ * the cache hit rate decaying slowly enough that no single week's report
10
+ * called it a finding.
11
+ *
12
+ * **Still no forecasts.** Twenty points make a trend visible; they do not
13
+ * make next month knowable. The series is stated, the shape is named as
14
+ * consecutive movement — never a line fitted through the points — and where
15
+ * it goes next remains the reader's to judge, the same refusal
16
+ * `modelMixDrift` has carried since 1.27.
17
+ *
18
+ * **Derived from stored reports, not re-parsed logs**, so a year of `--json`
19
+ * output is enough and the raw logs can be thrown away — which is what the
20
+ * privacy story requires anyway. Browser-safe: documents in, series out.
21
+ */
22
+
23
+ import { UNLABELLED } from './usage.js';
24
+ import type { PlanActionKind, PlanDocument } from './plan.js';
25
+
26
+ /** The slice of a stored profile document this module actually reads. */
27
+ export interface StoredReport {
28
+ /** Where it came from — a file name, shown so a finding can be traced. */
29
+ name: string;
30
+ span: { fromMs: number; toMs: number } | null;
31
+ totalUsd: number;
32
+ calls: number;
33
+ /** Label → dollars this period. */
34
+ byLabel: Map<string, number>;
35
+ /** Model → dollars this period. */
36
+ byModel: Map<string, number>;
37
+ /** Share of input tokens served from cache, or null when unknowable. */
38
+ cacheReadShare: number | null;
39
+ }
40
+
41
+ /**
42
+ * A run of consecutive movement, named — never extrapolated.
43
+ *
44
+ * `periods` counts the *rises* (or falls), so a run of 3 spans 4 reports.
45
+ * The floor is 3: two rises is what `--against` already shows, and one is
46
+ * noise wearing a trend's clothes.
47
+ */
48
+ export interface HistoryRun {
49
+ kind: 'label-spend-climbing' | 'model-share-climbing' | 'cache-share-decaying';
50
+ subject: string;
51
+ /** Consecutive rises (falls, for decay). */
52
+ periods: number;
53
+ /** The report the run started in, by name — "climbing since <this one>". */
54
+ sinceName: string;
55
+ /** First and last values of the run, so the reader judges the size. */
56
+ from: number;
57
+ to: number;
58
+ }
59
+
60
+ /** The same action planned again and again: a decision nobody is executing. */
61
+ export interface RepeatedPlanAction {
62
+ kind: PlanActionKind;
63
+ label: string;
64
+ model: string;
65
+ appearances: number;
66
+ firstPlanned: string | null;
67
+ lastPlanned: string | null;
68
+ }
69
+
70
+ export interface HistoryDocument {
71
+ schemaVersion: 1;
72
+ /** Ordered oldest first by span start. */
73
+ periods: { name: string; fromMs: number; toMs: number; totalUsd: number; calls: number }[];
74
+ /** Per label, dollars per period — null where the label had no traffic. */
75
+ labelSeries: { label: string; points: (number | null)[] }[];
76
+ /** Per model, share of that period's total — null where absent. */
77
+ modelShareSeries: { model: string; points: (number | null)[] }[];
78
+ /** Cache read share per period, null where unknowable. */
79
+ cacheShareSeries: (number | null)[];
80
+ /** The findings only a series can make. Shapes, never forecasts. */
81
+ runs: HistoryRun[];
82
+ /** Plans in the same directory, held against each other. */
83
+ repeatedPlanActions: RepeatedPlanAction[];
84
+ /**
85
+ * Reports that carry no span cannot be placed on a timeline; they are
86
+ * named here and in no series above, never silently absorbed.
87
+ */
88
+ undatedReports: string[];
89
+ }
90
+
91
+ export const MIN_RUN = 3;
92
+
93
+ /** The longest run of strictly consecutive movement ending anywhere in the series. */
94
+ function longestRun(
95
+ points: (number | null)[],
96
+ direction: 1 | -1,
97
+ ): { start: number; length: number } | null {
98
+ let best: { start: number; length: number } | null = null;
99
+ let start = -1;
100
+ let length = 0;
101
+ for (let i = 1; i < points.length; i++) {
102
+ const prev = points[i - 1] ?? null;
103
+ const here = points[i] ?? null;
104
+ if (prev !== null && here !== null && Math.sign(here - prev) === direction && here !== prev) {
105
+ if (length === 0) start = i - 1;
106
+ length += 1;
107
+ if (best === null || length > best.length) best = { start, length };
108
+ } else {
109
+ length = 0;
110
+ }
111
+ }
112
+ return best !== null && best.length >= MIN_RUN ? best : null;
113
+ }
114
+
115
+ export function buildHistory(
116
+ reports: StoredReport[],
117
+ plans: (PlanDocument & { createdAt?: string; name?: string })[] = [],
118
+ ): HistoryDocument {
119
+ const undatedReports = reports.filter((r) => r.span === null).map((r) => r.name);
120
+ const dated = reports
121
+ .filter((r) => r.span !== null)
122
+ .sort((a, b) => a.span!.fromMs - b.span!.fromMs);
123
+
124
+ const periods = dated.map((r) => ({
125
+ name: r.name,
126
+ fromMs: r.span!.fromMs,
127
+ toMs: r.span!.toMs,
128
+ totalUsd: r.totalUsd,
129
+ calls: r.calls,
130
+ }));
131
+
132
+ const labels = [...new Set(dated.flatMap((r) => [...r.byLabel.keys()]))].sort();
133
+ const labelSeries = labels.map((label) => ({
134
+ label,
135
+ points: dated.map((r) => r.byLabel.get(label) ?? null),
136
+ }));
137
+
138
+ const models = [...new Set(dated.flatMap((r) => [...r.byModel.keys()]))].sort();
139
+ const modelShareSeries = models.map((model) => ({
140
+ model,
141
+ points: dated.map((r) => {
142
+ const usd = r.byModel.get(model);
143
+ if (usd === undefined || r.totalUsd <= 0) return null;
144
+ return usd / r.totalUsd;
145
+ }),
146
+ }));
147
+
148
+ const cacheShareSeries = dated.map((r) => r.cacheReadShare);
149
+
150
+ const runs: HistoryRun[] = [];
151
+ for (const series of labelSeries) {
152
+ const run = longestRun(series.points, 1);
153
+ if (run === null) continue;
154
+ runs.push({
155
+ kind: 'label-spend-climbing',
156
+ subject: series.label,
157
+ periods: run.length,
158
+ sinceName: periods[run.start]!.name,
159
+ from: series.points[run.start]!,
160
+ to: series.points[run.start + run.length]!,
161
+ });
162
+ }
163
+ for (const series of modelShareSeries) {
164
+ const run = longestRun(series.points, 1);
165
+ if (run === null) continue;
166
+ runs.push({
167
+ kind: 'model-share-climbing',
168
+ subject: series.model,
169
+ periods: run.length,
170
+ sinceName: periods[run.start]!.name,
171
+ from: series.points[run.start]!,
172
+ to: series.points[run.start + run.length]!,
173
+ });
174
+ }
175
+ {
176
+ const run = longestRun(cacheShareSeries, -1);
177
+ if (run !== null) {
178
+ runs.push({
179
+ kind: 'cache-share-decaying',
180
+ subject: 'cache',
181
+ periods: run.length,
182
+ sinceName: periods[run.start]!.name,
183
+ from: cacheShareSeries[run.start]!,
184
+ to: cacheShareSeries[run.start + run.length]!,
185
+ });
186
+ }
187
+ }
188
+ runs.sort((a, b) => b.periods - a.periods);
189
+
190
+ /**
191
+ * Plans held against each other: the same action (kind, label, model) in
192
+ * two or more plans is a decision nobody is executing, and the dates make
193
+ * the sentence sayable — "planned first on <date>, still planned on
194
+ * <date>".
195
+ */
196
+ const seen = new Map<string, RepeatedPlanAction>();
197
+ const ordered = [...plans].sort((a, b) => (a.createdAt ?? '').localeCompare(b.createdAt ?? ''));
198
+ for (const plan of ordered) {
199
+ for (const action of plan.actions) {
200
+ const key = `${action.kind}\n${action.label}\n${action.model}`;
201
+ const entry = seen.get(key);
202
+ if (entry === undefined) {
203
+ seen.set(key, {
204
+ kind: action.kind,
205
+ label: action.label,
206
+ model: action.model,
207
+ appearances: 1,
208
+ firstPlanned: plan.createdAt ?? null,
209
+ lastPlanned: plan.createdAt ?? null,
210
+ });
211
+ } else {
212
+ entry.appearances += 1;
213
+ entry.lastPlanned = plan.createdAt ?? entry.lastPlanned;
214
+ }
215
+ }
216
+ }
217
+ const repeatedPlanActions = [...seen.values()]
218
+ .filter((entry) => entry.appearances >= 2)
219
+ .sort((a, b) => b.appearances - a.appearances);
220
+
221
+ return {
222
+ schemaVersion: 1,
223
+ periods,
224
+ labelSeries,
225
+ modelShareSeries,
226
+ cacheShareSeries,
227
+ runs,
228
+ repeatedPlanActions,
229
+ undatedReports,
230
+ };
231
+ }
232
+
233
+ /**
234
+ * Reads one stored `profile --json` document into the slice history needs.
235
+ * Returns null when the JSON is not a profile document — the caller names
236
+ * the file rather than absorbing it.
237
+ */
238
+ export function storedReportFrom(name: string, parsed: unknown): StoredReport | null {
239
+ const doc = parsed as {
240
+ schemaVersion?: number;
241
+ span?: { fromMs: number; toMs: number } | null;
242
+ total?: {
243
+ totalUsd?: number;
244
+ calls?: number;
245
+ inputTokens?: number;
246
+ cacheReadTokens?: number;
247
+ cacheWriteTokens?: number;
248
+ };
249
+ byLabelAndModel?: {
250
+ label?: string;
251
+ model?: string;
252
+ breakdown?: { totalUsd?: number };
253
+ }[];
254
+ };
255
+ if (doc === null || typeof doc !== 'object') return null;
256
+ if (doc.schemaVersion !== 1 || doc.total === undefined || !Array.isArray(doc.byLabelAndModel)) {
257
+ return null;
258
+ }
259
+
260
+ const byLabel = new Map<string, number>();
261
+ const byModel = new Map<string, number>();
262
+ for (const slice of doc.byLabelAndModel) {
263
+ const usd = slice.breakdown?.totalUsd ?? 0;
264
+ const label = slice.label ?? UNLABELLED;
265
+ const model = slice.model ?? 'unknown';
266
+ byLabel.set(label, (byLabel.get(label) ?? 0) + usd);
267
+ byModel.set(model, (byModel.get(model) ?? 0) + usd);
268
+ }
269
+
270
+ const input = doc.total.inputTokens ?? 0;
271
+ const cacheRead = doc.total.cacheReadTokens ?? 0;
272
+ const cacheWrite = doc.total.cacheWriteTokens ?? 0;
273
+ const denominator = input + cacheRead + cacheWrite;
274
+
275
+ return {
276
+ name,
277
+ span: doc.span ?? null,
278
+ totalUsd: doc.total.totalUsd ?? 0,
279
+ calls: doc.total.calls ?? 0,
280
+ byLabel,
281
+ byModel,
282
+ cacheReadShare: denominator > 0 ? cacheRead / denominator : null,
283
+ };
284
+ }
package/src/index.ts CHANGED
@@ -46,6 +46,10 @@ export { measuredUsage, labelCoverage, MIN_SCALE_DAYS, SCALE_TO_DAYS } from './m
46
46
  export { assignSources, fleetRollup } from './fleet.js';
47
47
  export { buildPlan, planLabelName } from './plan.js';
48
48
  export type { PlanAction, PlanActionKind, PlanAssumption, PlanDocument } from './plan.js';
49
+ export { verifyPlan } from './verify.js';
50
+ export { buildHistory, storedReportFrom, MIN_RUN } from './history.js';
51
+ export type { HistoryDocument, HistoryRun, RepeatedPlanAction, StoredReport } from './history.js';
52
+ export type { CannotTellReason, PlanVerification, VerifiedAction, VerifyOutcome } from './verify.js';
49
53
  export type { FleetSource, FleetRollup } from './fleet.js';
50
54
  export type { MeasuredUsage, LabelCoverage } from './measured-profile.js';
51
55
  export type { GateExplanation } from './gate-explain.js';
package/src/plan.ts CHANGED
@@ -78,6 +78,13 @@ export interface PlanAction {
78
78
  routeTo?: { id: string; displayName: string };
79
79
  /** The measured pieces behind a stake. */
80
80
  measured?: Record<string, number>;
81
+ /**
82
+ * The slice as it was when the plan was made — what a later verification
83
+ * compares the newer log against. Without this the plan is a prediction
84
+ * with no record of the world it was made in, and "calls doubled" could
85
+ * never be told from "the prediction was wrong".
86
+ */
87
+ baseline?: { calls: number; usd: number; inputPerCallTokens: number; outputPerCallTokens: number };
81
88
  };
82
89
  }
83
90
 
@@ -116,6 +123,19 @@ export function buildPlan(
116
123
  ): PlanDocument {
117
124
  const actions: PlanAction[] = [];
118
125
 
126
+ /** The slice as the plan saw it, recorded so verification has a "before". */
127
+ const baselineOf = (label: string, model: string) => {
128
+ const slice = report.byLabelAndModel.find((s) => s.label === label && s.model === model);
129
+ if (slice === undefined || slice.breakdown.calls === 0) return undefined;
130
+ const b = slice.breakdown;
131
+ return {
132
+ calls: b.calls,
133
+ usd: b.totalUsd,
134
+ inputPerCallTokens: (b.inputTokens + b.cacheReadTokens + b.cacheWriteTokens) / b.calls,
135
+ outputPerCallTokens: b.outputTokens / b.calls,
136
+ };
137
+ };
138
+
119
139
  for (const slice of levers.slices) {
120
140
  const assumes: PlanAssumption[] = [];
121
141
  let kind: PlanActionKind;
@@ -140,7 +160,10 @@ export function buildPlan(
140
160
  stakeUsd: null,
141
161
  assumes,
142
162
  check: slice.route !== null ? 'trazum route <log> --prompt-file <prompt> --cases <cases>' : null,
143
- detail: slice.route !== null ? { routeTo: slice.route.candidate } : {},
163
+ detail: {
164
+ ...(slice.route !== null ? { routeTo: slice.route.candidate } : {}),
165
+ baseline: baselineOf(slice.label, slice.model),
166
+ },
144
167
  });
145
168
  }
146
169
 
@@ -160,6 +183,7 @@ export function buildPlan(
160
183
  retried: row.retried,
161
184
  truncatedCalls: row.truncatedCalls,
162
185
  },
186
+ baseline: baselineOf(row.label, row.model),
163
187
  },
164
188
  });
165
189
  }
@@ -182,6 +206,7 @@ export function buildPlan(
182
206
  spentUsd: economics.spentUsd,
183
207
  withoutCachingUsd: economics.withoutCachingUsd,
184
208
  },
209
+ baseline: baselineOf(slice.label, slice.model),
185
210
  },
186
211
  });
187
212
  }