@trazum/core 1.55.0 → 1.56.1

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/history.ts CHANGED
@@ -60,6 +60,58 @@ export interface HistoryRun {
60
60
  /** First and last values of the run, so the reader judges the size. */
61
61
  from: number;
62
62
  to: number;
63
+ /**
64
+ * Days inside this run's stretch that no report covers.
65
+ *
66
+ * A run is *consecutive reports*, and until this field existed it read as
67
+ * *consecutive time*. Four reports with a three-week hole between the second
68
+ * and the third is not "climbing for four periods" in any sense a reader
69
+ * would act on — the climb may have reversed and come back inside the hole,
70
+ * and nothing here can see it. The caveat travels with the finding rather
71
+ * than living in another field the reader has to cross-reference, because a
72
+ * finding that needs a second lookup to be read correctly will be read
73
+ * incorrectly.
74
+ */
75
+ unmeasuredDays: number;
76
+ }
77
+
78
+ /**
79
+ * A stretch of calendar time no stored report covers.
80
+ *
81
+ * Arithmetic on the spans, not an inference about a schedule: this module has
82
+ * no idea how often somebody meant to run anything, and guessing a cadence in
83
+ * order to call a gap late would be the tool deciding what the reader's
84
+ * routine is. A hole between one report's end and the next one's start is a
85
+ * fact about the reports.
86
+ *
87
+ * It is also the whole of what "nobody produced this series on a schedule"
88
+ * looks like from inside the data: a cron that died three weeks ago does not
89
+ * announce itself, it just stops adding points — and a shorter series and a
90
+ * series with a hole in it read identically until somebody says which.
91
+ */
92
+ export interface UnmeasuredStretch {
93
+ fromMs: number;
94
+ toMs: number;
95
+ days: number;
96
+ /** The report that ends where the hole begins. */
97
+ afterName: string;
98
+ /** The report that begins where the hole ends. */
99
+ beforeName: string;
100
+ }
101
+
102
+ /**
103
+ * Two reports covering some of the same calendar time.
104
+ *
105
+ * `history` never sums `totalUsd` across periods, but a reader with the
106
+ * document in a spreadsheet will, and two reports over the same fortnight
107
+ * count that fortnight twice. Named rather than merged: which of the two is
108
+ * the better measurement is not knowable from here, and picking one would be
109
+ * throwing away money on a guess.
110
+ */
111
+ export interface OverlappingReports {
112
+ a: string;
113
+ b: string;
114
+ days: number;
63
115
  }
64
116
 
65
117
  /** The same action planned again and again: a decision nobody is executing. */
@@ -91,10 +143,87 @@ export interface HistoryDocument {
91
143
  * named here and in no series above, never silently absorbed.
92
144
  */
93
145
  undatedReports: string[];
146
+ /**
147
+ * Calendar time between the first report's start and the last one's end
148
+ * that no report covers, oldest first.
149
+ *
150
+ * The series is stated with its holes rather than closed over them: a
151
+ * scheduled run that stopped three weeks ago produces a series that looks
152
+ * exactly like a shorter one, and only this field tells the two apart.
153
+ */
154
+ unmeasured: UnmeasuredStretch[];
155
+ /** The same calendar time covered by two reports. Named, never merged. */
156
+ overlappingReports: OverlappingReports[];
94
157
  }
95
158
 
96
159
  export const MIN_RUN = 3;
97
160
 
