@refactorlabs/recount 0.9.0 → 0.10.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/llms.md CHANGED
@@ -9,7 +9,7 @@ import recount from '@refactorlabs/recount';
9
9
 
10
10
  // reads RECOUNT_API_KEY / RECOUNT_ENVIRONMENT from env automatically
11
11
  // call init() only to override
12
- recount.init({ apiKey: 'bec_...', environment: 'production', debug: true });
12
+ recount.init({ apiKey: 'bec_...', environment: 'Production', debug: true });
13
13
  ```
14
14
 
15
15
  If no API key is found, the SDK disables itself. All calls become no-ops with no errors thrown.
@@ -129,9 +129,11 @@ recount.addMessage('Cache warmed');
129
129
  Adds key/value pairs to the trace metadata after the trace has started:
130
130
 
131
131
  ```ts
132
- recount.addMetadata({ Decision: 'approved', Score: 87 });
132
+ recount.addMetadata({ Decision: 'Approved', Score: 87 });
133
133
  ```
134
134
 
135
+ Metadata keys and values, and environment names, are shown to people in the dashboard and in portals. Write them as plain words: `'Application ID'` not `applicationId`, `'Production'` not `production`.
136
+
135
137
  ## recount.named
136
138
 
137
139
  Sets the span name for the next auto-recorded span from an integration (Anthropic, OpenAI, MongoDB). Applies to exactly one span.
@@ -172,16 +174,25 @@ recount.addSpan('table', 'Policy validation', {
172
174
  .appendRow([recount.spanCell('Total', 3)], 'info') // spanning cell
173
175
  .summary([{ text: 'Total: $7,590', highlight: 'info' }])
174
176
  .redact(['fieldName'])
175
- .round(2)
177
+ .format({ cost: { format: 'money', currency: 'AUD' } }) // Recount formats it; send numbers
178
+ .signHighlight('saving', { positive: 'success', negative: 'danger' })
179
+ .round(2) // not applied to formatted columns
176
180
  .build()
177
181
  });
178
182
 
179
- // multiple tables in one span
180
- output: { tables: [recount.table('A').fromRecords(a).build(), recount.table('B').fromRecords(b).build()] }
183
+ // multiple tables: one table span each, inside a group (or tableSections() for shared columns)
184
+ recount.addGroup('Claim report', (g) => {
185
+ g.span('table', 'Summary', { output: recount.tableFromObject({ data: summary }) });
186
+ g.span('table', 'Breakdown', { output: recount.tableFromRecords({ data: items }) });
187
+ });
181
188
  ```
182
189
 
190
+ Column names (and `fromObject` keys) are shown to readers as-is. Write keys as plain words (`'Estimated cost'`), or rename code keys with `.label({ estimatedCost: 'Estimated cost' })`.
191
+
183
192
  Highlights: `'danger' | 'warn' | 'success' | 'info' | 'muted'`
184
193
 
194
+ Send numbers, not formatted strings. `.format()` takes `format` (`'money' | 'number' | 'percent' | 'integer' | 'text'`), `currency`, `unit` and `places`; a percent is a fraction (`0.045` shows as `4.5%`). In a `fromObject` table a formatted key becomes a typed cell, or make one yourself: `recount.cell(18481.65, { format: 'number', unit: 'MJ' })`.
195
+
185
196
  **Shorthand methods** (skip the builder chain):
186
197
 
187
198
  ```ts
@@ -192,23 +203,98 @@ recount.tableFromRecords({ data: rows, title?: string })
192
203
  recount.tableFromObject({ data: obj, title?: string })
193
204
  ```
194
205
 
