@refactorlabs/recount 0.5.5

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.
@@ -0,0 +1,196 @@
1
+ ---
2
+ name: recount-instrument
3
+ description: Finds decision logic in a Node.js/TypeScript codebase (pricing, billing, discounts, access control, approvals, LLM calls) and instruments it with the @refactorlabs/recount SDK so it shows up as an interactive trace timeline in the Recount dashboard. Use when the user asks to "add recount tracing", "instrument this with recount", "trace this decision", "make this explainable", or wants an audit trail on business logic. Not for generic APM/error tracking - that's not what this SDK is for.
4
+ ---
5
+
6
+ # Recount instrumentation
7
+
8
+ You are adding `@refactorlabs/recount` tracing to a codebase that doesn't have it yet, or extending
9
+ existing coverage. The SDK turns a function's internal logic into a timeline of named spans a
10
+ non-engineer can read - the goal is a trace that _explains a decision_, not a trace that logs
11
+ everything.
12
+
13
+ Full API reference: read `node_modules/@refactorlabs/recount/llms.md` if present, otherwise fetch
14
+ it from the package. Do not guess at the API - the builders (`table()`, `chart()`) and span option
15
+ shapes are specific. Read that file before writing any span code if you haven't already this
16
+ session.
17
+
18
+ ## Step 1 - Check setup
19
+
20
+ Look for `@refactorlabs/recount` in `package.json`. If missing:
21
+
22
+ ```bash
23
+ npm install @refactorlabs/recount
24
+ ```
25
+
26
+ Check for `RECOUNT_API_KEY` in `.env` / `.env.example`. If the user hasn't provided one, tell them
27
+ the SDK is safe to wire up without it - with no key, all calls become no-ops (see "Install & init"
28
+ in llms.md). Don't block instrumentation work on having a live key.
29
+
30
+ No wrapper module is required - `recount.init()` reads env vars automatically. Only suggest a
31
+ custom wrapper (an `active` flag + passthrough functions) if the codebase needs
32
+ `wrapCollection`/`wrapAnthropic` to also no-op cleanly in tests or local dev without a key set.
33
+
34
+ ## Step 2 - Find candidate decision points
35
+
36
+ Don't instrument everything. Search for functions that make a _decision_ - something a customer,
37
+ auditor, or support agent might later ask "why did this happen?" about. Signals to grep/read for,
38
+ roughly in order of strength:
39
+
40
+ - **Function names** matching decision verbs: `calculate*`, `compare*`, `apply*Discount`,
41
+ `check*`, `validate*`, `filter*`, `eligib*`, `approve*`, `resolve*`, `decide*`, `evaluate*`,
42
+ `price*`, `charge*`, `denyReason`, `canAccess*`
43
+ - **Branch density** - functions with multiple `if`/`else`/`switch`/ternary chains gating a
44
+ return value or a side effect. A function with one `if` guard clause is not a decision; a
45
+ function computing a result through five conditional rules is.
46
+ - **Money-shaped identifiers in scope**: `rate`, `charge`, `discount`, `fee`, `total`, `cost`,
47
+ `price`, `tax`, `gst`
48
+ - **PII-shaped identifiers**: `name`, `email`, `address`, `ssn`, `account`, `phone`, `dob` - these
49
+ don't make something a candidate on their own, but flag the fields you'll need to `redact` once
50
+ you do instrument nearby logic
51
+ - **LLM / external calls** already in the function - always worth wrapping (`wrapAnthropic`,
52
+ `wrapOpenAI`) rather than manual spans
53
+ - **Database queries that feed a decision** - a lookup or aggregation whose result is read by
54
+ branching logic downstream (a plan record, a customer's usage, a rate table). A query that just
55
+ serves a list to a UI isn't a candidate on its own.
56
+ - **Exported from a controller/route/handler** - the result crosses a system boundary, so a
57
+ dispute about it can't be resolved by re-reading the code alone
58
+
59
+ Build a short list: file, function name, one-line reason it qualifies. Do not start writing spans
60
+ yet.
61
+
62
+ ### Database queries specifically
63
+
64
+ Handle discovery differently for DB queries than for decision functions - it's a wrap-once choke
65
+ point, not a per-function scan.
66
+
67
+ **MongoDB** - grep for `.collection<...>(` / `db.collection(` / `MongoClient`. Find where
68
+ collection objects are constructed (usually a handful of call sites in a `db.ts`/`models/`
69
+ module, not scattered through business logic) and wrap each one there with `wrapCollection` from
70
+ `@refactorlabs/recount/mongodb`:
71
+
72
+ ```ts
73
+ import { wrapCollection } from '@refactorlabs/recount/mongodb';
74
+
75
+ const users = wrapCollection(db.collection('users'));
76
+ ```
77
+
78
+ That single wrap covers every `findOne`, `find`, `insertOne`, `updateOne`, `aggregate`, etc. called
79
+ against that collection from then on - `findOne`, `find`, `insertOne`, `insertMany`, `updateOne`,
80
+ `updateMany`, `deleteOne`, `deleteMany`, `replaceOne`, `findOneAndUpdate`, `findOneAndDelete`,
81
+ `aggregate`, `countDocuments`. Do not hand-write manual `addSpan('db', ...)` calls around
82
+ individual MongoDB queries once the collection is wrapped - that duplicates the trace. Pass
83
+ `redact: [...]` at wrap time for fields that shouldn't leave the app (e.g. `wrapCollection(col, {
84
+ redact: ['name'] })`), and use `recount.named('...')` immediately before a call if the default
85
+ span name (the collection/operation) isn't descriptive enough.
86
+
87
+ **Other databases** (Postgres via `pg`/Drizzle/Prisma, MySQL, etc.) - there's no auto-wrap helper,
88
+ so only add manual `recount.addSpan('db', name, { metadata: { table, queryType }, input: { query,
89
+ params }, output, redactParams })` at query call sites that sit inside a function you're already
90
+ instrumenting per Step 4, where the query result is what the decision hinges on. Don't blanket the
91
+ whole data layer.
92
+
93
+ ## Step 3 - Confirm scope with the user
94
+
95
+ Show the candidate list before touching code. Let the user pick which functions to instrument, or
96
+ confirm "all of these." Do not silently instrument the whole list, and do not expand scope to
97
+ files/functions not in the list without asking. If the user gave you a specific function or file
98
+ up front, skip straight to it and skip the broader repo scan.
99
+
100
+ ## Step 4 - Instrument each chosen function
101
+
102
+ For each one:
103
+
104
+ 1. **Wrap the entry point** in `recount.startTrace(name, options, async () => { ... })`. The trace
105
+ name should read like a ticket title (`Loan eligibility - ${applicationId}`), not a function
106
+ name. Put identifying context in `metadata` and a summary in `input`. If the decision is
107
+ regulated or long-lived (compliance, audit, dispute resolution), consider setting
108
+ `retentionPeriod` (`'1d' | '7d' | '30d' | '90d' | '1y'`, default `'30d'`) - don't set it for
109
+ routine/low-stakes traces, the default is fine.
110
+
111
+ 2. **Decompose the function's real steps into named spans** - don't wrap the whole body in one
112
+ span. Read the function and find its natural stages (a lookup, a calculation, a rule check, a
113
+ result). Each stage becomes one `addSpan` call. Mirror the actual branches and values already
114
+ in the code - never invent numbers, thresholds, or outcomes that aren't derived from the real
115
+ logic.
116
+
117
+ 3. **Pick the span type per stage**, from the actual reference table:
118
+
119
+ | Type | Use for |
120
+ | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- |
121
+ | `message` | Checkpoints, validation steps, plain text. Never dropped even if empty. |
122
+ | `json` | Structured data with no special rendering - config, parsed output, final decision |
123
+ | `table` | Any tabular/record data - use the `recount.table()` builder, not raw `json`, whenever the data is row-shaped (rules, line items, comparisons) |
124
+ | `chart` | Numeric trends or comparisons worth a visual |
125
+ | `http` | Outbound HTTP - use `recount.fetch()` for auto-tracing instead of a manual span |
126
+ | `llm` | LLM calls - use `wrapAnthropic`/`wrapOpenAI`, not manual spans, unless the client can't be wrapped |
127
+ | `db` | Database queries - use `wrapCollection` for MongoDB, manual `addSpan('db', ...)` otherwise |
128
+ | `image` | Inline images - generated content, screenshots |
129
+ | `group` (via `addGroup`) | Bundle a variable-length list of related spans (e.g. one span per line item) under a collapsible section |
130
+
131
+ A span with no `input` and no `output` is silently dropped - don't write a span that wouldn't
132
+ survive that check. If you want a guaranteed-visible checkpoint, use `addMessage` instead.
133
+
134
+ A trace holds at most 500 non-group spans (group spans themselves don't count, only their
135
+ children do). If a stage is "one span per record" over a loop that could run long (line items,
136
+ search results, plan comparisons), use `addGroup` with `limit` (keep first N) or `sample`
137
+ (random N, only above a `sampleThreshold`) instead of an unbounded span per iteration - see
138
+ llms.md's `addGroup` section for the full option set and worked examples. None of the files in
139
+ `examples/` in this repo use `addGroup` yet, so don't cite one as a reference.
140
+
141
+ 4. **Use the table builder properly** for any rule/comparison output - `.highlightRows()` /
142
+ `.highlightCells()` for pass/fail or good/bad framing, `.summary()` for a rolled-up total,
143
+ `.transformValues()` for currency/percent formatting. Look at
144
+ `examples/loan-eligibility.ts` and `examples/insurance-claim.ts` in this repo for the target
145
+ quality bar - each rule/factor becomes a table row with a real highlight derived from the
146
+ actual comparison in the code, not a hardcoded colour.
147
+
148
+ 5. **Add alerts on real thresholds already present in the code** (a `>=650` credit score check, a
149
+ `>40%` DTI cutoff) - don't invent thresholds that aren't already business rules in the
150
+ function. `alerts` take `gt`/`lt` against a `checks[].value`, optionally matched to a table
151
+ `target`.
152
+
153
+ 6. **Redact PII fields you flagged in Step 2** - either `recount.REDACTED` inline, or
154
+ `redact: [...]` on the span/table, or `redactParams` for db spans. Never trace a raw SSN, full
155
+ account number, or similar even if the surrounding code doesn't currently mask it.
156
+
157
+ Get the path semantics right - this is the part that actually protects data, so don't guess:
158
+ - On `addSpan`/`addGroup`, `redact` paths are **exact from the root**. `'name'` redacts only a
159
+ top-level `name` field - it does **not** reach `customer.name` or any other nested `name`.
160
+ To redact a nested field you must give its full dot path: `redact: ['customer.name',
161
+ 'customer.billing.accountNumber']`. If the traced object has `name` at multiple depths, list
162
+ every path - one root-level entry does not cover the rest.
163
+ - On the **table builder**, `.redact([...])` matches by **column key only** - dot paths are not
164
+ supported there, pass the bare key as it appears in the row object.
165
+ - HTTP spans already auto-redact `Authorization`, `Cookie`/`Set-Cookie`, `X-Api-Key`,
166
+ `X-Auth-Token`, `X-Api-Secret`, `X-Access-Token`, and `Proxy-Authorization` - don't add manual
167
+ redaction for these headers, it's redundant.
168
+
169
+ 7. **Name spans for what happened, not the function that ran it** - `'Credit assessment'`, not
170
+ `'runCreditCheck'`. The dashboard reader isn't looking at your source.
171
+
172
+ 8. **Every name is prose, not code** - trace names, span names, group names, table/column titles,
173
+ alert labels. Write them the way you'd say them out loud: `'Credit assessment'`, not
174
+ `creditAssessment` or `CREDIT_CHECK`. No camelCase, no snake_case, no identifier casing left
175
+ over from a variable name. Same for `metadata` keys shown in the dashboard - `'Application ID'`,
176
+ not `applicationId`.
177
+
178
+ ## Step 5 - Validate
179
+
180
+ Run the project's typecheck/build (`npm run typecheck` or equivalent - check `package.json`
181
+ scripts) after editing. Fix any type errors from span option shapes before considering the work
182
+ done - the SDK's types are strict about which options apply to which span type.
183
+
184
+ ## Step 6 - Summarize
185
+
186
+ List what got instrumented: function → trace name → spans added → what's redacted. Don't commit
187
+ unless asked.
188
+
189
+ ## Guardrails
190
+
191
+ - Never fabricate data in a span's `output` - it must come from a real variable in the function.
192
+ - Don't over-instrument: a straight-line function with no branching isn't a "decision," skip it.
193
+ - Don't duplicate an existing trace - if the function already calls `recount.*`, extend it, don't
194
+ wrap it again.
195
+ - If the repo already has a `recount.ts`/similar wrapper module (check `services/` or `lib/`),
196
+ use it instead of importing `@refactorlabs/recount` directly, to match existing conventions.