161
+ const DAY_MS = 86_400_000;
162
+
163
+ /**
164
+ * Whole days between two instants, never negative and never rounded up.
165
+ *
166
+ * Rounded down deliberately: a gap this module calls three days must be at
167
+ * least three days. A ceiling would make the smallest possible hole read as a
168
+ * day of missing measurement, which is the flattering direction inverted —
169
+ * alarming rather than reassuring, and just as wrong.
170
+ */
171
+ const daysBetween = (fromMs: number, toMs: number): number =>
172
+ Math.max(0, Math.floor((toMs - fromMs) / DAY_MS));
173
+
174
+ /**
175
+ * The holes and the overlaps in a set of dated reports.
176
+ *
177
+ * One sweep in start order. A report that ends before the furthest end seen so
178
+ * far is contained in what is already covered and moves nothing; one that
179
+ * starts after it opens a hole; one that starts before it overlaps.
180
+ */
181
+ function coverageOf(
182
+ dated: { name: string; fromMs: number; toMs: number }[],
183
+ ): { unmeasured: UnmeasuredStretch[]; overlaps: OverlappingReports[] } {
184
+ const unmeasured: UnmeasuredStretch[] = [];
185
+ const overlaps: OverlappingReports[] = [];
186
+ if (dated.length === 0) return { unmeasured, overlaps };
187
+
188
+ let coveredTo = dated[0]!.toMs;
189
+ let coveredBy = dated[0]!.name;
190
+ for (let i = 1; i < dated.length; i += 1) {
191
+ const report = dated[i]!;
192
+ if (report.fromMs > coveredTo) {
193
+ const days = daysBetween(coveredTo, report.fromMs);
194
+ // A hole shorter than a whole day is the seam between two adjacent
195
+ // exports, not a stretch nobody measured.
196
+ if (days > 0) {
197
+ unmeasured.push({
198
+ fromMs: coveredTo,
199
+ toMs: report.fromMs,
200
+ days,
201
+ afterName: coveredBy,
202
+ beforeName: report.name,
203
+ });
204
+ }
205
+ } else if (report.fromMs < coveredTo) {
206
+ const days = daysBetween(report.fromMs, Math.min(coveredTo, report.toMs));
207
+ if (days > 0) overlaps.push({ a: coveredBy, b: report.name, days });
208
+ }
209
+ if (report.toMs > coveredTo) {
210
+ coveredTo = report.toMs;
211
+ coveredBy = report.name;
212
+ }
213
+ }
214
+ return { unmeasured, overlaps };
215
+ }
216
+
217
+ /** Days of hole inside a stretch of the timeline. */
218
+ const unmeasuredWithin = (
219
+ unmeasured: UnmeasuredStretch[],
220
+ fromMs: number,
221
+ toMs: number,
222
+ ): number =>
223
+ unmeasured
224
+ .filter((hole) => hole.fromMs >= fromMs && hole.toMs <= toMs)
225
+ .reduce((sum, hole) => sum + hole.days, 0);
226
+
98
227
  /** The longest run of strictly consecutive movement ending anywhere in the series. */
99
228
  function longestRun(
100
229
  points: (number | null)[],
@@ -152,6 +281,12 @@ export function buildHistory(
152
281
 
153
282
  const cacheShareSeries = dated.map((r) => r.cacheReadShare);
154
283
 
284
+ const { unmeasured, overlaps: overlappingReports } = coverageOf(periods);
285
+
286
+ /** The unmeasured days a run spans, from the report it starts in to the one it ends in. */
287
+ const holeIn = (start: number, length: number): number =>
288
+ unmeasuredWithin(unmeasured, periods[start]!.fromMs, periods[start + length]!.toMs);
289
+
155
290
  const runs: HistoryRun[] = [];
156
291
  for (const series of labelSeries) {
157
292
  const run = longestRun(series.points, 1);
@@ -163,6 +298,7 @@ export function buildHistory(
163
298
  sinceName: periods[run.start]!.name,
164
299
  from: series.points[run.start]!,
165
300
  to: series.points[run.start + run.length]!,
301
+ unmeasuredDays: holeIn(run.start, run.length),
166
302
  });
167
303
  }
168
304
  for (const series of modelShareSeries) {
@@ -175,6 +311,7 @@ export function buildHistory(
175
311
  sinceName: periods[run.start]!.name,
176
312
  from: series.points[run.start]!,
177
313
  to: series.points[run.start + run.length]!,
314
+ unmeasuredDays: holeIn(run.start, run.length),
178
315
  });
179
316
  }
180
317
  {
@@ -187,6 +324,7 @@ export function buildHistory(
187
324
  sinceName: periods[run.start]!.name,
188
325
  from: cacheShareSeries[run.start]!,
189
326
  to: cacheShareSeries[run.start + run.length]!,
327
+ unmeasuredDays: holeIn(run.start, run.length),
190
328
  });
191
329
  }
192
330
  }
@@ -232,6 +370,8 @@ export function buildHistory(
232
370
  runs,
233
371
  repeatedPlanActions,
234
372
  undatedReports,
373
+ unmeasured,
374
+ overlappingReports,
235
375
  };
236
376
  }
237
377
 
package/src/index.ts CHANGED
@@ -51,6 +51,8 @@ export { explainGateFailure, gateMargin, GATE_MARGIN_TIGHT } from './gate-explai
51
51
  export { measuredUsage, labelCoverage, MIN_SCALE_DAYS, SCALE_TO_DAYS } from './measured-profile.js';