195
- ## Chart builder
206
+ ## Calculations
207
+
208
+ Trace a calculation as numbers, units and formulas, not sentences. Recount draws the table, checks every line that claims a formula and lets anyone recompute it. Never format numbers yourself.
209
+
210
+ ```ts
211
+ import recount, { calculation, units } from '@refactorlabs/recount';
212
+
213
+ const estimate = calculation('estimate', {
214
+ title: 'Estimated annual cost',
215
+ currency: 'AUD',
216
+ tolerance: 0.01
217
+ })
218
+ .input('days', 365.25, { label: 'Days', unit: units.days })
219
+ .input('daily_usage', 50.6, {
220
+ label: 'Daily usage',
221
+ unit: 'MJ/day',
222
+ source: 'Benchmark'
223
+ })
224
+ .charge('supply', 'Supply', {
225
+ quantity: 'days',
226
+ rate: supplyRate,
227
+ value: supplyCharge
228
+ }) // checks quantity * rate
229
+ .tiers('usage', {
230
+ // a working line + charge per band, then a subtotal `usage`
231
+ quantity: 'daily_usage',
232
+ periods: 'days',
233
+ unit: 'MJ',
234
+ per: 'day',
235
+ bands: [
236
+ { size: 20.71, rate: r1 },
237
+ { size: null, rate: r2 }
238
+ ], // size null = the rest
239
+ value: usageCharge // the engine's figure, checked against the bands
240
+ })
241
+ .percentOf('discount', 'Discount on usage', {
242
+ of: ['usage'],
243
+ rate: -0.03,
244
+ value: discount
245
+ })
246
+ .stated('concessions', 'Concessions', {
247
+ value: -50,
248
+ taxFree: true,
249
+ source: 'Current bill'
250
+ }) // not checked
251
+ .total(
252
+ 'total',
253
+ 'Estimated cost (incl. GST)',
254
+ "round(sum_kind('charge'), 2)",
255
+ { value: total }
256
+ )
257
+ .taxIncluded('gst', 'Includes GST', { rate: 0.1 }) // charges above not tagged tax_free; value worked out
258
+ .note('Tiers apply per day.');
259
+
260
+ recount.addCalculation('#1 Plan A', estimate, { public: true }); // one table span
261
+ // trace.calculation(name, calcs, opts) and g.calculation(...) inside addGroup work the same.
262
+ // Pass an array for several calculations in one span (up to 20); opts.side: 'input' for the input side.
263
+
264
+ // Workings as steps: step(key, label, formula, value?, opts?)
265
+ const usage = calculation('usage', { layout: 'steps', currency: 'AUD' })
266
+ .input('monthly_bill', monthlyBill, { label: 'Monthly bill' })
267
+ .input('days_per_month', 30.44, { label: 'Days per month', unit: 'days' })
268
+ .step('daily_bill', 'Daily bill', 'monthly_bill / days_per_month', dailyBill);
269
+ ```
270
+
271
+ - Formulas: `+ - * / ^`, brackets, keys of inputs and lines above, and `min max clamp abs round floor ceil mround sum sum_kind('kind') sum_tagged('tag') if(cond, a, b)`. No exponents or `%` in numbers.
272
+ - If the engine rounds, say so in the formula: `round(..., 2)`. Display rounding is Recount's.
273
+ - Leave `value` out when the engine has no figure of its own; Recount works it out (`computed`).
274
+ - Other helpers: `working(key, label, formula)` (muted, not summed), `subtotal`/`info(key, label, formula | null, opts)`, `line({...})` for any raw line.
275
+ - Line options: `value`, `unit`, `places`, `primary`, `tags`, `taxFree`, `highlight`, `detail`, `explain`, `source`, `sourceSpan`, `expected` (`{ value, source, tolerance, level, reason }`), `tolerance`, `alerts`, `redact`.
276
+ - Key `undefined` makes one from the label. The builder never throws: bad keys, units and formulas are repaired or reported in `c.problems` (and debug logs), so check `expect(c.problems).toEqual([])` in a unit test.
277
+ - `NaN` is sent as `null` (not calculated); `Infinity` too, so send text like `'Unlimited'`. Decimal strings (`'0.0316'`) and decimal.js / big.js values keep their precision.
278
+ - Checks always run; alerts only when the calculation opts in with `alerts: 'warn' | 'error'`.
196
279
 