52
52
  export { assignSources, fleetRollup } from './fleet.js';
53
53
  export { rollUp } from './rollup.js';
54
+ export { heartbeats } from './heartbeat.js';
55
+ export { ruleYield } from './rule-yield.js';
54
56
  export { buildPlan, planLabelName, parsePlanDocument, PLAN_ACTION_KINDS } from './plan.js';
55
57
  export type { PlanParseFailure, PlanParseResult } from './plan.js';
56
58
  export type { PlanAction, PlanActionKind, PlanAssumption, PlanDocument } from './plan.js';
@@ -245,9 +247,24 @@ export type {
245
247
  UnavailableFinding,
246
248
  UsageBucket,
247
249
  } from './connector.js';
248
- export type { HistoryDocument, HistoryRun, RepeatedPlanAction, StoredReport } from './history.js';
250
+ export type {
251
+ HistoryDocument,
252
+ HistoryRun,
253
+ RepeatedPlanAction,
254
+ StoredReport,
255
+ UnmeasuredStretch,
256
+ OverlappingReports,
257
+ } from './history.js';
249
258
  export type { CannotTellReason, PlanVerification, VerifiedAction, VerifyOutcome } from './verify.js';
250
259
  export type { FleetSource, FleetRollup } from './fleet.js';
260
+ export type { RuleYield, RuleYieldReport } from './rule-yield.js';
261
+ export type {
262
+ Heartbeat,
263
+ HeartbeatInput,
264
+ HeartbeatKind,
265
+ HeartbeatReport,
266
+ HeartbeatVerdict,
267
+ } from './heartbeat.js';
251
268
  export type {
252
269
  RollupInput,
253
270
  RollupDocument,
@@ -0,0 +1,205 @@
1
+ /**
2
+ * Which rules actually recover anything, and how much.
3
+ *
4
+ * The README says plainly that the deterministic rules recover about one per
5
+ * cent, and that is the fair complaint about this tool. It is also an
6
+ * **aggregate**, and an aggregate is where a distribution goes to hide: seven
7
+ * rules recovering one per cent between them could be seven rules each doing a
8
+ * seventh of the work, or two rules doing all of it beside five that have never
9
+ * changed a byte of anybody's prompt.
10
+ *
11
+ * Nobody here had measured which. That is the wrong place to start an arc
12
+ * about raising the ceiling — what to add on the model's side of the line is a
13
+ * question about what the dictionary side already covers, and "about one per
14
+ * cent" does not answer it.
15
+ *
16
+ * **Two numbers per rule, and they are not the same number.**
17
+ *
18
+ * - **Alone** is what the rule saves when it is the only one running.
19
+ * - **Marginal** is what the whole set loses when the rule is removed.
20
+ *
21
+ * They diverge exactly where rules overlap, which is most of the interesting
22
+ * cases: `duplicate-lines` and `duplicate-blocks` both find a repeated stanza,
23
+ * so each has a real `alone` and a `marginal` near zero. Reporting either
24
+ * figure by itself would be wrong in a different direction — `alone` alone
25
+ * makes an overlapping rule look load-bearing, and `marginal` alone makes it
26
+ * look inert. The report carries both and **never reconciles them into one**,
27
+ * for the same reason a measurement and a projection are never added here.
28
+ *
29
+ * **Inert is a fact about the corpus, never about the rule.** A rule that finds
30
+ * nothing across twenty-one files has not been shown to be useless; it has been
31
+ * shown that these twenty-one files do not contain what it looks for. The
32
+ * distinction is the whole difference between "delete this rule" and "measure
33
+ * it on something else", and this module refuses to make the first claim.
34
+ *
35
+ * Browser-safe: prompts in, arithmetic out, no filesystem.
36
+ */
37
+
38
+ import { optimize } from './optimize.js';
39
+ import type { OptimizeOptions, RuleId } from './types.js';
40
+
41
+ export interface RuleYield {
42
+ id: RuleId;
43
+ /** Tokens saved when this rule is the only one running, across every prompt. */
44
+ alone: number;
45
+ /**
46
+ * Tokens the full set loses when this rule is removed.
47
+ *
48
+ * Zero with a non-zero `alone` means every token it finds is found by
49
+ * something else too — an overlap, not a defect, and not a reason to delete
50
+ * anything without knowing which rule is the better one to keep.
51
+ */
52
+ marginal: number;
53
+ /** How many prompts it changed at all, running alone. */
54
+ prompts: number;
55
+ }
56
+
57
+ export interface RuleYieldReport {
58
+ schemaVersion: 1;
59
+ /** Prompts measured. */
60
+ prompts: number;
61
+ /** Tokens across every prompt before any rule ran. */
62
+ tokensBefore: number;
63
+ /**
64
+ * Tokens **the rules** save across every prompt.
65
+ *
66
+ * The whole run's saving minus the floor below, because they are not the
67
+ * same thing and the first version of this module reported the difference as
68
+ * if it were the rules' work. Run over a corpus the rules do not touch, that
69
+ * version said the optimiser saved twenty-one tokens and every rule was
70
+ * redundant — a sentence assembled out of somebody else's arithmetic.
71
+ */
72
+ tokensSaved: number;
73
+ /**
74
+ * Tokens the optimiser saves with **every rule disabled**.
75
+ *
76
+ * Normalisation the optimiser does regardless of the rule set. Named rather
77
+ * than folded in: it is a real saving and it is not a rule's, and a report
78
+ * that credited it to the rules would be flattering exactly the thing this
79
+ * measurement exists to be honest about.
80
+ */
81
+ floor: number;
82
+ /** Per rule, largest `marginal` first, then largest `alone`. */
83
+ rules: RuleYield[];
84
+ /**
85
+ * `alone` summed over every rule.
86
+ *
87
+ * Stated beside `tokensSaved` and deliberately not reconciled with it: the
88
+ * gap between them **is** the overlap, and a single "total" would be the one
89
+ * number that cannot be true. Larger than `tokensSaved` means rules are
90
+ * finding the same tokens; equal means they are disjoint on this corpus.
91
+ */
92
+ sumOfAlone: number;
93
+ /**
94
+ * Rules that save something alone and nothing at the margin — every token
95
+ * they find, another rule finds too. On **this corpus**.
96
+ */
97
+ redundantHere: RuleId[];
98
+ /**
99
+ * Rules that changed nothing at all — they never fired. On **this corpus**,
100
+ * which is the only claim the arithmetic supports: a rule that finds nothing
101
+ * in these files has not been shown to find nothing anywhere.
102
+ */
103
+ inertHere: RuleId[];
104
+ /**
105
+ * Rules that **fired and recovered nothing**: they changed the prompt and
106
+ * the token count did not move.
107
+ *
108
+ * Kept apart from `inertHere`, because the two look identical in a saving
109
+ * column and mean opposite things. A rule that never fires has not been
110
+ * exercised; a rule that fires and saves nothing has been exercised and is
111
+ * altering somebody's prompt for no measured benefit — which is a finding
112
+ * about the rule rather than about the corpus, and the one this measurement
113
+ * was least likely to produce and most worth producing.
114
+ *
115
+ * `emphasis` lands here on a prompt whose shouted words it lowercases: same
116
+ * words, same count, different instruction.
117
+ */
118
+ firedWithoutSavingHere: RuleId[];
119
+ /**
120
+ * How the tokens were counted, so the reader knows the margin.
121
+ *
122
+ * `heuristic` carries the estimator's documented band, and every figure here
123
+ * inherits it — a rule whose marginal yield is a handful of tokens is inside
124
+ * the noise, and the report says which counter it used rather than leaving
125
+ * somebody to assume an exact one.
126
+ */
127
+ tokenSource: 'heuristic' | 'external';
128
+ }
129
+
130
+ /**
131
+ * Measures each rule's yield over a set of prompts.
132
+ *
133
+ * `rules` is the full set to measure — the caller passes it rather than this
134
+ * module reaching for the catalogue, so a subset can be measured and so the
135
+ * list has one home. Every run uses the same options, so the level and the
136
+ * token counter are the caller's and not this module's assumption.
137
+ */
138
+ export function ruleYield(
139
+ prompts: string[],
140
+ rules: readonly RuleId[],
141
+ options: OptimizeOptions = {},
142
+ ): RuleYieldReport {
143
+ const run = (disableRules: RuleId[]) =>
144
+ prompts.map((prompt) => optimize(prompt, { ...options, disableRules }));
145
+
146
+ const whole = run([]);
147
+ const tokensBefore = whole.reduce((sum, result) => sum + result.tokensBefore, 0);
148
+ const wholeSaved = whole.reduce((sum, result) => sum + result.tokensSaved, 0);
149
+
150
+ /**
151
+ * What the optimiser saves with every rule off.
152
+ *
153
+ * Whitespace normalisation and the like happen either way, and crediting
154
+ * them to the rules is how "the rules recover about one per cent" survives
155
+ * on a corpus where the rules recover nothing.
156
+ */
157
+ const floorResults = run([...rules]);
158
+ const floor = floorResults.reduce((sum, result) => sum + result.tokensSaved, 0);
159
+ const tokensSaved = Math.max(0, wholeSaved - floor);
160
+
161
+ const measured: RuleYield[] = rules.map((id) => {
162
+ // Alone: everything else off.
163
+ const only = run(rules.filter((other) => other !== id));
164
+ const alone = Math.max(0, only.reduce((sum, result) => sum + result.tokensSaved, 0) - floor);
165
+ // Changed against the floor's own output, not against the original: the
166
+ // normalisation changes every prompt, and counting that as this rule
167
+ // having fired is how every rule came back as touching every file.
168
+ const changed = only.filter(
169
+ (result, index) => result.optimized !== floorResults[index]?.optimized,
170
+ ).length;
171
+
172
+ // Marginal: everything on but this one.
173
+ const without = run([id]);
174
+ const withoutSaved = without.reduce((sum, result) => sum + result.tokensSaved, 0);
175
+
176
+ return {
177
+ id,
178
+ alone,
179
+ // Never negative: removing a rule cannot make the set save more, and a
180
+ // rounding artefact that said it did would be a finding nobody could act
181
+ // on. Clamped rather than reported, because the clamp is the honest
182
+ // reading of a difference inside the counter's own noise.
183
+ marginal: Math.max(0, wholeSaved - withoutSaved),
184
+ prompts: changed,
185
+ };
186
+ });
187
+
188
+ measured.sort((a, b) => b.marginal - a.marginal || b.alone - a.alone);
189
+
190
+ return {
191
+ schemaVersion: 1,
192
+ prompts: prompts.length,
193
+ tokensBefore,
194
+ tokensSaved,
195
+ floor,
196
+ rules: measured,
197
+ sumOfAlone: measured.reduce((sum, rule) => sum + rule.alone, 0),
198
+ redundantHere: measured.filter((rule) => rule.alone > 0 && rule.marginal === 0).map((rule) => rule.id),
199
+ inertHere: measured.filter((rule) => rule.prompts === 0).map((rule) => rule.id),
200
+ firedWithoutSavingHere: measured
201
+ .filter((rule) => rule.prompts > 0 && rule.alone === 0)
202
+ .map((rule) => rule.id),
203
+ tokenSource: whole[0]?.tokenSource ?? 'heuristic',
204
+ };
205
+ }
package/src/rules.ts CHANGED
@@ -300,9 +300,28 @@ const nearDuplicateBlocksRule: Rule = {
300
300
  },
301
301
  };
302
302
 
303
- /** Every rule, in the order they must run. */
303
+ /**
304
+ * Every rule, in the order they must run.
305
+ *
306
+ * **The order decides what the reader is told, not just how fast this runs.**
307
+ * A repeated stanza is a repeated *block* and also a set of repeated *lines*,
308
+ * so all three of the deletion rules can find it and whichever runs first
309
+ * takes it. Coarsest first means the report says "one repeated paragraph"
310
+ * rather than "three repeated lines" for the same saving — the same number
311
+ * attached to a sentence somebody can act on instead of three they have to
312
+ * reassemble.
313
+ *
314
+ * That was an unstated consequence until `rules --measure` made the overlap
315
+ * visible: the leave-one-out measurement credits each of the three with the
316
+ * whole saving, because each of them *would* have caught it alone. The applied
317
+ * run credits exactly one, and this list is what picks which.
318
+ *
319
+ * `rules.test.js` pins both facts, so a reorder that quietly changes the
320
+ * attribution fails the build rather than changing what users read.
321
+ */
304
322
  export const RULES: readonly Rule[] = [
305
- // Whole-block deletions first, so the rest works over less text.
323
+ // Whole-block deletions first: less text for the rest to walk, and the
324
+ // coarsest description of what was removed.
306
325
  duplicateBlocksRule,
307
326
  nearDuplicateBlocksRule,
308
327
  duplicateLinesRule,