197
280
  ```ts
198
281
  recount.addSpan('chart', 'Damage breakdown', {
199
282
  output: recount
200
- .chart('bar', 'Title') // types: 'bar'|'line'|'pie'|'scatter'
283
+ .chart('bar', 'Title') // types: 'bar'|'line'|'pie'|'scatter'
201
284
  .labels(['A', 'B', 'C'])
202
- .series('Name', [1, 2, 3]) // call multiple times for multi-series
285
+ .series('Name', [1, 2, 3]) // call multiple times for multi-series
203
286
  .referenceLine(750, 'Excess')
204
287
  .build()
205
288
  });
206
289
 
207
- // from records
208
- recount.chart('bar').fromRecords(rows, 'labelKey', ['series1', 'series2']).build()
290
+ // from records - each series is named after its key, so use readable keys
291
+ recount.chart('bar').fromRecords(rows, 'Month', ['Revenue', 'Cost']).build();
209
292
 
210
- // multiple charts
211
- output: { charts: [...] }
293
+ // multiple charts: one chart span each, inside a group
294
+ recount.addGroup('Claims dashboard', (g) => {
295
+ g.span('chart', 'By month', { output: byMonth });
296
+ g.span('chart', 'By category', { output: byCategory });
297
+ });
212
298
  ```
213
299
 
214
300
  **Shorthand method:**
@@ -355,22 +441,25 @@ HTTP spans automatically redact `Authorization`, `Cookie`, `X-Api-Key`, and rela
355
441
  import recount from '@refactorlabs/recount';
356
442
 
357
443
  const damage = [
358
- { component: 'Rear bumper', severity: 'major', estimatedCost: 2_400 },
359
- { component: 'Boot lid', severity: 'major', estimatedCost: 3_100 },
360
- { component: 'Rear lights', severity: 'moderate', estimatedCost: 890 }
444
+ { component: 'Rear bumper', severity: 'Major', estimatedCost: 2_400 },
445
+ { component: 'Boot lid', severity: 'Major', estimatedCost: 3_100 },
446
+ { component: 'Rear lights', severity: 'Moderate', estimatedCost: 890 }
361
447
  ];
362
448
  const total = damage.reduce((s, d) => s + d.estimatedCost, 0);
363
449
  const excess = 750;
450
+ const settlement = Math.max(total - excess, 0);
364
451
 
365
452
  await recount.startTrace(
366
453
  'Insurance claim - CLM-2024-03941',
367
- {
368
- metadata: { 'Claim ID': 'CLM-2024-03941' },
369
- input: recount.tableFromObject({
370
- data: { 'Claim ID': 'CLM-2024-03941', Vehicle: '2019 Toyota Camry' }
371
- })
372
- },
454
+ { metadata: { 'Claim ID': 'CLM-2024-03941' } },
373
455
  async () => {
456
+ // What the run started from goes in a span: startTrace takes no input.
457
+ recount.addSpan('table', 'Claim', {
458
+ input: recount.tableFromObject({
459
+ data: { 'Claim ID': 'CLM-2024-03941', Vehicle: '2019 Toyota Camry' }
460
+ })
461
+ });
462
+
374
463
  recount.addSpan('db', 'Policy lookup', {
375
464
  description:
376
465
  'Fetches the active policy record for the submitted claim number',
@@ -386,25 +475,40 @@ await recount.startTrace(
386
475
  output: recount
387
476
  .table()
388
477
  .fromRecords(damage)
478
+ .label({
479
+ component: 'Component',
480
+ severity: 'Severity',
481
+ estimatedCost: 'Estimated cost'
482
+ })
389
483
  .highlightRows((row) =>
390
- row.severity === 'major'
484
+ row.severity === 'Major'
391
485
  ? 'danger'
392
- : row.severity === 'moderate'
486
+ : row.severity === 'Moderate'
393
487
  ? 'warn'
394
488
  : 'muted'
395
489
  )
396
- .transformValues({
397
- estimatedCost: (v) => `$${Number(v).toLocaleString()}`
398
- })
399
- .summary([
400
- { text: `Total: $${total.toLocaleString()}`, highlight: 'info' },
401
- {
402
- text: `Settlement: $${(total - excess).toLocaleString()}`,
403
- highlight: 'success'
404
- }
405
- ])
490
+ .format({ estimatedCost: { format: 'money', currency: 'AUD' } })
406
491
  .build()
407
492
  });
493
+
494
+ // The settlement maths as a calculation: Recount checks each formula.
495
+ const calc = recount
496
+ .calculation('settlement', { currency: 'AUD' })
497
+ .input('excess', excess, { label: 'Policy excess', unit: 'AUD' });
498
+ for (const d of damage) {
499
+ calc.stated(undefined, d.component, {
500
+ value: d.estimatedCost,
501
+ source: 'Assessor estimate'
502
+ });
503
+ }
504
+ calc
505
+ .subtotal('total_damage', 'Total damage', "sum_kind('charge')", {
506
+ value: total
507
+ })
508
+ .total('settlement', 'Settlement', 'max(total_damage - excess, 0)', {
509
+ value: settlement
510
+ });
511
+ recount.addCalculation('Settlement', calc);
408
512
  if (total > 5_000) {
409
513
  recount.addAlert('High-value claim (>$5,000)', 'warn', {
410
514
  checks: [{ value: total }]
@@ -424,7 +528,7 @@ await recount.startTrace(
424
528
  });
425
529
 
426
530
  recount.addSpan('json', 'Outcome', {
427
- output: { decision: 'approved', settlement: total - excess }
531
+ output: { decision: 'approved', settlement }
428
532
  });
429
533
  }
430
534
  );
package/package.json CHANGED
@@ -1,9 +1,12 @@
1
1
  {
2
2
  "name": "@refactorlabs/recount",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "Node.js SDK for Recount",
5
5
  "homepage": "https://recount.refactor.gg",
6
6
  "license": "MIT",
7
+ "engines": {
8
+ "node": ">=18"
9
+ },
7
10
  "repository": {
8
11
  "type": "git",
9
12
  "url": "https://gitlab.com/refactor-labs/recount-node"
@@ -140,7 +140,7 @@ For each one:
140
140
 
141
141
  4. **Use the table builder properly** for any rule/comparison output - `.highlightRows()` /
142
142
  `.highlightCells()` for pass/fail or good/bad framing, `.summary()` for a rolled-up total,
143
- `.transformValues()` for currency/percent formatting. Look at
143
+ `.transformValues()` for currency/percentage formatting. Look at
144
144
  `examples/loan-eligibility.ts` and `examples/insurance-claim.ts` in this repo for the target
145
145
  quality bar - each rule/factor becomes a table row with a real highlight derived from the
146
146
  actual comparison in the code, not a hardcoded colour.
@@ -176,8 +176,9 @@ For each one:
176
176
  8. **Every name is prose, not code** - trace names, span names, group names, table/column titles,
177
177
  alert labels. Write them the way you'd say them out loud: `'Credit assessment'`, not
178
178
  `creditAssessment` or `CREDIT_CHECK`. No camelCase, no snake_case, no identifier casing left
179
- over from a variable name. Same for `metadata` keys shown in the dashboard - `'Application ID'`,
180
- not `applicationId`.
179
+ over from a variable name. Same for `metadata` keys and values shown in the dashboard -
180
+ `'Application ID'`, not `applicationId` - and for environment names: `'Production'`, not
181
+ `production`.
181
182
 
182
183
  ## Step 5 - Validate
183
184
 
@@ -185,7 +186,7 @@ Run the project's typecheck/build (`npm run typecheck` or equivalent - check `pa
185
186
  scripts) after editing. Fix any type errors from span option shapes before considering the work
186
187
  done - the SDK's types are strict about which options apply to which span type.
187
188
 
188
- ## Step 6 - Summarize
189
+ ## Step 6 - Summarise
189
190
 
190
191
  List what got instrumented: function → trace name → spans added → what's redacted. Don't commit
191
192
  unless asked.